o
    .if9                     @  s.  d Z ddlmZ ddlZddlmZmZmZmZm	Z	m
Z
mZmZ ddl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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&m'Z' ddl(m)Z) ddl*m+Z+ ddl,m-Z-m.Z.m/Z/m0Z0m1Z1 ddl2m3Z3 G dd de3Z4dddZ5dS )z2Chain that just formats a prompt and calls an LLM.    )annotationsN)AnyDictListOptionalSequenceTupleUnioncast)BaseLanguageModelLanguageModelInput)dumpd)BaseMessage)BaseLLMOutputParserStrOutputParser)ChatGeneration
Generation	LLMResult)PromptValue)BasePromptTemplatePromptTemplate)ExtraField)RunnableRunnableBindingRunnableBranchRunnableWithFallbacks)DynamicRunnable)get_colored_text)AsyncCallbackManagerAsyncCallbackManagerForChainRunCallbackManagerCallbackManagerForChainRun	Callbacks)Chainc                   @  s  e Zd ZU dZed[ddZded< 	 ded	< 	 d
Zded< ee	dZ
ded< 	 dZded< 	 eedZded< G dd dZed\ddZed\ddZ	d]d^d!d"Z	d]d_d&d'Z	d]d`d)d*Z	d]dad,d-Z	d]dbd.d/Z	d]dcd3d4Z	d]dcd5d6Zeddd7d8Zded:d;Z	d]dfd<d=Zd]dgd@dAZd]dgdBdCZ	d]dhdEdFZ	d]didHdIZ	d]djdKdLZ dkdNdOZ!	d]djdPdQZ"edddRdSZ#edldVdWZ$dmdYdZZ%dS )nLLMChaina  Chain to run queries against LLMs.

    Example:
        .. code-block:: python

            from langchain.chains import LLMChain
            from langchain_community.llms import OpenAI
            from langchain_core.prompts import PromptTemplate
            prompt_template = "Tell me a {adjective} joke"
            prompt = PromptTemplate(
                input_variables=["adjective"], template=prompt_template
            )
            llm = LLMChain(llm=OpenAI(), prompt=prompt)
    returnboolc                 C     dS )NT selfr)   r)   M/var/www/html/corbot_env/lib/python3.10/site-packages/langchain/chains/llm.pyis_lc_serializable5      zLLMChain.is_lc_serializabler   promptzSUnion[Runnable[LanguageModelInput, str], Runnable[LanguageModelInput, BaseMessage]]llmtextstr
output_key)default_factoryr   output_parserTreturn_final_onlydict
llm_kwargsc                   @  s   e Zd ZdZejZdZdS )zLLMChain.Configz'Configuration for this pydantic object.TN)__name__
__module____qualname____doc__r   forbidextraarbitrary_types_allowedr)   r)   r)   r,   ConfigI   s    r@   	List[str]c                 C  s   | j jS )zJWill be whatever keys the prompt expects.

        :meta private:
        )r/   input_variablesr*   r)   r)   r,   
input_keysO   s   zLLMChain.input_keysc                 C  s   | j r| jgS | jdgS )z=Will always return text key.

        :meta private:
        full_generation)r6   r3   r*   r)   r)   r,   output_keysW   s   
zLLMChain.output_keysNinputsDict[str, Any]run_manager$Optional[CallbackManagerForChainRun]Dict[str, str]c                 C  s   | j |g|d}| |d S NrH   r   )generatecreate_outputsr+   rF   rH   responser)   r)   r,   _callb   s   zLLMChain._call
input_listList[Dict[str, Any]]r   c           	      C  s   | j ||d\}}|r| nd}t| jtr%| jj||fd|i| jS | jjdd|i| jt	t
|d|i}g }|D ]}t|trO|t|dg q>|t|dg q>t|dS 	z Generate LLM result from inputs.rL   N	callbacksstop)message)r1   )generationsr)   )prep_prompts	get_child
isinstancer0   r   generate_promptr8   bindbatchr
   r   r   appendr   r   r   	r+   rR   rH   promptsrV   rU   resultsrX   resr)   r)   r,   rM   j   s(   

zLLMChain.generate)Optional[AsyncCallbackManagerForChainRun]c           	        s   | j ||dI dH \}}|r| nd}t| jtr,| jj||fd|i| jI dH S | jjdd|i| jt	t
|d|iI dH }g }|D ]}t|trY|t|dg qH|t|dg qHt|dS rT   )aprep_promptsrZ   r[   r0   r   agenerate_promptr8   r]   abatchr
   r   r   r_   r   r   r   r`   r)   r)   r,   	agenerate   s*   


zLLMChain.agenerate-Tuple[List[PromptValue], Optional[List[str]]]c           	        s   d}t |dkrg |fS d|d v r|d d }g }|D ]?  fdd| jjD }| jjdi |}t| d}d| }|rH|j|d| jd	 d v rV d |krVtd
|	| q||fS )Prepare prompts from inputs.Nr   rV   c                      i | ]}| | qS r)   r)   .0krF   r)   r,   
<dictcomp>       z)LLMChain.prep_prompts.<locals>.<dictcomp>greenPrompt after formatting:

endverbose=If `stop` is present in any inputs, should be present in all.r)   
lenr/   rB   format_promptr   	to_stringon_textrw   
ValueErrorr_   	r+   rR   rH   rV   ra   selected_inputsr/   _colored_text_textr)   ro   r,   rY      s&   zLLMChain.prep_promptsc           	        s   d}t |dkrg |fS d|d v r|d d }g }|D ]B  fdd| jjD }| jjdi |}t| d}d| }|rL|j|d| jd	I dH  d v rZ d |krZtd
|	| q||fS )rj   Nr   rV   c                   rk   r)   r)   rl   ro   r)   r,   rp      rq   z*LLMChain.aprep_prompts.<locals>.<dictcomp>rr   rs   rt   ru   rx   r)   ry   r   r)   ro   r,   re      s(   zLLMChain.aprep_promptsrU   r#   List[Dict[str, str]]c              
   C  s|   t || j| j}|t| d|i}z	| j||d}W n ty/ } z|| |d}~ww | 	|}|
d|i |S )0Utilize the LLM generate method for speed gains.rR   rL   Noutputs)r!   	configurerU   rw   on_chain_startr   rM   BaseExceptionon_chain_errorrN   on_chain_endr+   rR   rU   callback_managerrH   rP   er   r)   r)   r,   apply   s"   


zLLMChain.applyc              
     s   t || j| j}|t| d|iI dH }z| j||dI dH }W n ty9 } z
||I dH  |d}~ww | 	|}|
d|iI dH  |S )r   rR   NrL   r   )r   r   rU   rw   r   r   rh   r   r   rN   r   r   r)   r)   r,   aapply   s$   


zLLMChain.aapplyc                 C  s   | j S Nr3   r*   r)   r)   r,   _run_output_key   s   zLLMChain._run_output_key
llm_resultc                   s0    fdd|j D } jr fdd|D }|S )zCreate outputs from response.c                   s"   g | ]} j  j|d |iqS )rD   )r3   r5   parse_result)rm   
generationr*   r)   r,   
<listcomp>  s    z+LLMChain.create_outputs.<locals>.<listcomp>c                   s   g | ]
} j | j  iqS r)   r   )rm   rr*   r)   r,   r     s    )rX   r6   )r+   r   resultr)   r*   r,   rN      s   
zLLMChain.create_outputsc                   s&   | j |g|dI d H }| |d S rK   )rh   rN   rO   r)   r)   r,   _acall  s   zLLMChain._acallkwargsr   c                 K  s   | ||d| j  S )S  Format prompt with kwargs and pass to LLM.

        Args:
            callbacks: Callbacks to pass to LLMChain
            **kwargs: Keys to pass to prompt template.

        Returns:
            Completion from LLM.

        Example:
            .. code-block:: python

                completion = llm.predict(adjective="funny")
        rU   r   r+   rU   r   r)   r)   r,   predict  s   zLLMChain.predictc                   s   | j ||dI dH | j S )r   r   N)acallr3   r   r)   r)   r,   apredict'  s   zLLMChain.apredict%Union[str, List[str], Dict[str, Any]]c                 K  s<   t d | jdd|i|}| jjdur| jj|S |S )z(Call predict and then parse the results.z_The predict_and_parse method is deprecated, instead pass an output parser directly to LLMChain.rU   Nr)   )warningswarnr   r/   r5   parser+   rU   r   r   r)   r)   r,   predict_and_parse8  s   zLLMChain.predict_and_parse%Union[str, List[str], Dict[str, str]]c                   sD   t d | jdd|i|I dH }| jjdur | jj|S |S )z)Call apredict and then parse the results.z`The apredict_and_parse method is deprecated, instead pass an output parser directly to LLMChain.rU   Nr)   )r   r   r   r/   r5   r   r   r)   r)   r,   apredict_and_parseF  s   zLLMChain.apredict_and_parse/Sequence[Union[str, List[str], Dict[str, str]]]c                 C  s"   t d | j||d}| |S )&Call apply and then parse the results.z]The apply_and_parse method is deprecated, instead pass an output parser directly to LLMChain.r   )r   r   r   _parse_generationr+   rR   rU   r   r)   r)   r,   apply_and_parseT  s
   
zLLMChain.apply_and_parser   c                   s"    j jd ur fdd|D S |S )Nc                   s    g | ]} j j| j qS r)   )r/   r5   r   r3   )rm   rc   r*   r)   r,   r   c  s    z.LLMChain._parse_generation.<locals>.<listcomp>)r/   r5   )r+   r   r)   r*   r,   r   _  s
   
zLLMChain._parse_generationc                   s*   t d | j||dI dH }| |S )r   z^The aapply_and_parse method is deprecated, instead pass an output parser directly to LLMChain.r   N)r   r   r   r   r   r)   r)   r,   aapply_and_parsej  s   
zLLMChain.aapply_and_parsec                 C  r(   )N	llm_chainr)   r*   r)   r)   r,   _chain_typeu  r.   zLLMChain._chain_typer   templatec                 C  s   t |}| ||dS )z&Create LLMChain from LLM and template.)r0   r/   )r   from_template)clsr0   r   prompt_templater)   r)   r,   from_stringy  s   
zLLMChain.from_stringintc                 C  s   t | j|S r   )_get_language_modelr0   get_num_tokens)r+   r1   r)   r)   r,   _get_num_tokens  s   zLLMChain._get_num_tokens)r&   r'   )r&   rA   r   )rF   rG   rH   rI   r&   rJ   )rR   rS   rH   rI   r&   r   )rR   rS   rH   rd   r&   r   )rR   rS   rH   rI   r&   ri   )rR   rS   rH   rd   r&   ri   )rR   rS   rU   r#   r&   r   )r&   r2   )r   r   r&   rS   )rF   rG   rH   rd   r&   rJ   )rU   r#   r   r   r&   r2   )rU   r#   r   r   r&   r   )rU   r#   r   r   r&   r   )rR   rS   rU   r#   r&   r   )r   r   r&   r   )r0   r   r   r2   r&   r%   )r1   r2   r&   r   )&r9   r:   r;   r<   classmethodr-   __annotations__r3   r   r   r5   r6   r7   r8   r@   propertyrC   rE   rQ   rM   rh   rY   re   r   r   r   rN   r   r   r   r   r   r   r   r   r   r   r   r)   r)   r)   r,   r%   %   sl   
 

r%   llm_liker   r&   r   c                 C  s`   t | tr| S t | trt| jS t | trt| jS t | ttfr't| j	S t
dt|  )NzAUnable to extract BaseLanguageModel from llm_like object of type )r[   r   r   r   boundr   runnabler   r   defaultr~   type)r   r)   r)   r,   r     s   





r   )r   r   r&   r   )6r<   
__future__r   r   typingr   r   r   r   r   r   r	   r
   langchain_core.language_modelsr   r   langchain_core.load.dumpr   langchain_core.messagesr   langchain_core.output_parsersr   r   langchain_core.outputsr   r   r   langchain_core.prompt_valuesr   langchain_core.promptsr   r   langchain_core.pydantic_v1r   r   langchain_core.runnablesr   r   r   r   %langchain_core.runnables.configurabler   langchain_core.utils.inputr   langchain.callbacks.managerr   r    r!   r"   r#   langchain.chains.baser$   r%   r   r)   r)   r)   r,   <module>   s*    (  `