
    3fi7                       d Z ddlmZ ddlmZ ddlmZmZ ddlm	Z	 ddl
mZ ddlmZ ddlmZ dd	lmZ  G d
 de      Z G d de      Z	 	 	 	 	 	 	 	 	 	 ddZ	 	 	 	 	 	 	 	 ddZ	 	 	 	 	 	 	 	 ddZ e	ddd       G d de             Zy)z=Combine many documents together by recursively reducing them.    )annotations)Callable)AnyProtocol)
deprecated)	Callbacks)Document)
ConfigDict)BaseCombineDocumentsChainc                      e Zd ZdZddZy)CombineDocsProtocol&Interface for the combine_docs method.c                     y)r   N selfdocskwargss      o/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langchain_classic/chains/combine_documents/reduce.py__call__zCombineDocsProtocol.__call__   s        Nr   list[Document]r   r   returnstr__name__
__module____qualname____doc__r   r   r   r   r   r      s
    05r   r   c                      e Zd ZdZddZy)AsyncCombineDocsProtocolr   c                   K   yw)z,Async interface for the combine_docs method.Nr   r   s      r   r   z!AsyncCombineDocsProtocol.__call__   s     s   Nr   r   r   r   r   r"   r"      s
    0;r   r"   c                    g }g }| D ]V  }|j                  |        ||fi |}||kD  s#t        |      dk(  rd}t        |      |j                  |dd        |dd }X |j                  |       |S )a  Split `Document` objects to subsets that each meet a cumulative len. constraint.

    Args:
        docs: The full list of `Document` objects.
        length_func: Function for computing the cumulative length of a set of `Document`
            objects.
        token_max: The maximum cumulative length of any subset of `Document` objects.
        **kwargs: Arbitrary additional keyword params to pass to each call of the
            `length_func`.

    Returns:
        A `list[list[Document]]`.
       zLA single document was longer than the context length, we cannot handle this.N)appendlen
ValueError)	r   length_func	token_maxr   new_result_doc_list_sub_result_docsdoc_num_tokensmsgs	            r   split_list_of_docsr1      s    &  5$!"2=f="#$).  !o%&&'7'<=/45 /0r   c                J    || fi |}| d   j                   j                         D ci c]  \  }}|t        |       }}}| dd D ]G  }|j                   j                         D ](  \  }}||v r||xx   d| z  cc<   t        |      ||<   * I t        ||      S c c}}w )  Execute a collapse function on a set of documents and merge their metadatas.

    Args:
        docs: A list of `Document` objects to combine.
        combine_document_func: A function that takes in a list of `Document` objects and
            optionally addition keyword parameters and combines them into a single
            string.
        **kwargs: Arbitrary additional keyword params to pass to the
            `combine_document_func`.

    Returns:
        A single `Document` with the output of `combine_document_func` for the page
            content and the combined metadata's of all the input documents. All metadata
            values are strings, and where there are overlapping keys across documents
            the values are joined by `', '`.
    r   r%   N, page_contentmetadatar7   itemsr   r	   r   combine_document_funcr   resultkvcombined_metadatar.   s           r   collapse_docsr@   C   s    * #4262F/3Aw/?/?/E/E/GHtq!CFHHABx .LL&&( 	.DAq%%!!$"QC0$'*1v!!$		.. 2CDD Is   Bc                f  K    || fi | d{   }| d   j                   j                         D ci c]  \  }}|t        |       }}}| dd D ]G  }|j                   j                         D ](  \  }}||v r||xx   d| z  cc<   t        |      ||<   * I t        ||      S 7 c c}}w w)r3   Nr   r%   r4   r5   r8   r:   s           r   acollapse_docsrB   c   s     * )888F/3Aw/?/?/E/E/GHtq!CFHHABx .LL&&( 	.DAq%%!!$"QC0$'*1v!!$		.. 2CDD 9Hs!   B1B)$B1B+
A B1+B1z0.3.1z1.0zThis class is deprecated. Please see the migration guide here for a recommended replacement: https://python.langchain.com/docs/versions/migrating_chains/map_reduce_chain/)sinceremovalmessagec                     e Zd ZU dZded<   	 dZded<   	 dZded	<   	 dZd
ed<   	  edd      Z	e
dd       Z	 	 d	 	 	 	 	 	 	 	 	 ddZ	 	 d	 	 	 	 	 	 	 	 	 ddZ	 	 d	 	 	 	 	 	 	 	 	 ddZ	 	 d	 	 	 	 	 	 	 	 	 ddZe
dd       Zy)ReduceDocumentsChaina	  Combine documents by recursively reducing them.

    This involves

    - `combine_documents_chain`
    - `collapse_documents_chain`

    `combine_documents_chain` is ALWAYS provided. This is final chain that is called.

    We pass all previous results to this chain, and the output of this chain is
    returned as a final result.

    `collapse_documents_chain` is used if the documents passed in are too many to all
    be passed to `combine_documents_chain` in one go. In this case,
    `collapse_documents_chain` is called recursively on as big of groups of documents
    as are allowed.

    Example:
        ```python
        from langchain_classic.chains import (
            StuffDocumentsChain,
            LLMChain,
            ReduceDocumentsChain,
        )
        from langchain_core.prompts import PromptTemplate
        from langchain_openai import OpenAI

        # This controls how each document will be formatted. Specifically,
        # it will be passed to `format_document` - see that function for more
        # details.
        document_prompt = PromptTemplate(
            input_variables=["page_content"], template="{page_content}"
        )
        document_variable_name = "context"
        model = OpenAI()
        # The prompt here should take as an input variable the
        # `document_variable_name`
        prompt = PromptTemplate.from_template("Summarize this content: {context}")
        llm_chain = LLMChain(llm=model, prompt=prompt)
        combine_documents_chain = StuffDocumentsChain(
            llm_chain=llm_chain,
            document_prompt=document_prompt,
            document_variable_name=document_variable_name,
        )
        chain = ReduceDocumentsChain(
            combine_documents_chain=combine_documents_chain,
        )
        # If we wanted to, we could also pass in collapse_documents_chain
        # which is specifically aimed at collapsing documents BEFORE
        # the final call.
        prompt = PromptTemplate.from_template("Collapse this content: {context}")
        llm_chain = LLMChain(llm=model, prompt=prompt)
        collapse_documents_chain = StuffDocumentsChain(
            llm_chain=llm_chain,
            document_prompt=document_prompt,
            document_variable_name=document_variable_name,
        )
        chain = ReduceDocumentsChain(
            combine_documents_chain=combine_documents_chain,
            collapse_documents_chain=collapse_documents_chain,
        )
        ```
    r   combine_documents_chainNz BaseCombineDocumentsChain | Nonecollapse_documents_chaini  intr+   
int | Nonecollapse_max_retriesTforbid)arbitrary_types_allowedextrac                J    | j                   | j                   S | j                  S )N)rI   rH   r   s    r   _collapse_chainz$ReduceDocumentsChain._collapse_chain   s&    ((4000+++r   c                r     | j                   |f||d|\  }} | j                  j                  d||d|S )a  Combine multiple documents recursively.

        Args:
            docs: List of documents to combine, assumed that each one is less than
                `token_max`.
            token_max: Recursively creates groups of documents less than this number
                of tokens.
            callbacks: Callbacks to be passed through
            **kwargs: additional parameters to be passed to LLM calls (like other
                input variables besides the documents)

        Returns:
            The first element returned is the single string output. The second
                element returned is a dictionary of other keys to return.
        r+   	callbacksr   rU   r   )	_collapserH   combine_docsr   r   r+   rU   r   result_docs_s          r   rX   z!ReduceDocumentsChain.combine_docs   sb    , (

 	
Q 9t++88 

 
 	
r   c                   K    | j                   |f||d| d{   \  }} | j                  j                  d||d| d{   S 7 .7 w)a  Async combine multiple documents recursively.

        Args:
            docs: List of documents to combine, assumed that each one is less than
                `token_max`.
            token_max: Recursively creates groups of documents less than this number
                of tokens.
            callbacks: Callbacks to be passed through
            **kwargs: additional parameters to be passed to LLM calls (like other
                input variables besides the documents)

        Returns:
            The first element returned is the single string output. The second
                element returned is a dictionary of other keys to return.
        rT   NrV   r   )
_acollapserH   acombine_docsrY   s          r   r^   z"ReduceDocumentsChain.acombine_docs  s|     ,  /t 
 
 	 
 
Q @T11?? 

 
 
 	


s!   AA)AAAAc                    |} j                   j                  } ||fi |}d fd}|xs  j                  }	d}
||||	kD  rwt        |||	fi |}|D cg c]  }t	        ||fi | }} ||fi |}|
dz  }
 j
                  r-|
 j
                  k(  rd j
                   d|	 d}t        |      |||	kD  rw|i fS c c}w )Nc                B     j                   j                  d| d|S N)input_documentsrU   r   )rR   runr   r   rU   r   s     r   _collapse_docs_funcz;ReduceDocumentsChain._collapse.<locals>._collapse_docs_func@  s3    +4''++  $#  r   r   r%   Exceed 7 tries to                         collapse document to  tokens.r   )rH   prompt_lengthr+   r1   r@   rL   r)   r   r   r+   rU   r   rZ   r*   
num_tokensre   
_token_maxretriesr,   docs_r0   s   `  `          r   rW   zReduceDocumentsChain._collapse5  s    22@@ 77
	 0$..
$j)@"4# 	# 1 e%8CFCK  %[;F;JqLG((W8Q8Q-Q 9 9: ;..8\C o%! $j)@" Bs   B?c                   K   |} j                   j                  } ||fi |}d fd}|xs  j                  }	d}
|||	kD  rt        |||	fi |}|D cg c]  }t	        ||fi | d {    }} ||fi |}|
dz  }
 j
                  r-|
 j
                  k(  rd j
                   d|	 d}t        |      |||	kD  r|i fS 7 [c c}w w)Nc                ^   K    j                   j                  d| d| d {   S 7 wra   )rR   arunrd   s     r   re   z<ReduceDocumentsChain._acollapse.<locals>._collapse_docs_funcg  sA     2--22  $#    s   #-+-r   r%   rf   rg   rh   r   )rH   ri   r+   r1   rB   rL   r)   rj   s   `  `          r   r]   zReduceDocumentsChain._acollapse\  s'     22@@ 77
	 0$..
$j)@"4# 	# 1 %U,?J6JJJK  %[;F;JqLG((W8Q8Q-Q 9 9: ;..8\C o%! $j)@" B Ks1   ACC-C	
.C4ACC	CCc                     y)Nreduce_documents_chainr   rQ   s    r   _chain_typez ReduceDocumentsChain._chain_type  s    'r   )r   r   )NN)
r   r   r+   rK   rU   r   r   r   r   ztuple[str, dict])
r   r   r+   rK   rU   r   r   r   r   ztuple[list[Document], dict])r   r   )r   r   r   r    __annotations__rI   r+   rL   r
   model_configpropertyrR   rX   r^   rW   r]   rt   r   r   r   rG   rG      s   >@ 76 BF>E
 Is
 (,*+  $L
 , , !%#	 
 
  
 	 

  
 
 
J !%#	 
 
  
 	 

  
 
 
J !%#	%% % 	%
 % 
%%T !%#	%% % 	%
 % 
%%N ( (r   rG   N)
r   r   r*   r   r+   rJ   r   r   r   zlist[list[Document]])r   r   r;   r   r   r   r   r	   )r   r   r;   r"   r   r   r   r	   )r    
__future__r   collections.abcr   typingr   r   langchain_core._apir   langchain_core.callbacksr   langchain_core.documentsr	   pydanticr
   /langchain_classic.chains.combine_documents.baser   r   r"   r1   r@   rB   rG   r   r   r   <module>r      s    C " $   * . -  U5( 5;x ;"
"" " 	"
 "JE
E.E E 	E@E
E3E E 	E@ 
	X	y(4 y(y(r   