o
    JjgO7                     @  s   d Z ddlmZ ddlmZmZmZmZ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
 d
eZG dd deZd&ddZd'ddZd(ddZedd d!d"G d#d$ d$eZd%S ))z=Combine many documents together by recursively reducing them.    )annotations)AnyCallableListOptionalProtocolTuple)
deprecated)	Callbacks)Document)
ConfigDict)BaseCombineDocumentsChainc                   @     e Zd ZdZddd	Zd
S )CombineDocsProtocol&Interface for the combine_docs method.docsList[Document]kwargsr   returnstrc                 K     dS )r   N selfr   r   r   r   a/var/www/html/zoom/venv/lib/python3.10/site-packages/langchain/chains/combine_documents/reduce.py__call__   s    zCombineDocsProtocol.__call__Nr   r   r   r   r   r   __name__
__module____qualname____doc__r   r   r   r   r   r          r   c                   @  r   )AsyncCombineDocsProtocolr   r   r   r   r   r   r   c                   s   dS )z,Async interface for the combine_docs method.Nr   r   r   r   r   r      s    z!AsyncCombineDocsProtocol.__call__Nr   r   r   r   r   r   r#      r"   r#   r   r   length_funcr   	token_maxintr   r   r   List[List[Document]]c                 K  st   g }g }| D ],}| | ||fi |}||kr2t|dkr#td| |dd  |dd }q| | |S )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   r$   r%   r   new_result_doc_list_sub_result_docsdoc_num_tokensr   r   r   split_list_of_docs   s   

r1   combine_document_funcr   c                 K  s   || fi |}dd | d j  D }| dd D ]"}|j  D ]\}}||v r5||  d| 7  < q!t|||< q!qt||dS )  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 ", ".
    c                 S     i | ]	\}}|t |qS r   r   .0kvr   r   r   
<dictcomp>S       z!collapse_docs.<locals>.<dictcomp>r   r(   N, page_contentmetadatar?   itemsr   r   r   r2   r   resultcombined_metadatar/   r8   r9   r   r   r   collapse_docs=   s   rE   c                   s   || fi |I dH }dd | d j  D }| dd D ]"}|j  D ]\}}||v r9||  d| 7  < q%t|||< q%qt||dS )r3   Nc                 S  r4   r   r5   r6   r   r   r   r:   s   r;   z"acollapse_docs.<locals>.<dictcomp>r   r(   r<   r=   r@   rB   r   r   r   acollapse_docs]   s   rF   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                   @  s   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dZ	e
d%ddZ		d&d'ddZ		d&d'ddZ		d&d(ddZ		d&d(d d!Ze
d)d#d$ZdS )*ReduceDocumentsChainay
  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  r&   r%   Optional[int]collapse_max_retriesTforbid)arbitrary_types_allowedextrar   c                 C  s   | j d ur| j S | jS )N)rL   rK   r   r   r   r   _collapse_chain   s   
z$ReduceDocumentsChain._collapse_chainr   r   	callbacksr
   r   r   Tuple[str, dict]c                 K  s4   | 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%   rT   r   rT   Nr   )	_collapserK   combine_docsr   r   r%   rT   r   result_docsextra_return_dictr   r   r   rY      s   
z!ReduceDocumentsChain.combine_docsc                   sB   | j |f||d|I dH \}}| jjd||d|I dH S )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.
        rV   NrW   r   )
_acollapserK   acombine_docsrZ   r   r   r   r^     s   z"ReduceDocumentsChain.acombine_docsTuple[List[Document], dict]c                   s   |}j j}||fi |}d fdd}|pj}	d	}
|d url||	krlt|||	fi |}g }|D ]}t||fi |}|| q3||fi |}|
d
7 }
jrd|
jkrdtdj d|	 d|d url||	ks%|i fS )Nr   r   r   r   r   r   c                   s   j jd|  d|S N)input_documentsrT   r   )rS   runr   r   rT   r   r   r   _collapse_docs_func+  s
   z;ReduceDocumentsChain._collapse.<locals>._collapse_docs_funcr   r(   Exceed 7 tries to                         collapse document to  tokens.r   )rK   prompt_lengthr%   r1   rE   r*   rN   r,   r   r   r%   rT   r   r[   r$   
num_tokensre   
_token_maxretriesr-   new_docr   rd   r   rX      s4   

zReduceDocumentsChain._collapsec                   s   |}j j}||fi |}d fdd}|pj}	d	}
|d urp||	krpt|||	fi |}g }|D ]}t||fi |I d H }|| q4||fi |}|
d
7 }
jrh|
jkrhtdj d|	 d|d urp||	ks&|i fS )Nr   r   r   r   r   r   c                   s    j jd|  d|I d H S r`   )rS   arunrc   rd   r   r   re   N  s   z<ReduceDocumentsChain._acollapse.<locals>._collapse_docs_funcr   r(   rf   rg   rh   r   )rK   ri   r%   r1   rF   r*   rN   r,   rj   r   rd   r   r]   C  s6   

zReduceDocumentsChain._acollapser   c                 C  r   )Nreduce_documents_chainr   rR   r   r   r   _chain_typef  s   z ReduceDocumentsChain._chain_type)r   r   )NN)
r   r   r%   rM   rT   r
   r   r   r   rU   )
r   r   r%   rM   rT   r
   r   r   r   r_   )r   r   )r   r   r    r!   __annotations__rL   r%   rN   r   model_configpropertyrS   rY   r^   rX   r]   rq   r   r   r   r   rJ   }   s<   
 
C	  &#rJ   N)
r   r   r$   r   r%   r&   r   r   r   r'   )r   r   r2   r   r   r   r   r   )r   r   r2   r#   r   r   r   r   )r!   
__future__r   typingr   r   r   r   r   r   langchain_core._apir	   langchain_core.callbacksr
   langchain_core.documentsr   pydanticr   'langchain.chains.combine_documents.baser   r   r#   r1   rE   rF   rJ   r   r   r   r   <module>   s&     

 
  	