
    @'h*/                        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     t/home/kushmeetdev/Regenta/Chatbot/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|dgz   }|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 rAd|v rt        d      |d   }|j                  d      }t        ||      }||d<   |d= d|v r|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_chain)
ValueErrorgetr   )clsvaluescombine_chaincollapse_chainreduce_chains        r&   get_reduce_chainz(MapReduceDocumentsChain.get_reduce_chain   s     $v-'61 R 
 ##;<M#ZZ(ABN/(5)7L 0<F+,/0(F245r'   c                $    d|v r|d   |d<   |d= |S )r1   return_map_stepsr    )r8   r9   s     r&   get_return_intermediate_stepsz5MapReduceDocumentsChain.get_return_intermediate_steps   s+     '289K2LF./)*r'   c                    d|vrt        d      |d   j                  j                  }d|vr#t        |      dk(  r
|d   |d<   |S t        d      |d   |vrt        d|d    d|       |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)r8   r9   llm_chain_variabless      r&   "get_default_document_variable_namez:MapReduceDocumentsChain.get_default_document_variable_name   s     f$9::$[188HH#61&'1,3Fq3I/0  !9 
 ./7JJ -f5M.N-O P??R>SU  r'   c                    t        | j                  t              rB| j                  j                  r| j                  j                  S | j                  j                  S t        dt        | j                         d      z Kept for backward compatibility.z$`reduce_documents_chain` is of type z$ so it does not have this attribute.)
isinstancer   r   r5   r4   r6   typer#   s    r&   r3   z/MapReduceDocumentsChain.collapse_document_chain   ss     d113GH**CC22KKK22JJJ63345 6"# r'   c                    t        | j                  t              r| j                  j                  S t	        dt        | j                         d      rJ   )rK   r   r   r4   r6   rL   rM   s    r&   r2   z.MapReduceDocumentsChain.combine_document_chain   sR     d113GH..FFF63345 6"# 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_maxrR   r   )r   applyr   rT   r   	enumerater   rU   r   combine_docsr   r#   docsrW   rR   kwargsdmap_resultsquestion_result_keyirresult_docsresultextra_return_dictr   s                 r&   rZ   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%
#,	%
EK%
!! ))BM!NQ!$7"8!N!N6H23((( T
 "Os   !C('C!C'c           	       K   | j                   j                  |D cg c]  }i | 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)rP   rQ   NrS   rV   r   )r   aapplyr   rT   r   rY   r   rU   r   acombine_docsr   r[   s                 r&   rh   z%MapReduceDocumentsChain.acombine_docs  s7     !NN11RVWQH,,ann=HHW 2 
 

 #nn77 "+.
 1 !$7"847CSCST
 

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

%
 "OsK   D#C0DC5(D4'C7&DC=DC?%D7D?Dc                     y)Nmap_reduce_documents_chainr@   rM   s    r&   _chain_typez#MapReduceDocumentsChain._chain_type"  s    +r'   )N)r$   zOptional[RunnableConfig]returnztype[BaseModel])rl   z	list[str])r9   dictrl   r   )rl   r   )NN)
r\   zlist[Document]rW   zOptional[int]rR   r   r]   r   rl   ztuple[str, dict])rl   r   )__name__
__module____qualname____doc____annotations__r   r"   propertyr)   r   model_configr   classmethodr=   rA   rH   r3   r2   rZ   rh   rk   __classcell__)r%   s   @r&   r   r      s   HT 755JI&+t+< 261.1	1    $L
 (#  $, (#  $ (#  $,   	 	 $(#	)) !) 	)
 ) 
)D $(#	)) !) 	)
 ) 
)> , ,r'   r   N)rq   
__future__r   typingr   r   langchain_core._apir   langchain_core.callbacksr   langchain_core.documentsr   langchain_core.runnables.configr	   langchain_core.runnables.utilsr
   pydanticr   r   r   'langchain.chains.combine_documents.baser   )langchain.chains.combine_documents.reducer   langchain.chains.llmr   r   r@   r'   r&   <module>r      s\    U "   * . - : 7 ; ; M J ) 
	X	H,7 H,H,r'   