
    @h8                       S r SSKJr  SSKJr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  SSKJr   " S	 S
\5      r " S S\5      r          SS jr        SS jr        SS jr\	" SSSS9 " S S\5      5       rg)z=Combine many documents together by recursively reducing them.    )annotations)AnyCallableOptionalProtocol)
deprecated)	Callbacks)Document)
ConfigDict)BaseCombineDocumentsChainc                  "    \ rS rSrSrSS jrSrg)CombineDocsProtocol   &Interface for the combine_docs method.c                    g)r   N selfdocskwargss      a/var/www/html/shao/venv/lib/python3.13/site-packages/langchain/chains/combine_documents/reduce.py__call__CombineDocsProtocol.__call__   s        r   Nr   list[Document]r   r   returnstr__name__
__module____qualname____firstlineno____doc__r   __static_attributes__r   r   r   r   r      s
    05r   r   c                  "    \ rS rSrSrSS jrSrg)AsyncCombineDocsProtocol   r   c                   #    g7f)z,Async interface for the combine_docs method.Nr   r   s      r   r   !AsyncCombineDocsProtocol.__call__   s     s   r   Nr   r   r   r   r   r'   r'      s
    0;r   r'   c                    / n/ nU  HY  nUR                  U5        U" U40 UD6nXr:  d  M$  [        U5      S:X  a  Sn[        U5      eUR                  USS 5        USS nM[     UR                  U5        U$ )a  Split Documents into subsets that each meet a cumulative length constraint.

Args:
    docs: The full list of Documents.
    length_func: Function for computing the cumulative length of a set of Documents.
    token_max: The maximum cumulative length of any subset of Documents.
    **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_docsr8      s    $ $!"2=f="#$).  !o%&&'7'<=/4  /0r   c                J   U" U 40 UD6nU S   R                   R                  5        VVs0 sH  u  pEU[        U5      _M     nnnU SS  HI  nUR                   R                  5        H(  u  pEXF;   a  Xd==   SU 3-  ss'   M  [        U5      Xd'   M*     MK     [        X6S9$ s  snnf )  Execute a collapse function on a set of documents and merge their metadatas.

Args:
    docs: A list of Documents to combine.
    combine_document_func: A function that takes in a list of Documents 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r>   itemsr   r
   r   combine_document_funcr   resultkvcombined_metadatar5   s           r   collapse_docsrG   A   s    * #4262F/3Aw/?/?/E/E/GH/GtqCF/GHABxLL&&(DA%!$"QC0$'*1v!$	 )  DD Is   Bc                f  #    U" U 40 UD6I Sh  vN nU S   R                   R                  5        VVs0 sH  u  pEU[        U5      _M     nnnU SS  HI  nUR                   R                  5        H(  u  pEXF;   a  Xd==   SU 3-  ss'   M  [        U5      Xd'   M*     MK     [        X6S9$  Ns  snnf 7f)r:   Nr   r,   r;   r<   r?   rA   s           r   acollapse_docsrI   a   s     * )888F/3Aw/?/?/E/E/GH/GtqCF/GHABxLL&&(DA%!$"QC0$'*1v!$	 )  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                     \ rS rSr% SrS\S'    SrS\S'    SrS	\S
'    SrS\S'    \	" SSS9r
\SS j5       r  S         SS jjr  S         SS jjr  S         SS jjr  S         SS jjr\SS j5       rSrg)ReduceDocumentsChain   a	  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:
    .. code-block:: python

        from langchain.chains import (
            StuffDocumentsChain, LLMChain, ReduceDocumentsChain
        )
        from langchain_core.prompts import PromptTemplate
        from langchain_community.llms 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"
        llm = 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=llm, 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=llm, 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#Optional[BaseCombineDocumentsChain]collapse_documents_chaini  intr2   Optional[int]collapse_max_retriesTforbid)arbitrary_types_allowedextrac                L    U R                   b  U R                   $ U R                  $ )N)rQ   rP   r   s    r   _collapse_chain$ReduceDocumentsChain._collapse_chain   s&    ((4000+++r   c                p    U R                   " U4UUS.UD6u  pVU R                  R                  " SUUS.UD6$ )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.
r2   	callbacksr   r^   r   )	_collapserP   combine_docsr   r   r2   r^   r   result_docsextra_return_dicts          r   ra   !ReduceDocumentsChain.combine_docs   s]    , *.*
*
 	*
& ++88 

 
 	
r   c                   #    U R                   " U4UUS.UD6I Sh  vN u  pVU R                  R                  " SUUS.UD6I Sh  vN $  N- N7f)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.
r]   Nr_   r   )
_acollapserP   acombine_docsrb   s          r   rh   "ReduceDocumentsChain.acombine_docs  st     , 040
0
 	0
 *
& 11?? 

 
 
 	
*

s!   AA
(AAAAc                  ^ ^ UnT R                   R                  nU" U40 UD6nSUU 4S jjnU=(       d    T R                  n	Sn
Ub  Xy:  a  [        UUU	40 UD6nU Vs/ sH  n[	        X40 UD6PM     nnU" U40 UD6nU
S-  n
T R
                  (       a.  U
T R
                  :X  a  ST R
                   SU	 S3n[        U5      eUb  Xy:  a  M  U0 4$ s  snf )Nc                B   > TR                   R                  " SU TS.UD6$ N)input_documentsr^   r   )rZ   runr   r   r^   r   s     r   _collapse_docs_func;ReduceDocumentsChain._collapse.<locals>._collapse_docs_func8  s1    ''++  $#  r   r   r,   Exceed 7 tries to                         collapse document to  tokens.r   )rP   prompt_lengthr2   r8   rG   rT   r0   r   r   r2   r^   r   rc   r1   
num_tokensrp   
_token_maxretriesr3   docs_r7   s   `  `          r   r`   ReduceDocumentsChain._collapse-  s    22@@ 77
	 	 0$..
$)@"4# 	# 10E eCFC0   %[;F;JqLG((W8Q8Q-Q 9 9: ;..8\C o%! $)@" Bs   Cc                  ^ ^#    UnT R                   R                  nU" U40 UD6nSUU 4S jjnU=(       d    T R                  n	Sn
Ub  Xy:  a  [        UUU	40 UD6nU Vs/ sH  n[	        X40 UD6I S h  vN PM     nnU" U40 UD6nU
S-  n
T R
                  (       a.  U
T R
                  :X  a  ST R
                   SU	 S3n[        U5      eUb  Xy:  a  M  U0 4$  Nes  snf 7f)Nc                ^   >#    TR                   R                  " SU TS.UD6I S h  vN $  N7frl   )rZ   arunro   s     r   rp   <ReduceDocumentsChain._acollapse.<locals>._collapse_docs_func_  s>     --22  $#    s   #-+-r   r,   rr   rs   rt   r   )rP   ru   r2   r8   rI   rT   r0   rv   s   `  `          r   rg   ReduceDocumentsChain._acollapseT  s'     22@@ 77
	 	 0$..
$)@"4# 	# 10E %UJ6JJJ0   %[;F;JqLG((W8Q8Q-Q 9 9: ;..8\C o%! $)@" B Ks1   AC! C4C
5C=AC!C!CC!c                    g)Nreduce_documents_chainr   rY   s    r   _chain_type ReduceDocumentsChain._chain_type{  s    'r   r   )r   r   )NN)
r   r   r2   rS   r^   r	   r   r   r   ztuple[str, dict])
r   r   r2   rS   r^   r	   r   r   r   ztuple[list[Document], dict])r   r   )r    r!   r"   r#   r$   __annotations__rQ   r2   rT   r   model_configpropertyrZ   ra   rh   r`   rg   r   r%   r   r   r   rN   rN      s~   AF 760DHAH0 IsG +/-.J  $L
 , , $(#	 
 
 ! 
 	 

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

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