
    hZ/                        d Z ddlm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 dd	lmZmZmZ dd
lmZ ddlmZ ddlmZ  eddd       G d de             Zy)zOCombining documents by mapping a chain over them first, then combining results.    )annotations)AnyOptional)
deprecated)	Callbacks)Document)RunnableConfig)create_model)	BaseModel
ConfigDictmodel_validator)BaseCombineDocumentsChain)ReduceDocumentsChain)LLMChainz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                      e Zd ZU dZded<   	 ded<   	 ded<   	 dZd	ed
<   	 	 d	 	 	 d fdZed fd       Z e	dd      Z
 ed      edd              Z ed      edd              Z ed      edd              Zedd       Zedd       Z	 	 d	 	 	 	 	 	 	 	 	 d dZ	 	 d	 	 	 	 	 	 	 	 	 d dZed!d       Z xZS )"MapReduceDocumentsChaina-  Combining documents by mapping a chain over them, then combining results.

    We first call `llm_chain` on each document individually, passing in the
    `page_content` and any other kwargs. This is the `map` step.

    We then process the results of that `map` step in a `reduce` step. This should
    likely be a ReduceDocumentsChain.

    Example:
        .. code-block:: python

            from langchain.chains import (
                StuffDocumentsChain,
                LLMChain,
                ReduceDocumentsChain,
                MapReduceDocumentsChain,
            )
            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)
            # We now define how to combine these summaries
            reduce_prompt = PromptTemplate.from_template(
                "Combine these summaries: {context}"
            )
            reduce_llm_chain = LLMChain(llm=llm, prompt=reduce_prompt)
            combine_documents_chain = StuffDocumentsChain(
                llm_chain=reduce_llm_chain,
                document_prompt=document_prompt,
                document_variable_name=document_variable_name
            )
            reduce_documents_chain = ReduceDocumentsChain(
                combine_documents_chain=combine_documents_chain,
            )
            chain = MapReduceDocumentsChain(
                llm_chain=llm_chain,
                reduce_documents_chain=reduce_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
            )
            reduce_documents_chain = ReduceDocumentsChain(
                combine_documents_chain=combine_documents_chain,
                collapse_documents_chain=collapse_documents_chain,
            )
            chain = MapReduceDocumentsChain(
                llm_chain=llm_chain,
                reduce_documents_chain=reduce_documents_chain,
            )
    r   	llm_chainr   reduce_documents_chainstrdocument_variable_nameFboolreturn_intermediate_stepsc           	         | j                   r-t        	 di | j                  t        d fdt        t           d fiS t
        |   |      S )Nintermediate_steps)MapReduceDocumentsOutput)r   r
   
output_keyr   listsuperget_output_schema)selfconfig	__class__s     k/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/langchain/chains/combine_documents/map_reduce.pyr"   z)MapReduceDocumentsChain.get_output_schemar   sW     ))* OOc4[(49d*;  w(00    c                @    t         |   }| j                  rg |d}|S )z2Expect input key.

        :meta private:
        r   )r!   output_keysr   )r#   _output_keysr%   s     r&   r)   z#MapReduceDocumentsChain.output_keys   s.     w*))@\@+?@Lr'   Tforbid)arbitrary_types_allowedextrabefore)modec                    d|v rNd|v rd}t        |      |d   }|j                  d      }t        ||      }||d<   |d= |j                  dd       |S )For backwards compatibility.combine_document_chainr   zBoth `reduce_documents_chain` and `combine_document_chain` cannot be provided at the same time. `combine_document_chain` is deprecated, please only provide `reduce_documents_chain`collapse_document_chain)combine_documents_chaincollapse_documents_chainN)
ValueErrorgetr   pop)clsvaluesmsgcombine_chaincollapse_chainreduce_chains         r&   get_reduce_chainz(MapReduceDocumentsChain.get_reduce_chain   s     $v-'61R 
 !o%"#;<M#ZZ(ABN/(5)7L 0<F+,/0JJ0$7r'   c                $    d|v r|d   |d<   |d= |S )r1   return_map_stepsr    )r9   r:   s     r&   get_return_intermediate_stepsz5MapReduceDocumentsChain.get_return_intermediate_steps   s+     '289K2LF./)*r'   c                    d|vrd}t        |      |d   j                  j                  }d|vr%t        |      dk(  r
|d   |d<   |S d}t        |      |d   |vrd|d    d| }t        |      |S )	z4Get default document variable name, if not provided.r   z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: )r6   promptinput_variableslen)r9   r:   r;   llm_chain_variabless       r&   "get_default_document_variable_namez:MapReduceDocumentsChain.get_default_document_variable_name   s     f$.CS/!$[188HH#61&'1,3Fq3I/0 9  !o%,-5HH)&1I*J)K L;;N:OQ  S/!r'   c                   t        | j                  t              rB| j                  j                  r| j                  j                  S | j                  j                  S dt        | j                         d}t        |      z Kept for backward compatibility.z$`reduce_documents_chain` is of type z$ so it does not have this attribute.)
isinstancer   r   r5   r4   typer6   r#   r;   s     r&   r3   z/MapReduceDocumentsChain.collapse_document_chain   sw     d113GH**CC22KKK..FFF2D//01 2 	
 or'   c                    t        | j                  t              r| j                  j                  S dt	        | j                         d}t        |      rL   )rM   r   r   r4   rN   r6   rO   s     r&   r2   z.MapReduceDocumentsChain.combine_document_chain   sV     d113GH..FFF2D//01 2 	
 or'   c           	        | j                   j                  |D cg c]  }| j                  |j                  i| c}|      }| j                   j                  }t        |      D 	cg c]"  \  }}	t        |	|   ||   j                        $ }
}}	 | j                  j                  |
f||d|\  }}| j                  r|D 	cg c]  }	|	|   	 }}	||d<   ||fS c c}w c c}	}w c c}	w )Combine documents in a map reduce manner.

        Combine by mapping first chain over all documents, then reducing the results.
        This reducing can be done recursively if needed (if there are many documents).
        	callbackspage_contentmetadata	token_maxrT   r   )r   applyr   rV   r   	enumerater   rW   r   combine_docsr   r#   docsrY   rT   kwargsdmap_resultsquestion_result_keyirresult_docsresultextra_return_dictr   s                 r&   r\   z$MapReduceDocumentsChain.combine_docs   s    nn**NRSd))1>>DVDS + 

 #nn77 "+.
 1 !$7"847CSCST
 

 %MD$?$?$L$L%
%
 	%
!! ))BM!NQ!$7"8!N!N6H23(((% T
 "Os   !C('C!C'c           	       K   | j                   j                  |D cg c]  }| j                  |j                  i| c}|       d{   }| j                   j                  }t        |      D 	cg c]"  \  }}	t        |	|   ||   j                        $ }
}}	 | j                  j                  |
f||d| d{   \  }}| j                  r|D 	cg c]  }	|	|   	 }}	||d<   ||fS c c}w 7 c c}	}w 7 ;c c}	w w)rR   rS   NrU   rX   r   )r   aapplyr   rV   r   r[   r   rW   r   acombine_docsr   r]   s                 r&   rj   z%MapReduceDocumentsChain.acombine_docs  s4     !NN11NRSd))1>>DVDS 2 
 

 #nn77 "+.
 1 !$7"847CSCST
 

 +T$*E*E*S*S+
+
 	+
 %
!! ))BM!NQ!$7"8!N!N6H23(((% T


%
 "OsK   D!C.D	C3
(D2'C5&D?C; DC=#D5D=Dc                     y)Nmap_reduce_documents_chainrB   )r#   s    r&   _chain_typez#MapReduceDocumentsChain._chain_type*  s    +r'   )N)r$   zOptional[RunnableConfig]returnztype[BaseModel])rn   z	list[str])r:   dictrn   r   )rn   r   )NN)
r^   zlist[Document]rY   zOptional[int]rT   r   r_   r   rn   ztuple[str, dict])rn   r   )__name__
__module____qualname____doc____annotations__r   r"   propertyr)   r   model_configr   classmethodr?   rC   rJ   r3   r2   r\   rj   rm   __classcell__)r%   s   @r&   r   r      s   HT 755JI&+t+< ,01(1 
1    $L
 (#  $, (#  $ (#  $0   	 	 $(#	 ) ) ! ) 	 )
  ) 
 )J $(#	 ) ) ! ) 	 )
  ) 
 )D , ,r'   r   N)rs   
__future__r   typingr   r   langchain_core._apir   langchain_core.callbacksr   langchain_core.documentsr   langchain_core.runnables.configr	   langchain_core.utils.pydanticr
   pydanticr   r   r   'langchain.chains.combine_documents.baser   )langchain.chains.combine_documents.reducer   langchain.chains.llmr   r   rB   r'   r&   <module>r      s\    U "   * . - : 6 ; ; M J ) 
	X	P,7 P,P,r'   