a
    •˜ëj³-  ã                   @   s  d 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mZ ddlmZmZ dd	lmZmZ dd
lmZmZmZ ddlmZ ddlmZmZmZmZm Z  ddl!m"Z" ddeedœeeee ee e#e#ee$e#ef ef dœdd„Z%edddd�G dd„ deƒƒZ&dS )z7Chain that combines documents by stuffing into context.é    )ÚAnyÚOptional)Ú
deprecated)Ú	Callbacks)ÚDocument)ÚLanguageModelLike)ÚBaseOutputParserÚStrOutputParser)ÚBasePromptTemplateÚformat_document)ÚRunnableÚRunnablePassthrough)Ú
ConfigDictÚFieldÚmodel_validator)Úoverride)ÚDEFAULT_DOCUMENT_PROMPTÚDEFAULT_DOCUMENT_SEPARATORÚDOCUMENTS_KEYÚBaseCombineDocumentsChainÚ_validate_prompt)ÚLLMChainN)Úoutput_parserÚdocument_promptÚdocument_separatorÚdocument_variable_name)ÚllmÚpromptr   r   r   r   Úreturnc                   sd   t |ˆƒ |pt‰ |ptƒ }ttdœ‡ ‡‡fdd„}tjf i ˆ|i¤Žjdd�|B | B |B jdd�S )aÄ  Create a chain for passing a list of Documents to a model.

    Args:
        llm: Language model.
        prompt: Prompt template. Must contain input variable "context" (override by
            setting document_variable), which will be used for passing in the formatted
            documents.
        output_parser: Output parser. Defaults to StrOutputParser.
        document_prompt: Prompt used for formatting each document into a string. Input
            variables can be "page_content" or any metadata keys that are in all
            documents. "page_content" will automatically retrieve the
            `Document.page_content`, and all other inputs variables will be
            automatically retrieved from the `Document.metadata` dictionary. Default to
            a prompt that only contains `Document.page_content`.
        document_separator: String separator to use between formatted document strings.
        document_variable_name: Variable name to use for the formatted documents in the
            prompt. Defaults to "context".

    Returns:
        An LCEL Runnable. The input is a dictionary that must have a "context" key that
        maps to a List[Document], and any other input variables expected in the prompt.
        The Runnable return type depends on output_parser used.

    Example:
        .. code-block:: python

            # pip install -U langchain langchain-community

            from langchain_community.chat_models import ChatOpenAI
            from langchain_core.documents import Document
            from langchain_core.prompts import ChatPromptTemplate
            from langchain.chains.combine_documents import create_stuff_documents_chain

            prompt = ChatPromptTemplate.from_messages(
                [("system", "What are everyone's favorite colors:\n\n{context}")]
            )
            llm = ChatOpenAI(model="gpt-3.5-turbo")
            chain = create_stuff_documents_chain(llm, prompt)

            docs = [
                Document(page_content="Jesse loves red but not yellow"),
                Document(
                    page_content="Jamal loves green but not as much as he loves orange"
                ),
            ]

            chain.invoke({"context": docs})

    )Úinputsr   c                    s   ˆ  ‡ fdd„| ˆ D ƒ¡S )Nc                 3   s   | ]}t |ˆ ƒV  qd S ©N)r   ©Ú.0Údoc)Ú_document_prompt© úg/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/langchain/chains/combine_documents/stuff.pyÚ	<genexpr>X   s   ÿzDcreate_stuff_documents_chain.<locals>.format_docs.<locals>.<genexpr>)Újoin)r   ©r$   r   r   r%   r&   Úformat_docsW   s    þz1create_stuff_documents_chain.<locals>.format_docsZformat_inputs)Zrun_nameÚstuff_documents_chain)r   r   r	   ÚdictÚstrr   ZassignZwith_config)r   r   r   r   r   r   Z_output_parserr*   r%   r)   r&   Úcreate_stuff_documents_chain   s     :

ÿýüûÿùr.   z0.2.13z1.0z½This class is deprecated. Use the `create_stuff_documents_chain` constructor instead. See migration guide here: https://python.langchain.com/docs/versions/migrating_chains/stuff_docs_chain/)ZsinceZremovalÚmessagec                       s  e Zd ZU dZeed< edd„ d�Zeed< e	ed< dZ
e	ed	< ed
dd�Zedd�eeedœdd„ƒƒZeeee	 dœ‡ fdd„ƒƒZee eedœdd„Zee eee dœdd„Zd"ee eeee	ef dœdd„Zd#ee eeee	ef dœdd„Zee	dœd d!„ƒZ‡  Z S )$ÚStuffDocumentsChaina  Chain that combines documents by stuffing into context.

    This chain takes a list of documents and first combines them into a single string.
    It does this by formatting each document into a string with the `document_prompt`
    and then joining them together with `document_separator`. It then adds that new
    string to the inputs with the variable name set by `document_variable_name`.
    Those inputs are then passed to the `llm_chain`.

    Example:
        .. code-block:: python

            from langchain.chains import StuffDocumentsChain, 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}")
            llm_chain = LLMChain(llm=llm, prompt=prompt)
            chain = StuffDocumentsChain(
                llm_chain=llm_chain,
                document_prompt=document_prompt,
                document_variable_name=document_variable_name,
            )

    Ú	llm_chainc                   C   s   t S r    )r   r%   r%   r%   r&   Ú<lambda>˜   ó    zStuffDocumentsChain.<lambda>)Údefault_factoryr   r   z

r   TZforbid)Zarbitrary_types_allowedÚextraÚbefore)Úmode)Úvaluesr   c                 C   sh   |d j j}d|vr<t|ƒdkr.|d |d< qdd}t|ƒ‚n(|d |vrdd|d › d|› �}t|ƒ‚|S )zæGet default document variable name, if not provided.

        If only one variable is present in the llm_chain.prompt,
        we can infer that the formatted documents should be passed in
        with this variable name.
        r1   r   é   r   zQdocument_variable_name must be provided if there are multiple llm_chain_variableszdocument_variable_name z- was not found in llm_chain input_variables: )r   Úinput_variablesÚlenÚ
ValueError)Úclsr8   Zllm_chain_variablesÚmsgr%   r%   r&   Ú"get_default_document_variable_name¦   s    	ÿ
ÿÿz6StuffDocumentsChain.get_default_document_variable_name)r   c                    s"   ‡ fdd„ˆ j jD ƒ}tƒ j| S )Nc                    s   g | ]}|ˆ j kr|‘qS r%   )r   )r"   Úk©Úselfr%   r&   Ú
<listcomp>Ä   s   z2StuffDocumentsChain.input_keys.<locals>.<listcomp>)r1   Ú
input_keysÚsuper)rB   Z
extra_keys©Ú	__class__rA   r&   rD   Á   s    
ÿzStuffDocumentsChain.input_keys)ÚdocsÚkwargsr   c                    s>   ‡ fdd„|D ƒ}‡ fdd„|  ¡ D ƒ}ˆ j |¡|ˆ j< |S )aô  Construct inputs from kwargs and docs.

        Format and then join all the documents together into one input with name
        `self.document_variable_name`. Also pluck any additional variables
        from **kwargs.

        Args:
            docs: List of documents to format and then join into single input
            **kwargs: additional inputs to chain, will pluck any other required
                arguments from here.

        Returns:
            dictionary of inputs to LLMChain
        c                    s   g | ]}t |ˆ jƒ‘qS r%   )r   r   r!   rA   r%   r&   rC   Ù   r3   z3StuffDocumentsChain._get_inputs.<locals>.<listcomp>c                    s$   i | ]\}}|ˆ j jjv r||“qS r%   )r1   r   r:   )r"   r@   ÚvrA   r%   r&   Ú
<dictcomp>Û   s   þz3StuffDocumentsChain._get_inputs.<locals>.<dictcomp>)Úitemsr   r(   r   )rB   rH   rI   Zdoc_stringsr   r%   rA   r&   Ú_get_inputsÉ   s    
þzStuffDocumentsChain._get_inputsc                 K   s2   | j |fi |¤Ž}| jjjf i |¤Ž}| j |¡S )a„  Return the prompt length given the documents passed in.

        This can be used by a caller to determine whether passing in a list
        of documents would exceed a certain prompt length. This useful when
        trying to ensure that the size of a prompt remains below a certain
        context limit.

        Args:
            docs: a list of documents to use to calculate the total prompt length.
            **kwargs: additional parameters to use to get inputs to LLMChain.

        Returns:
            Returns None if the method does not depend on the prompt length,
            otherwise the length of the prompt in tokens.
        )rM   r1   r   ÚformatZ_get_num_tokens)rB   rH   rI   r   r   r%   r%   r&   Úprompt_lengthã   s    z!StuffDocumentsChain.prompt_lengthN)rH   Ú	callbacksrI   r   c                 K   s,   | j |fi |¤Ž}| jjf d|i|¤Ži fS )aÀ  Stuff all documents into one prompt and pass to LLM.

        Args:
            docs: List of documents to join together into one variable
            callbacks: Optional callbacks to pass along
            **kwargs: additional parameters to use to get inputs to LLMChain.

        Returns:
            The first element returned is the single string output. The second
            element returned is a dictionary of other keys to return.
        rP   )rM   r1   Zpredict©rB   rH   rP   rI   r   r%   r%   r&   Úcombine_docs÷   s    z StuffDocumentsChain.combine_docsc                 Ë   s2   | j |fi |¤Ž}| jjf d|i|¤ŽI dH i fS )aÆ  Async stuff all documents into one prompt and pass to LLM.

        Args:
            docs: List of documents to join together into one variable
            callbacks: Optional callbacks to pass along
            **kwargs: additional parameters to use to get inputs to LLMChain.

        Returns:
            The first element returned is the single string output. The second
            element returned is a dictionary of other keys to return.
        rP   N)rM   r1   ZapredictrQ   r%   r%   r&   Úacombine_docs  s    z!StuffDocumentsChain.acombine_docsc                 C   s   dS )Nr+   r%   rA   r%   r%   r&   Ú_chain_type!  s    zStuffDocumentsChain._chain_type)N)N)!Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   Ú__annotations__r   r   r
   r-   r   r   Zmodel_configr   Úclassmethodr,   r   r?   Úpropertyr   ÚlistrD   r   rM   r   ÚintrO   r   ÚtuplerR   rS   rT   Ú__classcell__r%   r%   rF   r&   r0   g   sF   

#ÿþ ý
û ý
ûr0   )'rX   Útypingr   r   Zlangchain_core._apir   Zlangchain_core.callbacksr   Zlangchain_core.documentsr   Zlangchain_core.language_modelsr   Zlangchain_core.output_parsersr   r	   Zlangchain_core.promptsr
   r   Zlangchain_core.runnablesr   r   Zpydanticr   r   r   Ztyping_extensionsr   Z'langchain.chains.combine_documents.baser   r   r   r   r   Zlangchain.chains.llmr   r-   r,   r.   r0   r%   r%   r%   r&   Ú<module>   s>   ùøNü	