
    $hbA                    2   S r SSKJr  SSKrSSKJrJr  SSKJr  SSK	J
r
JrJr  SSKJr  SSKJrJrJr  SS	KJr  SS
KJr  SSKJr  SSKJrJrJrJr  SSKJr  \
(       a  SSK J!r!J"r"  \#r$\%\   r&\\$\&4   r'\\\&4   r( " S S\SS9r) " S S\\$\&4   \5      r*g)a  **Retriever** class returns Documents given a text **query**.

It is more general than a vector store. A retriever does not need to be able to
store documents, only to return (or retrieve) it. Vector stores can be used as
the backbone of a retriever, but there are other types of retrievers as well.

**Class hierarchy:**

.. code-block::

    BaseRetriever --> <name>Retriever  # Examples: ArxivRetriever, MergerRetriever

**Main helpers:**

.. code-block::

    RetrieverInput, RetrieverOutput, RetrieverLike, RetrieverOutputLike,
    Document, Serializable, Callbacks,
    CallbackManagerForRetrieverRun, AsyncCallbackManagerForRetrieverRun
    )annotationsN)ABCabstractmethod)	signature)TYPE_CHECKINGAnyOptional)
ConfigDict)Self	TypedDictoverride)
deprecated)	Callbacks)Document)RunnableRunnableConfigRunnableSerializableensure_config)run_in_executor)#AsyncCallbackManagerForRetrieverRunCallbackManagerForRetrieverRunc                  H    \ rS rSr% SrS\S'    S\S'    S\S'    S\S'   S	rg
)LangSmithRetrieverParams7   z!LangSmith parameters for tracing.strls_retriever_nameOptional[str]ls_vector_store_providerls_embedding_providerls_embedding_model N)__name__
__module____qualname____firstlineno____doc____annotations____static_attributes__r!       Q/var/www/html/shao/venv/lib/python3.13/site-packages/langchain_core/retrievers.pyr   r   7   s)    +++ ((%%r)   r   F)totalc                    ^  \ rS rSr% Sr\" SS9rSrS\S'   Sr	S\S'   S	r
S
\S'    S	rS\S'    \SU 4S jj5       rSS jr\ S       S S jj5       r\ S       S S jj5       r\      S!S j5       r      S"S jr\" SSSS9S	S	S	S	S.             S#S jj5       r\" SSSS9S	S	S	S	S.             S#S jj5       rSrU =r$ )$BaseRetrieverD   a|  Abstract base class for a Document retrieval system.

A retrieval system is defined as something that can take string queries and return
the most 'relevant' Documents from some source.

Usage:

A retriever follows the standard Runnable interface, and should be used
via the standard Runnable methods of `invoke`, `ainvoke`, `batch`, `abatch`.

Implementation:

When implementing a custom retriever, the class should implement
the `_get_relevant_documents` method to define the logic for retrieving documents.

Optionally, an async native implementations can be provided by overriding the
`_aget_relevant_documents` method.

Example: A retriever that returns the first 5 documents from a list of documents

    .. code-block:: python

        from langchain_core.documents import Document
        from langchain_core.retrievers import BaseRetriever

        class SimpleRetriever(BaseRetriever):
            docs: list[Document]
            k: int = 5

            def _get_relevant_documents(self, query: str) -> list[Document]:
                """Return the first k documents from the list of documents"""
                return self.docs[:self.k]

            async def _aget_relevant_documents(self, query: str) -> list[Document]:
                """(Optional) async native implementation."""
                return self.docs[:self.k]

Example: A simple retriever based on a scikit-learn vectorizer

    .. code-block:: python

        from sklearn.metrics.pairwise import cosine_similarity

        class TFIDFRetriever(BaseRetriever, BaseModel):
            vectorizer: Any
            docs: list[Document]
            tfidf_array: Any
            k: int = 4

            class Config:
                arbitrary_types_allowed = True

            def _get_relevant_documents(self, query: str) -> list[Document]:
                # Ip -- (n_docs,x), Op -- (n_docs,n_Feats)
                query_vec = self.vectorizer.transform([query])
                # Op -- (n_docs,1) -- Cosine Sim with each doc
                results = cosine_similarity(self.tfidf_array, query_vec).reshape((-1,))
                return [self.docs[i] for i in results.argsort()[-self.k :][::-1]]

T)arbitrary_types_allowedFbool_new_arg_supported_expects_other_argsNOptional[list[str]]tagsOptional[dict[str, Any]]metadatac                  > [         TU ]  " S
0 UD6  U R                  [        R                  :w  aA  [        R
                  " S[        SS9  U R                  n[        R                  U l        X l        [        U S5      (       a_  U R                  [        R                  :w  aA  [        R
                  " S[        SS9  U R                  n[        R                  U l	        X0l
        [        U R                  5      R                  nUR                  S5      S LU l        U R                  (       d/  U R                  [        R                  :X  a        SS jnXPl
        [        [!        UR#                  5       5      1 Sk-
  5      S	:  U l        g )NzgRetrievers must implement abstract `_get_relevant_documents` method instead of `get_relevant_documents`   )
stacklevelaget_relevant_documentsziRetrievers must implement abstract `_aget_relevant_documents` method instead of `aget_relevant_documents`run_managerc                L   #    [        S U R                  U5      I S h  vN $  N7fN)r   _get_relevant_documents)selfquerys     r*   _aget_relevant_documentsABaseRetriever.__init_subclass__.<locals>._aget_relevant_documents   s#      -T43O3OQVWWWWs   $"$>   r?   r@   r;   r   r!   )r?   r   r@   r   returnlist[Document])super__init_subclass__get_relevant_documentsr-   warningswarnDeprecationWarningr>   hasattrr:   rA   r   
parametersgetr1   lensetkeysr2   )clskwargsswapaswaprL   rA   	__class__s         r*   rF   BaseRetriever.__init_subclass__   sa   !+F+ %%)M)MMMM7"	 --D44 & +/'C233++}/T/TTMM8"	 //E55 ' ,1(s::;FF
!+!>d!J&&,,0V0VVXX#&XX
 ,D( JOO%&)IIJQN 	r)   c                    U R                  5       nUR                  S5      (       a  USS nOUR                  S5      (       a  USS nUR                  5       n[	        US9$ )z Get standard params for tracing.	Retriever	   Ni)r   )get_name
startswithendswithlowerr   )r?   _kwargsdefault_retriever_names      r*   _get_ls_paramsBaseRetriever._get_ls_params   se    !%!,,[99%;AB%?"#,,[99%;CR%@"!7!=!=!?':PQQr)   c           
        SSK Jn  [        U5      n0 UR                  S5      =(       d    0 EU R                  " S0 UD6EnUR                  UR                  S5      SUR                  SS5      UR                  S5      U R                  UU R                  S	9nUR                  SUUR                  S
5      =(       d    U R                  5       UR                  SS5      S9n U R                  (       a  UO0 nU R                  (       a  U R                  " U4SU0UD6n	OU R                  " U40 UD6n	UR                  U	5        U	$ ! [         a  n
UR!                  U
5        e Sn
A
ff = f)at  Invoke the retriever to get relevant documents.

Main entry point for synchronous retriever invocations.

Args:
    input: The query string.
    config: Configuration for the retriever. Defaults to None.
    kwargs: Additional arguments to pass to the retriever.

Returns:
    List of relevant documents.

Examples:

.. code-block:: python

    retriever.invoke("query")

r   )CallbackManagerr6   	callbacksNverboseFr4   re   inheritable_tags
local_tagsinheritable_metadatalocal_metadatarun_namerun_idnamerl   r;   r!   ) langchain_core.callbacks.managerrc   r   rM   r`   	configurer4   r6   on_retriever_startrZ   popr2   r1   r>   on_retriever_end	Exceptionon_retriever_error)r?   inputconfigrR   rc   ri   callback_managerr;   kwargs_resultes              r*   invokeBaseRetriever.invoke   sn   . 	Ev& 
zz*%+ 
!!+F+ 
 +44JJ{#JJy%0#ZZ/yy!5== 5 
 '99J':4==?::h-	 : 
	 $ 8 8fbG&&55'26= 55eGwG
 (( M  	**1-	s    AE 
E#EE#c           
     6  #    SSK Jn  [        U5      n0 UR                  S5      =(       d    0 EU R                  " S0 UD6EnUR                  UR                  S5      SUR                  SS5      UR                  S5      U R                  UU R                  S	9nUR                  SUUR                  S
5      =(       d    U R                  5       UR                  SS5      S9I Sh  vN n U R                  (       a  UO0 nU R                  (       a  U R                  " U4SU0UD6I Sh  vN n	OU R                  " U40 UD6I Sh  vN n	UR                  U	5      I Sh  vN   U	$  N N= N# N! [         a   n
UR!                  U
5      I Sh  vN    e Sn
A
ff = f7f)a  Asynchronously invoke the retriever to get relevant documents.

Main entry point for asynchronous retriever invocations.

Args:
    input: The query string.
    config: Configuration for the retriever. Defaults to None.
    kwargs: Additional arguments to pass to the retriever.

Returns:
    List of relevant documents.

Examples:

.. code-block:: python

    await retriever.ainvoke("query")

r   )AsyncCallbackManagerr6   rd   Nre   Fr4   rf   rk   rl   rm   r;   r!   )ro   r   r   rM   r`   rp   r4   r6   rq   rZ   rr   r2   r1   rA   rs   rt   ru   )r?   rv   rw   rR   r   ri   rx   r;   ry   rz   r{   s              r*   ainvokeBaseRetriever.ainvoke  s    4 	Jv& 
zz*%+ 
!!+F+ 
 099JJ{#JJy%0#ZZ/yy!5== : 
 -??J':4==?::h-	 @ 
 
	 $ 8 8fbG&&#<< '2 6=    $<<UNgNN
 ..   M+
 O
	  	00333	sx   C"F$E$%F*>E, (E&)E, E(E, 	FE*F&E, (E, *F,
F6F
FFFFc                   g)zGet documents relevant to a query.

Args:
    query: String to find relevant documents for.
    run_manager: The callback handler to use.

Returns:
    List of relevant documents.
Nr!   r?   r@   r;   s      r*   r>   %BaseRetriever._get_relevant_documentsT  s    r)   c               f   #    [        SU R                  UUR                  5       S9I Sh  vN $  N7f)zAsynchronously get documents relevant to a query.

Args:
    query: String to find relevant documents for
    run_manager: The callback handler to use
Returns:
    List of relevant documents
N)r;   )r   r>   get_syncr   s      r*   rA   &BaseRetriever._aget_relevant_documentsb  s9      %((#,,.	
 
 	
 
s   (1/1z0.1.46r|   z1.0)sincealternativeremoval)rd   r4   r6   rk   c                   0 nU(       a  X'S'   U(       a  X7S'   U(       a  XGS'   U(       a  XWS'   U R                   " X40 UD6$ )a}  Retrieve documents relevant to a query.

Users should favor using `.invoke` or `.batch` rather than
`get_relevant_documents directly`.

Args:
    query: string to find relevant documents for.
    callbacks: Callback manager or list of callbacks. Defaults to None.
    tags: Optional list of tags associated with the retriever.
        These tags will be associated with each call to this retriever,
        and passed as arguments to the handlers defined in `callbacks`.
        Defaults to None.
    metadata: Optional metadata associated with the retriever.
        This metadata will be associated with each call to this retriever,
        and passed as arguments to the handlers defined in `callbacks`.
        Defaults to None.
    run_name: Optional name for the run. Defaults to None.
    kwargs: Additional arguments to pass to the retriever.

Returns:
    List of relevant documents.
rd   r4   r6   rk   )r|   r?   r@   rd   r4   r6   rk   rR   rw   s           r*   rG   $BaseRetriever.get_relevant_documentst  sI    B "$"+;!6N!):!):{{53F33r)   r   c                  #    0 nU(       a  X'S'   U(       a  X7S'   U(       a  XGS'   U(       a  XWS'   U R                   " X40 UD6I Sh  vN $  N7f)ax  Asynchronously get documents relevant to a query.

Users should favor using `.ainvoke` or `.abatch` rather than
`aget_relevant_documents directly`.

Args:
    query: string to find relevant documents for.
    callbacks: Callback manager or list of callbacks.
    tags: Optional list of tags associated with the retriever.
        These tags will be associated with each call to this retriever,
        and passed as arguments to the handlers defined in `callbacks`.
        Defaults to None.
    metadata: Optional metadata associated with the retriever.
        This metadata will be associated with each call to this retriever,
        and passed as arguments to the handlers defined in `callbacks`.
        Defaults to None.
    run_name: Optional name for the run. Defaults to None.
    kwargs: Additional arguments to pass to the retriever.

Returns:
    List of relevant documents.
rd   r4   r6   rk   N)r   r   s           r*   r:   %BaseRetriever.aget_relevant_documents  sR     B "$"+;!6N!):!):\\%:6::::s   AAAAr!   )rR   r   rC   None)r^   r   rC   r   r=   )rv   r   rw   zOptional[RunnableConfig]rR   r   rC   rD   )r@   r   r;   r   rC   rD   )r@   r   r;   r   rC   rD   )r@   r   rd   r   r4   r3   r6   r5   rk   r   rR   r   rC   rD   )r"   r#   r$   r%   r&   r
   model_configr1   r'   r2   r4   r6   r   rF   r`   r|   r   r   r>   rA   r   rG   r:   r(   __classcell__)rU   s   @r*   r-   r-   D   s   ;z  $L  %$ %% $D
$ *.H&- 0
 0
d	R =A;;":;MP;	; ;z  ,0>> )> 	>
 
> >@ *H	 

*M
	
$ hHeD
  $$(-1"&)4)4 	)4
 ")4 +)4  )4 )4 
)4 E)4V hIuE
  $$(-1"&);); 	);
 "); +);  ); ); 
); F);r)   r-   )+r&   
__future__r   rH   abcr   r   inspectr   typingr   r   r	   pydanticr
   typing_extensionsr   r   r   langchain_core._apir   langchain_core.callbacksr   langchain_core.documentsr   langchain_core.runnablesr   r   r   r   langchain_core.runnables.configr   ro   r   r   r   RetrieverInputlistRetrieverOutputRetrieverLikeRetrieverOutputLiker   r-   r!   r)   r*   <module>r      s   * #  #  / /  7 7 * . -  <
 x.89sO34 
y 
F;()HI3 F;r)   