§
    è˜ºhÔ*  ã                   ó4  — d Z ddl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mZ ddlmZmZ ddlmZmZmZ ddl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dœde
dedee         dee         de"deee"ef         ef         fd„Z# G d„ de¦  «        Z$dS )z7Chain that combines documents by stuffing into context.é    )ÚAnyÚDictÚListÚOptionalÚTuple)ÚDocument)ÚLanguageModelLike)ÚBaseOutputParserÚStrOutputParser)ÚBasePromptTemplateÚformat_document)ÚExtraÚFieldÚroot_validator)ÚRunnableÚRunnablePassthrough)Ú	Callbacks)ÚDEFAULT_DOCUMENT_PROMPTÚDEFAULT_DOCUMENT_SEPARATORÚDOCUMENTS_KEYÚBaseCombineDocumentsChainÚ_validate_prompt)ÚLLMChainN)Úoutput_parserÚdocument_promptÚdocument_separatorÚllmÚpromptr   r   r   Úreturnc                ó  ‡‡— t          |¦  «         |pt          Š|pt          ¦   «         }dt          dt          fˆˆfd„}t          j        di t          |i¤Ž                     d¬¦  «        |z  | z  |z                       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", 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.

    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:

{context}")]
            )
            llm = ChatOpenAI(model_name="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                 ó\   •— ‰                      ˆfd„| t                   D ¦   «         ¦  «        S )Nc              3   ó8   •K  — | ]}t          |‰¦  «        V — Œd S ©N)r   )Ú.0ÚdocÚ_document_prompts     €úp/var/www/html/services/rag-service/venv/lib/python3.11/site-packages/langchain/chains/combine_documents/stuff.pyú	<genexpr>zDcreate_stuff_documents_chain.<locals>.format_docs.<locals>.<genexpr>O   s?   øè è € ð '
ð '
Ø7:�O˜CÐ!1Ñ2Ô2ð'
ð '
ð '
ð '
ð '
ð '
ó    )Újoinr   )r!   r'   r   s    €€r(   Úformat_docsz1create_stuff_documents_chain.<locals>.format_docsN   sF   ø€ Ø!×&Ò&ð '
ð '
ð '
ð '
Ø>DÅ]Ô>Sð'
ñ '
ô '
ñ 
ô 
ð 	
r*   Úformat_inputs)Úrun_nameÚstuff_documents_chain© )	r   r   r   ÚdictÚstrr   Úassignr   Úwith_config)r   r   r   r   r   Ú_output_parserr,   r'   s       `  @r(   Úcreate_stuff_documents_chainr6      sË   øø€ õh �VÑÔÐØ&ÐAÕ*AÐØ"Ð7¥oÑ&7Ô&7€Nð
�Dð 
¥Sð 
ð 
ð 
ð 
ð 
ð 
ð 
õ 	Ô"ÐBÐB¥m°[Ð%AÐBÐB×NÒNØ$ð 	Oñ 	
ô 	
ð ñ	ð ñ		ð
 ñ	÷ ‚kÐ2€kÑ3Ô3ð4r*   c                   óº  ‡ — e Zd ZU dZeed<   	  ed„ ¬¦  «        Zeed<   	 e	ed<   	 dZ
e	ed<   	  G d	„ d
¦  «        Z ed¬¦  «        dedefd„¦   «         Zedee	         fˆ fd„¦   «         Zdee         dedefd„Zdee         dedee         fd„Z	 ddee         dededee	ef         fd„Z	 ddee         dededee	ef         fd„Zede	fd„¦   «         Zˆ x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                  ó   — t           S r$   )r   r0   r*   r(   ú<lambda>zStuffDocumentsChain.<lambda>‡   s   € Õ 7€ r*   )Údefault_factoryr   Údocument_variable_namez

r   c                   ó$   — e Zd ZdZej        ZdZdS )úStuffDocumentsChain.Configz'Configuration for this pydantic object.TN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   ÚforbidÚextraÚarbitrary_types_allowedr0   r*   r(   ÚConfigr?   �   s#   € € € € € Ø5Ð5à”ˆØ"&ÐÐÐr*   rG   T)ÚpreÚvaluesr   c                 óØ   — |d         j         j        }d|vr.t          |¦  «        dk    r|d         |d<   n4t          d¦  «        ‚|d         |vrt          d|d         › d|› �¦  «        ‚|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.
        r9   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)ÚclsrI   Úllm_chain_variabless      r(   Ú"get_default_document_variable_namez6StuffDocumentsChain.get_default_document_variable_name–   s´   € ð % [Ô1Ô8ÔHÐØ#¨6Ð1Ð1ÝÐ&Ñ'Ô'¨1Ò,Ð,Ø3FÀqÔ3I�Ð/Ñ0Ð0å ð3ñô ð ð
 Ð.Ô/Ð7JÐJÐJÝ ðU¨fÐ5MÔ.Nð Uð UØ?RðUð Uñô ð ð ˆr*   c                 ób   •‡ — ˆ fd„‰ j         j        D ¦   «         }t          ¦   «         j        |z   S )Nc                 ó*   •— g | ]}|‰j         k    ¯|‘ŒS r0   )r=   )r%   ÚkÚselfs     €r(   ú
<listcomp>z2StuffDocumentsChain.input_keys.<locals>.<listcomp>±   s-   ø€ ð 
ð 
ð 
Ø°A¸Ô9TÒ4TÐ4TˆAÐ4TÐ4TÐ4Tr*   )r9   Ú
input_keysÚsuper)rU   Ú
extra_keysÚ	__class__s   ` €r(   rW   zStuffDocumentsChain.input_keys¯   sE   øø€ ð
ð 
ð 
ð 
Ø”~Ô0ð
ñ 
ô 
ˆ
õ ‰wŒwÔ! JÑ.Ð.r*   ÚdocsÚkwargsc                 ó¨   ‡ — ˆ fd„|D ¦   «         }ˆ f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                 ó:   •— g | ]}t          |‰j        ¦  «        ‘ŒS r0   )r   r   )r%   r&   rU   s     €r(   rV   z3StuffDocumentsChain._get_inputs.<locals>.<listcomp>Æ   s&   ø€ ÐRÐRÐRÀc• s¨DÔ,@ÑAÔAÐRÐRÐRr*   c                 óB   •— i | ]\  }}|‰j         j        j        v ¯||“ŒS r0   )r9   r   rL   )r%   rT   ÚvrU   s      €r(   ú
<dictcomp>z3StuffDocumentsChain._get_inputs.<locals>.<dictcomp>È   s<   ø€ ð 
ð 
ð 
á��1Ø�D”NÔ)Ô9Ð9Ð9ð ˆqà9Ð9Ð9r*   )Úitemsr   r+   r=   )rU   r[   r\   Údoc_stringsr!   s   `    r(   Ú_get_inputszStuffDocumentsChain._get_inputs¶   st   ø€ ð  SÐRÐRÐRÈTÐRÑRÔRˆð
ð 
ð 
ð 
àŸš™œð
ñ 
ô 
ˆð
 /3Ô.E×.JÒ.JÈ;Ñ.WÔ.WˆˆtÔ*Ñ+Øˆr*   c                 ó€   —  | j         |fi |¤Ž} | j        j        j        di |¤Ž}| j                             |¦  «        S )aV  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: List[Document], a list of documents to use to calculate the
                total prompt length.

        Returns:
            Returns None if the method does not depend on the prompt length,
            otherwise the length of the prompt in tokens.
        r0   )rd   r9   r   ÚformatÚ_get_num_tokens)rU   r[   r\   r!   r   s        r(   Úprompt_lengthz!StuffDocumentsChain.prompt_lengthÐ   sQ   € ð  "�Ô! $Ð1Ð1¨&Ð1Ð1ˆØ-�”Ô&Ô-Ð7Ð7°Ð7Ð7ˆØŒ~×-Ò-¨fÑ5Ô5Ð5r*   NÚ	callbacksc                 óJ   —  | j         |fi |¤Ž} | j        j        d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.
        ri   r0   )rd   r9   Úpredict©rU   r[   ri   r\   r!   s        r(   Úcombine_docsz StuffDocumentsChain.combine_docsä   sC   € ð "�Ô! $Ð1Ð1¨&Ð1Ð1ˆà%ˆtŒ~Ô%ÐDÐD°	ÐD¸VÐDÐDÀbÐHÐHr*   c              ‹   óZ   K  —  | j         |fi |¤Ž} | j        j        dd|i|¤Žƒ d{V —†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.
        ri   Nr0   )rd   r9   Úapredictrl   s        r(   Úacombine_docsz!StuffDocumentsChain.acombine_docsö   sY   è è € ð "�Ô! $Ð1Ð1¨&Ð1Ð1ˆà,�T”^Ô,ÐKÐK°yÐKÀFÐKÐKÐKÐKÐKÐKÐKÐKÈRÐOÐOr*   c                 ó   — dS )Nr/   r0   )rU   s    r(   Ú_chain_typezStuffDocumentsChain._chain_type  s   € à&Ð&r*   r$   )r@   rA   rB   rC   r   Ú__annotations__r   r   r   r2   r   rG   r   r   rQ   Úpropertyr   rW   r   r   r1   rd   r   Úintrh   r   r   rm   rp   rr   Ú__classcell__)rZ   s   @r(   r8   r8   ]   sa  ø€ € € € € € ð#ð #ðJ ÐÐÑð$à*/¨%Ø7Ð7ð+ñ +ô +€OÐ'ð ð ñ ð SØÐÐÑðIà$Ð˜Ð$Ð$Ñ$Ø?ð'ð 'ð 'ð 'ð 'ñ 'ô 'ð 'ð €^˜ÐÑÔð¸ð Àð ð ð ñ Ôðð0 ð/˜D œIð /ð /ð /ð /ð /ñ „Xð/ð  X¤ð ¸#ð À$ð ð ð ð ð46 $ x¤.ð 6¸Cð 6ÀHÈSÄMð 6ð 6ð 6ð 6ð* <@ðIð IØ˜”NðIØ/8ðIØKNðIà	ˆs�DˆyÔ	ðIð Ið Ið Ið& <@ðPð PØ˜”NðPØ/8ðPØKNðPà	ˆs�DˆyÔ	ðPð Pð Pð Pð$ ð'˜Sð 'ð 'ð 'ñ „Xð'ð 'ð 'ð 'ð 'r*   r8   )%rC   Útypingr   r   r   r   r   Úlangchain_core.documentsr   Úlangchain_core.language_modelsr	   Úlangchain_core.output_parsersr
   r   Úlangchain_core.promptsr   r   Úlangchain_core.pydantic_v1r   r   r   Úlangchain_core.runnablesr   r   Úlangchain.callbacks.managerr   Ú'langchain.chains.combine_documents.baser   r   r   r   r   Úlangchain.chains.llmr   r2   r6   r8   r0   r*   r(   ú<module>r�      sö  ðØ =Ð =Ø 3Ð 3Ð 3Ð 3Ð 3Ð 3Ð 3Ð 3Ð 3Ð 3Ð 3Ð 3Ð 3Ð 3à -Ð -Ð -Ð -Ð -Ð -Ø <Ð <Ð <Ð <Ð <Ð <Ø KÐ KÐ KÐ KÐ KÐ KÐ KÐ KØ FÐ FÐ FÐ FÐ FÐ FÐ FÐ FØ CÐ CÐ CÐ CÐ CÐ CÐ CÐ CÐ CÐ CØ BÐ BÐ BÐ BÐ BÐ BÐ BÐ Bà 1Ð 1Ð 1Ð 1Ð 1Ð 1ðð ð ð ð ð ð ð ð ð ð ð ð ð ð *Ð )Ð )Ð )Ð )Ð )ð 15Ø48Ø8ðD4ð D4ð D4Ø	ðD4àðD4ð Ð,Ô-ð	D4ð
 Ð0Ô1ðD4ð ðD4ð ˆd�3˜�8Œn˜cÐ!Ô"ðD4ð D4ð D4ð D4ðNm'ð m'ð m'ð m'ð m'Ð3ñ m'ô m'ð m'ð m'ð m'r*   