a
    •˜ëjð$  ã                   @  s¸   d 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
 ddlmZmZ ddlmZ dd	lmZmZmZ dd
lmZ ddlmZ ddœdd„Zedddd�G dd„ deƒƒZdS )zLCombine documents by doing a first pass and then refining on more documents.é    )Úannotations)ÚAny)Ú
deprecated)Ú	Callbacks)ÚDocument)ÚBasePromptTemplateÚformat_document©ÚPromptTemplate)Ú
ConfigDictÚFieldÚmodel_validator)ÚBaseCombineDocumentsChain)ÚLLMChainr
   ©Úreturnc                   C  s   t dgdd�S )NÚpage_contentz{page_content})Úinput_variablesÚtemplater	   © r   r   úh/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/langchain/chains/combine_documents/refine.pyÚ_get_default_document_prompt   s    r   z0.3.1z1.0z«This class is deprecated. Please see the migration guide here for a recommended replacement: https://python.langchain.com/docs/versions/migrating_chains/refine_docs_chain/)ZsinceZremovalÚmessagec                      s&  e Zd ZU dZded< ded< ded< ded< eed�Zd	ed
< dZded< e	ddœ‡ fdd„ƒZ
eddd�Zedd�edddœdd„ƒƒZedd�edddœdd„ƒƒZd4dd dd!d"œd#d$„Zd5dd dd!d"œd%d&„Zddd!d'œd(d)„Zd*dd+d,œd-d.„Zddd+d/œd0d1„Ze	ddœd2d3„ƒZ‡  ZS )6ÚRefineDocumentsChainaø  Combine documents by doing a first pass and then refining on more documents.

    This algorithm first calls `initial_llm_chain` on the first document, passing
    that first document in with the variable name `document_variable_name`, and
    produces a new variable with the variable name `initial_response_name`.

    Then, it loops over every remaining document. This is called the "refine" step.
    It calls `refine_llm_chain`,
    passing in that document with the variable name `document_variable_name`
    as well as the previous response with the variable name `initial_response_name`.

    Example:
        .. code-block:: python

            from langchain.chains import RefineDocumentsChain, LLMChain
            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}")
            initial_llm_chain = LLMChain(llm=llm, prompt=prompt)
            initial_response_name = "prev_response"
            # The prompt here should take as an input variable the
            # `document_variable_name` as well as `initial_response_name`
            prompt_refine = PromptTemplate.from_template(
                "Here's your first summary: {prev_response}. "
                "Now add to it based on the following context: {context}"
            )
            refine_llm_chain = LLMChain(llm=llm, prompt=prompt_refine)
            chain = RefineDocumentsChain(
                initial_llm_chain=initial_llm_chain,
                refine_llm_chain=refine_llm_chain,
                document_prompt=document_prompt,
                document_variable_name=document_variable_name,
                initial_response_name=initial_response_name,
            )

    r   Úinitial_llm_chainÚrefine_llm_chainÚstrÚdocument_variable_nameÚinitial_response_name)Údefault_factoryr   Údocument_promptFÚboolÚreturn_intermediate_stepsz	list[str]r   c                   s   t ƒ j}| jrg |¢d‘}|S )z2Expect input key.

        :meta private:
        Úintermediate_steps)ÚsuperÚoutput_keysr"   )ÚselfZ_output_keys©Ú	__class__r   r   r%   b   s    z RefineDocumentsChain.output_keysTZforbid)Zarbitrary_types_allowedÚextraÚbefore)ÚmodeÚdictr   )Úvaluesr   c                 C  s   d|v r|d |d< |d= |S )zFor backwards compatibility.Zreturn_refine_stepsr"   r   )Úclsr-   r   r   r   Úget_return_intermediate_stepsr   s    z2RefineDocumentsChain.get_return_intermediate_stepsc                 C  s|   d|vrd}t |ƒ‚|d jj}d|vrPt|ƒdkrB|d |d< qxd}t |ƒ‚n(|d |vrxd|d › d|› �}t |ƒ‚|S )	z4Get default document variable name, if not provided.r   z"initial_llm_chain must be providedr   é   r   zWdocument_variable_name must be provided if there are multiple llm_chain input_variableszdocument_variable_name z- was not found in llm_chain input_variables: )Ú
ValueErrorÚpromptr   Úlen)r.   r-   ÚmsgZllm_chain_variablesr   r   r   Ú"get_default_document_variable_name{   s"    ÿ
ÿÿz7RefineDocumentsChain.get_default_document_variable_nameNzlist[Document]r   ztuple[str, dict])ÚdocsÚ	callbacksÚkwargsr   c           	      K  s„   | j |fi |¤Ž}| jjf d|i|¤Ž}|g}|dd… D ]<}|  ||¡}i |¥|¥}| jjf d|i|¤Ž}| |¡ q:|  ||¡S )aõ  Combine by mapping first chain over all, then stuffing into final chain.

        Args:
            docs: List of documents to combine
            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.
        r7   r0   N)Ú_construct_initial_inputsr   ZpredictÚ_construct_refine_inputsr   ÚappendÚ_construct_result©	r&   r6   r7   r8   ÚinputsÚresÚrefine_stepsÚdocÚbase_inputsr   r   r   Úcombine_docs•   s    z!RefineDocumentsChain.combine_docsc           	      Ë  s�   | j |fi |¤Ž}| jjf d|i|¤ŽI dH }|g}|dd… D ]B}|  ||¡}i |¥|¥}| jjf d|i|¤ŽI dH }| |¡ q@|  ||¡S )aù  Combine by mapping a first chain over all, then stuffing into a final chain.

        Args:
            docs: List of documents to combine
            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.
        r7   Nr0   )r9   r   Zapredictr:   r   r;   r<   r=   r   r   r   Úacombine_docs±   s    z"RefineDocumentsChain.acombine_docs)r@   r?   r   c                 C  s   | j rd|i}ni }||fS )Nr#   )r"   )r&   r@   r?   Zextra_return_dictr   r   r   r<   Í   s    
z&RefineDocumentsChain._construct_resultr   zdict[str, Any])rA   r?   r   c                 C  s   | j t|| jƒ| j|iS )N)r   r   r    r   )r&   rA   r?   r   r   r   r:   Ô   s    þz-RefineDocumentsChain._construct_refine_inputs)r6   r8   r   c                   sX   d|d j i‰ ˆ  |d j¡ ‡ fdd„| jjD ƒ}| j| jjf i |¤Ži}i |¥|¥S )Nr   r   c                   s   i | ]}|ˆ | “qS r   r   )Ú.0Úk©Z	base_infor   r   Ú
<dictcomp>á   ó    zBRefineDocumentsChain._construct_initial_inputs.<locals>.<dictcomp>)r   ÚupdateÚmetadatar    r   r   Úformat)r&   r6   r8   Zdocument_inforB   r   rG   r   r9   Ú   s    ÿz.RefineDocumentsChain._construct_initial_inputsc                 C  s   dS )NZrefine_documents_chainr   )r&   r   r   r   Ú_chain_typeç   s    z RefineDocumentsChain._chain_type)N)N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú__annotations__r   r   r    r"   Úpropertyr%   r   Zmodel_configr   Úclassmethodr/   r5   rC   rD   r<   r:   r9   rM   Ú__classcell__r   r   r'   r   r      s<   

0ÿ
þ ý ýr   N)rQ   Ú
__future__r   Útypingr   Zlangchain_core._apir   Zlangchain_core.callbacksr   Zlangchain_core.documentsr   Zlangchain_core.promptsr   r   Zlangchain_core.prompts.promptr
   Zpydanticr   r   r   Z'langchain.chains.combine_documents.baser   Zlangchain.chains.llmr   r   r   r   r   r   r   Ú<module>   s"   ü	