Ë
    ´ŒjJ-  ã                   ó6  — 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mZmZmZmZ ddlm Z  ddeedœdededee   dee   de!de!dee"e!ef   ef   fd„Z# eddd¬«       G d„ de«      «       Z$y)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)Ú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                óø   ‡‡‡— t        |‰«       |xs t        Š|xs
 t        «       }dt        dt        fˆˆˆfd„}t        j                  di ‰|i¤Žj                  d¬«      |z  | z  |z  j                  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                 ó>   •— ‰j                  ˆfd„| ‰   D «       «      S )Nc              3   ó6   •K  — | ]  }t        |‰«      –— Œ y ­w©N)r   )Ú.0ÚdocÚ_document_prompts     €úr/var/www/html/Fitness-lenito-AI-main/venv/lib/python3.12/site-packages/langchain/chains/combine_documents/stuff.pyÚ	<genexpr>zDcreate_stuff_documents_chain.<locals>.format_docs.<locals>.<genexpr>T   s!   øè ø€ ð '
á5�ô ˜CÐ!1×2Ù5ùs   ƒ)Újoin)r    r&   r   r   s    €€€r'   Úformat_docsz1create_stuff_documents_chain.<locals>.format_docsS   s)   ø€ Ø!×&Ñ&ó '
àÐ4Ò5ó'
ó 
ð 	
ó    Úformat_inputs)Úrun_nameÚstuff_documents_chain© )r   r   r
   ÚdictÚstrr   ÚassignÚwith_config)	r   r   r   r   r   r   Ú_output_parserr*   r&   s	       ``  @r'   Úcreate_stuff_documents_chainr5      sœ   ú€ ôn �VÐ3Ô4Ø&ÒAÔ*AÐØ"Ò7¤oÓ&7€Nð
œDð 
¤S÷ 
ô 	×"Ñ"ÑKÐ&<¸kÐ%JÑK×WÑWØ$ð 	Xó 	
ð ñ	ð ñ		ð
 ñ	÷ �kÐ2€kÓ3ð4r+   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/)ÚsinceÚremovalÚmessagec                   óp  ‡ — e Zd ZU dZeed<   	  ed„ ¬«      Zeed<   	 e	ed<   	 dZ
e	ed<   	  ed	d
¬«      Z ed¬«      e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   r/   r+   r'   Ú<lambda>zStuffDocumentsChain.<lambda>–   s   € Õ 7r+   )Údefault_factoryr   r   z

r   TÚforbid)Úarbitrary_types_allowedÚextraÚbefore)ÚmodeÚvaluesr   c                 óÄ   — |d   j                   j                  }d|vr%t        |«      dk(  r
|d   |d<   |S d}t        |«      ‚|d   |vrd|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.
        r;   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)ÚclsrD   Úllm_chain_variablesÚmsgs       r'   Ú"get_default_document_variable_namez6StuffDocumentsChain.get_default_document_variable_name¤   s£   € ð % [Ñ1×8Ñ8×HÑHÐØ#¨6Ñ1ÜÐ&Ó'¨1Ò,Ø3FÀqÑ3I�Ð/Ñ0ð ˆð3ð ô ! “oÐ%ØÐ,Ñ-Ð5HÑHà)¨&Ð1IÑ*JÐ)Kð L;Ø;NÐ:OðQð ô ˜S“/Ð!Øˆr+   c                 óŽ   •— | j                   j                  D �cg c]  }|| j                  k7  sŒ|‘Œ }}t        ‰| �  |z   S c c}w r#   )r;   Ú
input_keysr   Úsuper)ÚselfÚkÚ
extra_keysÚ	__class__s      €r'   rO   zStuffDocumentsChain.input_keys¿   sP   ø€ ð —~‘~×0Ò0ó
Ù0�!°A¸×9TÑ9TÓ4TŠAÐ0ð 	ð 
ô ‰wÑ! JÑ.Ð.ùò
s
   šA¯AÚdocsÚkwargsc                 ó<  — |D �cg c]  }t        || j                  «      ‘Œ }}|j                  «       D ��ci c]*  \  }}|| j                  j                  j
                  v r||“Œ, }}}| j                  j                  |«      || j                  <   |S c c}w c c}}w )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
        )	r   r   Úitemsr;   r   rG   r   r)   r   )rQ   rU   rV   r%   Údoc_stringsrR   Úvr    s           r'   Ú_get_inputszStuffDocumentsChain._get_inputsÆ   s¢   € ñ  NRÓRÉTÀc” s¨D×,@Ñ,@ÕAÈTˆÐRð Ÿ™œô
á&‘��1Ø�D—N‘N×)Ñ)×9Ñ9Ñ9ð ˆq‰DØ&ð 	ñ 
ð
 /3×.EÑ.E×.JÑ.JÈ;Ó.Wˆˆt×*Ñ*Ñ+Øˆùò Sùó
s
   …B·/Bc                 óª   —  | j                   |fi |¤Ž} | j                  j                  j                  di |¤Ž}| j                  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.
        r/   )r[   r;   r   ÚformatÚ_get_num_tokens)rQ   rU   rV   r    r   s        r'   Úprompt_lengthz!StuffDocumentsChain.prompt_lengthà   sO   € ð  "�×!Ñ! $Ñ1¨&Ñ1ˆØ-�—‘×&Ñ&×-Ñ-Ñ7°Ñ7ˆØ�~‰~×-Ñ-¨fÓ5Ð5r+   Ú	callbacksc                 óh   —  | 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.
        r`   r/   )r[   r;   Úpredict©rQ   rU   r`   rV   r    s        r'   Úcombine_docsz StuffDocumentsChain.combine_docsô   s?   € ð" "�×!Ñ! $Ñ1¨&Ñ1ˆà%ˆt�~‰~×%Ñ%ÑD°	ÐD¸VÑDÀbÐHÐHr+   c              ‹   ó„   K  —  | j                   |fi |¤Ž} | j                  j                  dd|i|¤Žƒ d{  –—† i fS 7 Œ­w)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.
        r`   Nr/   )r[   r;   Úapredictrc   s        r'   Úacombine_docsz!StuffDocumentsChain.acombine_docs	  sI   è ø€ ð" "�×!Ñ! $Ñ1¨&Ñ1ˆà,�T—^‘^×,Ñ,ÑK°yÐKÀFÑK×KÈRÐOÐOÐKús   ‚5A ·>¸A c                  ó   — y)Nr.   r/   )rQ   s    r'   Ú_chain_typezStuffDocumentsChain._chain_type  s   € à&r+   r#   ) Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   Ú__annotations__r   r   r   r1   r   r   Úmodel_configr   Úclassmethodr0   r   rM   ÚpropertyÚlistrO   r   r[   r   Úintr_   r   Útuplerd   rg   ri   Ú__classcell__)rT   s   @r'   r:   r:   c   sˆ  ø… ñ#ðJ Óð$á*/Ù7ô+€OÐ'ó ð SØÓðIà$Ð˜Ó$Ø?áØ $Øô€Lñ
 ˜(Ô#Øð¸ð Àò ó ó $ðð2 ð/˜D ™Iô /ó ð/ð  X¡ð ¸#ð À$ó ð46 $ x¡.ð 6¸Cð 6ÀHÈSÁMó 6ð.  $ñIà�8‰nðIð ðIð ð	Ið
 
ˆs�DˆyÑ	óIð0  $ñPà�8‰nðPð ðPð ð	Pð
 
ˆs�DˆyÑ	óPð* ð'˜Sò 'ó ô'r+   r:   )%rm   Útypingr   r   Úlangchain_core._apir   Úlangchain_core.callbacksr   Úlangchain_core.documentsr   Úlangchain_core.language_modelsr   Úlangchain_core.output_parsersr	   r
   Úlangchain_core.promptsr   r   Úlangchain_core.runnablesr   r   Úpydanticr   r   r   Ú'langchain.chains.combine_documents.baser   r   r   r   r   Úlangchain.chains.llmr   r1   r0   r5   r:   r/   r+   r'   Ú<module>r�      sá   ðÙ =ç  å *Ý .Ý -Ý <ß Kß Fß Bß 7Ñ 7÷õ õ *ð 15Ø48Ø8Ø"/òH4Ø	ðH4àðH4ð Ð,Ñ-ð	H4ð
 Ð0Ñ1ðH4ð ðH4ð  ðH4ð ˆd�3˜�8‰n˜cÐ!Ñ"óH4ñV Ø
Øð	Xô	ôt'Ð3ó t'óñt'r+   