o
    Zh                     @  s  d Z ddlmZ ddlZddlZddlZddlZddlmZ ddl	m
Z
 ddlmZmZmZmZmZmZmZmZmZmZmZ ddlZddlmZ ddlmZmZmZ dd	lmZ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* ddl+m,Z, ddl-m.Z. ddl/m0Z0 ddl1m2Z2 ddl3m4Z4m5Z5m6Z6 ddl7m8Z8 ddl9m:Z: ddl;m<Z< ddl=m>Z>m?Z?m@Z@ ddlAmBZB ddlCmDZD ddlEmFZF ddlGmHZH ddlImJZJ ddlKmLZL ddlMmNZN ddlOmPZP eQeRZSG dd de>ZTG d d! d!e>ZUG d"d# d#e,eeef  ZVG d$d% d%e,eee ef  ZWG d&d' d'eTZXG d(d) d)eUZYed*eDd+d,G d-d. d.eTZZed*eDd+d,G d/d0 d0eTZ[G d1d2 d2e:Z\eeeeef  Z]eeXeYf Z^G d3d4 d4eLZ_dS )5zEChain that takes in an input and produces an action and action input.    )annotationsN)abstractmethod)Path)AnyAsyncIteratorCallableDictIteratorListOptionalSequenceTupleUnioncast)
deprecated)AgentActionAgentFinish	AgentStep)AsyncCallbackManagerForChainRunAsyncCallbackManagerForToolRunBaseCallbackManagerCallbackManagerForChainRunCallbackManagerForToolRun	Callbacks)OutputParserException)BaseLanguageModel)BaseMessage)BaseOutputParser)BasePromptTemplate)FewShotPromptTemplate)PromptTemplate)RunnableRunnableConfigensure_config)AddableDict)BaseTool)get_color_mapping)	BaseModel
ConfigDictmodel_validator)Self)AGENT_DEPRECATION_WARNING)AgentExecutorIterator)	AgentType)InvalidTool)Chain)LLMChain)asyncio_timeoutc                      s   e Zd ZdZed0ddZd1ddZe		d2d3ddZe		d2d3ddZ	eed0ddZ
d4ddZe		d2d5d"d#Zed6d$d%Zd7 fd'd(Zd8d,d-Zd9d.d/Z  ZS ):BaseSingleActionAgentzBase Single Action Agent class.return	List[str]c                 C     dgS Return values of the agent.output selfr9   r9   M/var/www/html/lang_env/lib/python3.10/site-packages/langchain/agents/agent.pyreturn_values@      z#BaseSingleActionAgent.return_valuesOptional[List[str]]c                 C  s   d S Nr9   r:   r9   r9   r<   get_allowed_toolsE   s   z'BaseSingleActionAgent.get_allowed_toolsNintermediate_stepsList[Tuple[AgentAction, str]]	callbacksr   kwargsr   Union[AgentAction, AgentFinish]c                 K     dS )0  Given input, decided what to do.

        Args:
            intermediate_steps: Steps the LLM has taken to date,
                along with observations.
            callbacks: Callbacks to run.
            **kwargs: User inputs.

        Returns:
            Action specifying what tool to use.
        Nr9   r;   rB   rD   rE   r9   r9   r<   planH       zBaseSingleActionAgent.planc                      dS )6  Async given input, decided what to do.

        Args:
            intermediate_steps: Steps the LLM has taken to date,
                along with observations.
            callbacks: Callbacks to run.
            **kwargs: User inputs.

        Returns:
            Action specifying what tool to use.
        Nr9   rI   r9   r9   r<   aplan[       zBaseSingleActionAgent.aplanc                 C  rG   7Return the input keys.

        :meta private:
        Nr9   r:   r9   r9   r<   
input_keysn   rK   z BaseSingleActionAgent.input_keysearly_stopping_methodstrr   c                 K  &   |dkrt ddidS td| d)  Return response when agent has been stopped due to max iterations.

        Args:
            early_stopping_method: Method to use for early stopping.
            intermediate_steps: Steps the LLM has taken to date,
                along with observations.
            **kwargs: User inputs.

        Returns:
            AgentFinish: Agent finish object.

        Raises:
            ValueError: If `early_stopping_method` is not supported.
        forcer8   3Agent stopped due to iteration limit or time limit. 'Got unsupported early_stopping_method ``r   
ValueErrorr;   rS   rB   rE   r9   r9   r<   return_stopped_responsev   s   
z-BaseSingleActionAgent.return_stopped_responsellmr   toolsSequence[BaseTool]callback_managerOptional[BaseCallbackManager]c                 K     t )a.  Construct an agent from an LLM and tools.

        Args:
            llm: Language model to use.
            tools: Tools to use.
            callback_manager: Callback manager to use.
            kwargs: Additional arguments.

        Returns:
            BaseSingleActionAgent: Agent object.
        NotImplementedError)clsr`   ra   rc   rE   r9   r9   r<   from_llm_and_tools   s   z(BaseSingleActionAgent.from_llm_and_toolsc                 C  re   z#Return Identifier of an agent type.rf   r:   r9   r9   r<   _agent_type      z!BaseSingleActionAgent._agent_typer   c                   s\   t   }z| j}W n ty   d}Y nw t|tr$t|j|d< |S |dur,||d< |S )z{Return dictionary representation of agent.

        Returns:
            Dict: Dictionary representation of agent.
        N_type)super
model_dumprk   rg   
isinstancer-   rT   value)r;   rE   _dictrm   	__class__r9   r<   dict   s   


zBaseSingleActionAgent.dict	file_pathUnion[Path, str]Nonec                 C  s   t |tr
t|}n|}|j}|jddd |  }d|vr&td|  d|jdkrKt|d}t	j
||dd	 W d
   d
S 1 sDw   Y  d
S |jdrqt|d}tj
||dd W d
   d
S 1 sjw   Y  d
S t| d)zSave the agent.

        Args:
            file_path: Path to file to save the agent to.

        Example:
        .. code-block:: python

            # If working with agent executor
            agent.agent.save(file_path="path/agent.yaml")
        Tparentsexist_okrm   Agent z does not support saving.jsonw   indentNz.yamlz.ymlFZdefault_flow_style must be json or yaml)rp   rT   r   parentmkdirru   rg   suffixopenjsondumpendswithyamlr]   )r;   rv   	save_pathdirectory_path
agent_dictfr9   r9   r<   save   s"   


""zBaseSingleActionAgent.savec                 C     i S #Return logging kwargs for tool run.r9   r:   r9   r9   r<   tool_run_logging_kwargs   s   z-BaseSingleActionAgent.tool_run_logging_kwargsr3   r4   r3   r?   r@   rB   rC   rD   r   rE   r   r3   rF   rS   rT   rB   rC   rE   r   r3   r   )
r`   r   ra   rb   rc   rd   rE   r   r3   r2   r3   rT   rE   r   r3   r   rv   rw   r3   rx   r3   r   )__name__
__module____qualname____doc__propertyr=   rA   r   rJ   rN   rR   r_   classmethodri   rk   ru   r   r   __classcell__r9   r9   rs   r<   r2   =   s.    


#r2   c                      s   e Zd ZdZed(ddZd)ddZe		d*d+ddZe		d*d+ddZ	eed(ddZ
d,ddZed-ddZd. fdd Zd/d$d%Zd0d&d'Z  ZS )1BaseMultiActionAgentzBase Multi Action Agent class.r3   r4   c                 C  r5   r6   r9   r:   r9   r9   r<   r=      r>   z"BaseMultiActionAgent.return_valuesr?   c                 C  rG   )z]Get allowed tools.

        Returns:
            Optional[List[str]]: Allowed tools.
        Nr9   r:   r9   r9   r<   rA      s   z&BaseMultiActionAgent.get_allowed_toolsNrB   rC   rD   r   rE   r   %Union[List[AgentAction], AgentFinish]c                 K  rG   )a5  Given input, decided what to do.

        Args:
            intermediate_steps: Steps the LLM has taken to date,
                along with the observations.
            callbacks: Callbacks to run.
            **kwargs: User inputs.

        Returns:
            Actions specifying what tool to use.
        Nr9   rI   r9   r9   r<   rJ      rK   zBaseMultiActionAgent.planc                   rL   )a;  Async given input, decided what to do.

        Args:
            intermediate_steps: Steps the LLM has taken to date,
                along with the observations.
            callbacks: Callbacks to run.
            **kwargs: User inputs.

        Returns:
            Actions specifying what tool to use.
        Nr9   rI   r9   r9   r<   rN   
  rO   zBaseMultiActionAgent.aplanc                 C  rG   rP   r9   r:   r9   r9   r<   rR     rK   zBaseMultiActionAgent.input_keysrS   rT   r   c                 K  rU   )rV   rW   r8   z$Agent stopped due to max iterations.rY   rZ   r[   r\   r^   r9   r9   r<   r_   %  s
   
z,BaseMultiActionAgent.return_stopped_responsec                 C  re   rj   rf   r:   r9   r9   r<   rk   A  rl   z BaseMultiActionAgent._agent_typer   c                   s4   t   }z
t| j|d< W |S  ty   Y |S w )*Return dictionary representation of agent.rm   )rn   ro   rT   rk   rg   r;   rE   rr   rs   r9   r<   ru   F  s   
zBaseMultiActionAgent.dictrv   rw   rx   c                 C  s   t |tr
t|}n|}|  }d|vrtd|  d|j}|jddd |jdkrKt|d}t	j
||dd	 W d
   d
S 1 sDw   Y  d
S |jdrqt|d}tj
||dd W d
   d
S 1 sjw   Y  d
S t| d)a  Save the agent.

        Args:
            file_path: Path to file to save the agent to.

        Raises:
            NotImplementedError: If agent does not support saving.
            ValueError: If file_path is not json or yaml.

        Example:
        .. code-block:: python

            # If working with agent executor
            agent.agent.save(file_path="path/agent.yaml")
        rm   r|   z does not support saving.Try   r}   r~   r   r   Nr   Fr   r   )rp   rT   r   ru   rg   r   r   r   r   r   r   r   r   r]   )r;   rv   r   r   r   r   r9   r9   r<   r   O  s"   


""zBaseMultiActionAgent.savec                 C  r   r   r9   r:   r9   r9   r<   r   v  rl   z,BaseMultiActionAgent.tool_run_logging_kwargsr   r   r@   rB   rC   rD   r   rE   r   r3   r   r   r   r   r   r   )r   r   r   r   r   r=   rA   r   rJ   rN   rR   r_   rk   ru   r   r   r   r9   r9   rs   r<   r      s(    


	'r   c                   @     e Zd ZdZed	ddZdS )
AgentOutputParserz=Base class for parsing agent output into agent action/finish.textrT   r3   rF   c                 C  rG   )z$Parse text into agent action/finish.Nr9   r;   r   r9   r9   r<   parse  rK   zAgentOutputParser.parseN)r   rT   r3   rF   r   r   r   r   r   r   r9   r9   r9   r<   r   |  s    r   c                   @  r   )
MultiActionAgentOutputParserzBase class for parsing agent output into agent actions/finish.

    This is used for agents that can return multiple actions.
    r   rT   r3   r   c                 C  rG   )zParse text into agent actions/finish.

        Args:
            text: Text to parse.

        Returns:
            Union[List[AgentAction], AgentFinish]:
                List of agent actions or agent finish.
        Nr9   r   r9   r9   r<   r     rK   z"MultiActionAgentOutputParser.parseN)r   rT   r3   r   r   r9   r9   r9   r<   r     s    r   c                   @     e Zd ZU dZded< 	 g Zded< g Zded< dZded	< 	 edd
Z	e
dddZe
dddZ	ddddZ	ddddZdS )RunnableAgentAgent powered by Runnables.z/Runnable[dict, Union[AgentAction, AgentFinish]]runnabler4   input_keys_argreturn_keys_argTboolstream_runnableZarbitrary_types_allowedr3   c                 C     | j S r7   r   r:   r9   r9   r<   r=     r>   zRunnableAgent.return_valuesc                 C  r   )zReturn the input keys.r   r:   r9   r9   r<   rR     r>   zRunnableAgent.input_keysNrB   rC   rD   r   rE   r   rF   c                 K  f   i |d|i}d}| j r'| jj|d|idD ]}|du r |}q||7 }q|S | jj|d|id}|S aP  Based on past history and current inputs, decide what to do.

        Args:
            intermediate_steps: Steps the LLM has taken to date,
                along with the observations.
            callbacks: Callbacks to run.
            **kwargs: User inputs.

        Returns:
            Action specifying what tool to use.
        rB   NrD   configr   r   streamZinvoker;   rB   rD   rE   inputsfinal_outputchunkr9   r9   r<   rJ     s   
zRunnableAgent.planc                   x   i |d|i}d}| j r-| jj|d|id2 z3 dH W }|du r%|}q||7 }q6 |S | jj|d|idI dH }|S aR  Async based on past history and current inputs, decide what to do.

        Args:
            intermediate_steps: Steps the LLM has taken to date,
                along with observations.
            callbacks: Callbacks to run.
            **kwargs: User inputs.

        Returns:
            Action specifying what tool to use.
        rB   NrD   r   r   r   astreamZainvoker   r9   r9   r<   rN     s    
zRunnableAgent.aplanr   r@   r   r   r   r   r   __annotations__r   r   r   r(   Zmodel_configr   r=   rR   rJ   rN   r9   r9   r9   r<   r     s&   
 'r   c                   @  r   )RunnableMultiActionAgentr   z5Runnable[dict, Union[List[AgentAction], AgentFinish]]r   r4   r   r   Tr   r   r   r3   c                 C  r   r   r   r:   r9   r9   r<   r=     r>   z&RunnableMultiActionAgent.return_valuesc                 C  r   )QReturn the input keys.

        Returns:
            List of input keys.
        r   r:   r9   r9   r<   rR     s   z#RunnableMultiActionAgent.input_keysNrB   rC   rD   r   rE   r   r   c                 K  r   r   r   r   r9   r9   r<   rJ   (  s   
zRunnableMultiActionAgent.planc                   r   r   r   r   r9   r9   r<   rN   O  s    
zRunnableMultiActionAgent.aplanr   r@   r   r   r9   r9   r9   r<   r     s&   
 *r   z0.1.0z1.0)messageZremovalc                      sv   e Zd ZU dZded< 	 ded< 	 ded< 	 edd	d
Zd fddZ	ddddZ	ddddZ	d ddZ
  ZS )!LLMSingleActionAgentz$Base class for single action agents.r0   	llm_chainr   output_parserr4   stopr3   c                 C     t t| jjdh S )r   rB   listsetr   rR   r:   r9   r9   r<   rR     s   zLLMSingleActionAgent.input_keysrE   r   r   c                      t   }|d= |S r   r   rn   ru   r   rs   r9   r<   ru        
zLLMSingleActionAgent.dictNrB   rC   rD   r   rF   c                 K  s(   | j jd|| j|d|}| j|S )a4  Given input, decided what to do.

        Args:
            intermediate_steps: Steps the LLM has taken to date,
                along with the observations.
            callbacks: Callbacks to run.
            **kwargs: User inputs.

        Returns:
            Action specifying what tool to use.
        rB   r   rD   Nr9   )r   runr   r   r   r;   rB   rD   rE   r8   r9   r9   r<   rJ     s   zLLMSingleActionAgent.planc                   s0   | j jd|| j|d|I dH }| j|S )rM   r   Nr9   )r   arunr   r   r   r   r9   r9   r<   rN     s   zLLMSingleActionAgent.aplanc                 C  s&   dt | jdkrddS | jd dS )r   rY   r   
llm_prefixobservation_prefix)lenr   r:   r9   r9   r<   r     s
   z,LLMSingleActionAgent.tool_run_logging_kwargsr   r   r@   r   r   )r   r   r   r   r   r   rR   ru   rJ   rN   r   r   r9   r9   rs   r<   r   {  s    
 	r   c                      sF  e Zd ZU dZded< 	 ded< 	 dZded< 	 dK fddZdLddZedMddZ	dNddZ
edMddZdOddZ	dPdQd"d#Z	dPdQd$d%ZdRd'd(ZedMd)d*Zed+d,dSd.d/ZeedTd0d1ZeedTd2d3ZeedUd7d8ZedVd:d;ZeedWd<d=Ze		dXdYdCdDZdZdGdHZd[dIdJZ  ZS )\AgentzAgent that calls the language model and deciding the action.

    This is driven by a LLMChain. The prompt in the LLMChain MUST include
    a variable called "agent_scratchpad" where the agent can put its
    intermediary work.
    r0   r   r   r   Nr?   allowed_toolsrE   r   r3   r   c                   r   r   r   r   rs   r9   r<   ru     r   z
Agent.dictc                 C  r   )zGet allowed tools.)r   r:   r9   r9   r<   rA     s   zAgent.get_allowed_toolsr4   c                 C  r5   r6   r9   r:   r9   r9   r<   r=     r>   zAgent.return_valuesr   rT   c                 C     t d)zsFix the text.

        Args:
            text: Text to fix.

        Returns:
            str: Fixed text.
        z(fix_text not implemented for this agent.r]   r   r9   r9   r<   	_fix_text  s   	zAgent._fix_textc                 C  s    d| j   d| j   gS )N
z
	)r   rstripr:   r9   r9   r<   _stop  s   zAgent._stoprB   rC   Union[str, List[BaseMessage]]c                 C  s<   d}|D ]\}}||j 7 }|d| j | d| j 7 }q|S )zJConstruct the scratchpad that lets the agent continue its thought process.rY   r   )logr   r   )r;   rB   thoughtsactionobservationr9   r9   r<   _construct_scratchpad  s
   
zAgent._construct_scratchpadrD   r   rF   c                 K  s4   | j |fi |}| jjdd|i|}| j|S )rH   rD   Nr9   )get_full_inputsr   predictr   r   )r;   rB   rD   rE   full_inputsfull_outputr9   r9   r<   rJ     s   z
Agent.planc                   sF   | j |fi |}| jjdd|i|I dH }| j|I dH }|S )rM   rD   Nr9   )r   r   Zapredictr   Zaparse)r;   rB   rD   rE   r   r   Zagent_outputr9   r9   r<   rN   '  s
   zAgent.aplanDict[str, Any]c                 K  s&   |  |}|| jd}i ||}|S )a1  Create the full inputs for the LLMChain from intermediate steps.

        Args:
            intermediate_steps: Steps the LLM has taken to date,
                along with observations.
            **kwargs: User inputs.

        Returns:
            Dict[str, Any]: Full inputs for the LLMChain.
        agent_scratchpadr   )r   r   )r;   rB   rE   r   
new_inputsr   r9   r9   r<   r   =  s   
zAgent.get_full_inputsc                 C  r   )rQ   r   r   r:   r9   r9   r<   rR   O  s   zAgent.input_keysaftermoder*   c                 C  sv   | j j}d|jvr9td |jd t|tr"| jd7  _| S t|t	r0| j
d7  _
| S tdt| | S )aF  Validate that prompt matches format.

        Args:
            values: Values to validate.

        Returns:
            Dict: Validated values.

        Raises:
            ValueError: If `agent_scratchpad` is not in prompt.input_variables
             and prompt is not a FewShotPromptTemplate or a PromptTemplate.
        r   zl`agent_scratchpad` should be a variable in prompt.input_variables. Did not find it, so adding it at the end.z
{agent_scratchpad}zGot unexpected prompt type )r   promptZinput_variablesloggerwarningappendrp   r    templater   r   r]   type)r;   r   r9   r9   r<   validate_promptW  s   


zAgent.validate_promptc                 C  rG   )z&Prefix to append the observation with.Nr9   r:   r9   r9   r<   r   t  rK   zAgent.observation_prefixc                 C  rG   )z#Prefix to append the LLM call with.Nr9   r:   r9   r9   r<   r   y  rK   zAgent.llm_prefixra   rb   r   c                 C  rG   )zCreate a prompt for this class.

        Args:
            tools: Tools to use.

        Returns:
            BasePromptTemplate: Prompt template.
        Nr9   rh   ra   r9   r9   r<   create_prompt~  rK   zAgent.create_promptrx   c                 C  rG   )zgValidate that appropriate tools are passed in.

        Args:
            tools: Tools to use.
        Nr9   r  r9   r9   r<   _validate_tools  s   zAgent._validate_toolsc                 K  rG   )z)Get default output parser for this class.Nr9   )rh   rE   r9   r9   r<   _get_default_output_parser  rK   z Agent._get_default_output_parserr`   r   rc   rd   Optional[AgentOutputParser]c           	      K  sN   |  | t|| ||d}dd |D }|p|  }| d|||d|S )aO  Construct an agent from an LLM and tools.

        Args:
            llm: Language model to use.
            tools: Tools to use.
            callback_manager: Callback manager to use.
            output_parser: Output parser to use.
            kwargs: Additional arguments.

        Returns:
            Agent: Agent object.
        )r`   r   rc   c                 S     g | ]}|j qS r9   name.0toolr9   r9   r<   
<listcomp>      z,Agent.from_llm_and_tools.<locals>.<listcomp>)r   r   r   Nr9   )r  r0   r  r  )	rh   r`   ra   rc   r   rE   r   Z
tool_namesZ_output_parserr9   r9   r<   ri     s   
zAgent.from_llm_and_toolsrS   r   c                 K  s   |dkrt ddidS |dkrXd}|D ]\}}||j7 }|d| j | d| j 7 }q|d7 }|| jd}i ||}| jjdi |}	| j|	}
t	|
t rQ|
S t d|	i|	S t
d	| )a  Return response when agent has been stopped due to max iterations.

        Args:
            early_stopping_method: Method to use for early stopping.
            intermediate_steps: Steps the LLM has taken to date,
                along with observations.
            **kwargs: User inputs.

        Returns:
            AgentFinish: Agent finish object.

        Raises:
            ValueError: If `early_stopping_method` is not in ['force', 'generate'].
        rW   r8   rX   rY   generater   zB

I now need to return a final answer based on the previous steps:r   zBearly_stopping_method should be one of `force` or `generate`, got Nr9   )r   r   r   r   r   r   r   r   r   rp   r]   )r;   rS   rB   rE   r   r   r   r   r   r   Zparsed_outputr9   r9   r<   r_     s4   

zAgent.return_stopped_responsec                 C  s   | j | jdS )r   r   r   r:   r9   r9   r<   r     s   zAgent.tool_run_logging_kwargsr   r   r   )r   rT   r3   rT   )rB   rC   r3   r   r@   r   )rB   rC   rE   r   r3   r   r3   r*   r   )ra   rb   r3   r   )ra   rb   r3   rx   )rE   r   r3   r   )NN)r`   r   ra   rb   rc   rd   r   r	  rE   r   r3   r   r   r   )r   r   r   r   r   r   ru   rA   r   r=   r   r   r   rJ   rN   r   rR   r)   r  r   r   r   r   r  r  r  ri   r_   r   r   r9   r9   rs   r<   r     sZ   
 




	
#7r   c                   @  sJ   e Zd ZU dZdZded< 	 dZded< 	 	ddddZ	ddddZdS )ExceptionToolz!Tool that just returns the query.
_ExceptionrT   r  zException tooldescriptionNqueryrun_manager#Optional[CallbackManagerForToolRun]r3   c                 C  s   |S r@   r9   r;   r  r  r9   r9   r<   _run  s   zExceptionTool._run(Optional[AsyncCallbackManagerForToolRun]c                   s   |S r@   r9   r  r9   r9   r<   _arun  s   zExceptionTool._arunr@   )r  rT   r  r  r3   rT   )r  rT   r  r  r3   rT   )	r   r   r   r   r  r   r  r  r  r9   r9   r9   r<   r    s   
 
r  c                   @  s  e Zd ZU dZded< 	 ded< 	 dZded< 	 d	Zd
ed< 	 dZded< 	 dZded< 	 dZ	ded< 	 dZ
ded< 	 e	ddddZedddd!d"Zed#dedd&d'Zedd)d*Zdd.d/Zdd0d1Z	dddd2dd7d8Zedd:d;Zedd<d=Zdd@dAZddFdGZ	dddOdPZ	dddRdSZddVdWZ	ddd]d^Z	ddd`daZ	dddedfZ	dddgdhZ	dddjdkZ 	dddldmZ!	dddndoZ"	dddpdqZ#ddudvZ$ddwdxZ%	ddd~dZ&	ddddZ'dS )AgentExecutorzAgent that is using tools.<Union[BaseSingleActionAgent, BaseMultiActionAgent, Runnable]agentrb   ra   Fr   return_intermediate_steps   zOptional[int]max_iterationsNzOptional[float]max_execution_timerW   rT   rS   z8Union[bool, str, Callable[[OutputParserException], str]]handle_parsing_errorszTUnion[int, Callable[[List[Tuple[AgentAction, str]]], List[Tuple[AgentAction, str]]]]trim_intermediate_stepsrD   r   rE   r   r3   c                 K  s   | d|||d|S )a  Create from agent and tools.

        Args:
            agent: Agent to use.
            tools: Tools to use.
            callbacks: Callbacks to use.
            kwargs: Additional arguments.

        Returns:
            AgentExecutor: Agent executor object.
        )r   ra   rD   Nr9   r9   )rh   r   ra   rD   rE   r9   r9   r<   from_agent_and_toolsG  s   z"AgentExecutor.from_agent_and_toolsr   r   r*   c                 C  sZ   | j }| j}| }|dur+t|tdd |D kr+td| ddd |D  d| S )a  Validate that tools are compatible with agent.

        Args:
            values: Values to validate.

        Returns:
            Dict: Validated values.

        Raises:
            ValueError: If allowed tools are different than provided tools.
        Nc                 S  r
  r9   r  r  r9   r9   r<   r  r  r  z0AgentExecutor.validate_tools.<locals>.<listcomp>zAllowed tools (z!) different than provided tools (c                 S  r
  r9   r  r  r9   r9   r<   r  u  r  ))r   ra   rA   r   r]   )r;   r   ra   r   r9   r9   r<   validate_toolsa  s   zAgentExecutor.validate_toolsbeforevaluesr   c              
   C  s   | d}|rJt|trJz|j}W n ty% } zd}W Y d}~nd}~ww |ttt tf k}|	dd}|rBt
||d|d< |S t||d|d< |S )zConvert runnable to agent if passed in.

        Args:
            values: Values to validate.

        Returns:
            Dict: Validated values.
        r   FNr   T)r   r   )getrp   r!   Z
OutputType	Exceptionr   r
   r   r   popr   r   )rh   r,  r   output_type_Zmulti_actionr   r9   r9   r<   validate_runnable_agenty  s&   



z%AgentExecutor.validate_runnable_agent2Union[BaseSingleActionAgent, BaseMultiActionAgent]c                 C  s   t | jtrtt| jS | jS )aC  Type cast self.agent.

        If the `agent` attribute is a Runnable, it will be converted one of
        RunnableAgentType in the validate_runnable_agent root_validator.

        To support instantiating with a Runnable, here we explicitly cast the type
        to reflect the changes made in the root_validator.
        )rp   r   r!   r   RunnableAgentTyper:   r9   r9   r<   _action_agent  s   
zAgentExecutor._action_agentrv   rw   rx   c                 C  r   )zRaise error - saving not supported for Agent Executors.

        Args:
            file_path: Path to save to.

        Raises:
            ValueError: Saving not supported for agent executors.
        zpSaving not supported for agent executors. If you are trying to save the agent, please use the `.save_agent(...)`r   r;   rv   r9   r9   r<   r     s   	zAgentExecutor.savec                 C  s   | j |S )zZSave the underlying agent.

        Args:
            file_path: Path to save to.
        )r5  r   r6  r9   r9   r<   
save_agent  s   zAgentExecutor.save_agent)include_run_infoasync_r   r8  r9  r,   c                C  s   t | ||| j|dS )ag  Enables iteration over steps taken to reach final output.

        Args:
            inputs: Inputs to the agent.
            callbacks: Callbacks to run.
            include_run_info: Whether to include run info.
            async_: Whether to run async. (Ignored)

        Returns:
            AgentExecutorIterator: Agent executor iterator object.
        )tagsr8  )r,   r:  )r;   r   rD   r8  r9  r9   r9   r<   iter  s   zAgentExecutor.iterr4   c                 C  s   | j jS )rQ   )r5  rR   r:   r9   r9   r<   rR     s   zAgentExecutor.input_keysc                 C  s   | j r
| jjdg S | jjS )z@Return the singular output key.

        :meta private:
        rB   )r!  r5  r=   r:   r9   r9   r<   output_keys  s   zAgentExecutor.output_keysr  r%   c                 C  s   dd | j D | S )zLookup tool by name.

        Args:
            name: Name of tool.

        Returns:
            BaseTool: Tool object.
        c                 S     i | ]}|j |qS r9   r  r  r9   r9   r<   
<dictcomp>      z-AgentExecutor.lookup_tool.<locals>.<dictcomp>)ra   )r;   r  r9   r9   r<   lookup_tool  s   	zAgentExecutor.lookup_tool
iterationsinttime_elapsedfloatc                 C  s4   | j d ur|| j krdS | jd ur|| jkrdS dS )NFT)r#  r$  )r;   rA  rC  r9   r9   r<   _should_continue  s   

zAgentExecutor._should_continuer8   r   rB   r   r  $Optional[CallbackManagerForChainRun]r   c                 C  s.   |r|j |d| jd |j}| jr||d< |S Ngreen)colorverboserB   Zon_agent_finishrJ  r=   r!  r;   r8   rB   r  r   r9   r9   r<   _return  s   zAgentExecutor._return)Optional[AsyncCallbackManagerForChainRun]c                   s6   |r|j |d| jdI d H  |j}| jr||d< |S rG  rK  rL  r9   r9   r<   _areturn  s   zAgentExecutor._areturnNextStepOutput1Union[AgentFinish, List[Tuple[AgentAction, str]]]c                 C  s4   t |d trt|dksJ |d S dd |D S )Nr&     c                 S  s"   g | ]}t |tr|j|jfqS r9   )rp   r   r   r   r  ar9   r9   r<   r  %  s
    

z4AgentExecutor._consume_next_step.<locals>.<listcomp>)rp   r   r   )r;   r,  r9   r9   r<   _consume_next_step  s   z AgentExecutor._consume_next_stepname_to_tool_mapDict[str, BaseTool]color_mappingDict[str, str]rC   c              
   C  s"   |  dd | |||||D S )Nc                 S  s   g | ]}|qS r9   r9   rS  r9   r9   r<   r  2  s    z1AgentExecutor._take_next_step.<locals>.<listcomp>)rU  _iter_next_stepr;   rV  rX  r   rB   r  r9   r9   r<   _take_next_step)  s   zAgentExecutor._take_next_step4Iterator[Union[AgentFinish, AgentAction, AgentStep]]c              
   c  s   z|  |}| jj|fd|r| ndi|}W n ty } zt| jtr-| j }nd}|r:tdt	| t	|}	t| jtrU|j
rRt	|j}
t	|j}	nd}
nt| jt	r_| j}
nt| jrj| |}
ntdtd|
|	}|r}|j|dd	 | j }t j|jf| jd|r| ndd
|}
t||
dV  W Y d}~dS d}~ww t|tr|V  dS t|tr|g}n|}|D ]}|V  q|D ]}| ||||V  qdS )Take a single step in the thought-action-observation loop.

        Override this to take control of how the agent makes and acts on choices.
        rD   NFAn output parsing error occurred. In order to pass this error back to the agent and have it try again, pass `handle_parsing_errors=True` to the AgentExecutor. This is the error: Invalid or incomplete response.Got unexpected type of `handle_parsing_errors`r  rH  rI  rJ  rI  rD   r   r   )_prepare_intermediate_stepsr5  rJ   	get_childr   rp   r%  r   r]   rT   send_to_llmr   
llm_outputcallabler   on_agent_actionr   r  r   
tool_inputrJ  r   r   _perform_agent_action)r;   rV  rX  r   rB   r  r8   eraise_errorr   r   tool_run_kwargsactionsagent_actionr9   r9   r<   rZ  >  sz   






(
zAgentExecutor._iter_next_steprq  r   r   c           
      C  s   |r	|j |dd |j|v r<||j }|j}||j }| j }|r&d|d< |j|jf| j||r4| nd d|}	n"| j }t	 j|jt
| df| jd |rW| nd d|}	t||	dS )NrH  rb  rY   r   rc  Zrequested_tool_nameZavailable_tool_namesrd  )rj  r  return_directr5  r   r   rk  rJ  rf  r.   r   keysr   
r;   rV  rX  rq  r  r  rs  rI  ro  r   r9   r9   r<   rl    s>   






z#AgentExecutor._perform_agent_actionc              
     s*   |  dd | |||||2 I d H S )Nc                   s   g | z3 d H W }|q6 S r@   r9   rS  r9   r9   r<   r    s
    z2AgentExecutor._atake_next_step.<locals>.<listcomp>)rU  _aiter_next_stepr[  r9   r9   r<   _atake_next_step  s   
zAgentExecutor._atake_next_step9AsyncIterator[Union[AgentFinish, AgentAction, AgentStep]]c              
    s  z |}jj|fdr ndi|I dH }W n ty } z~tjtr0j }nd}|r=tdt	| t	|}	tjtrX|j
rUt	|j}
t	|j}	nd}
ntjt	rbj}
ntjrm|}
ntdtd|
|	}j }t j|jfjdr ndd|I dH }
t||
d	V  W Y d}~dS d}~ww t|tr|V  dS t|tr|g}n|}|D ]}|V  qtj fd
d|D  I dH }|D ]}|V  qdS )r^  rD   NFr_  r`  ra  r  rc  rd  c                   s   g | ]
}  |qS r9   )_aperform_agent_action)r  rq  rX  rV  r  r;   r9   r<   r    s    z2AgentExecutor._aiter_next_step.<locals>.<listcomp>)re  r5  rN   rf  r   rp   r%  r   r]   rT   rg  r   rh  ri  r   r   r  r   rk  rJ  r   r   asynciogather)r;   rV  rX  r   rB   r  r8   rm  rn  r   r   ro  rp  rq  resultr   r9   rz  r<   rv    s|   





&


zAgentExecutor._aiter_next_stepc           
        s   |r|j || jddI d H  |j|v rE||j }|j}||j }| j }|r,d|d< |j|jf| j||r:| nd d|I d H }	n%| j }t	 j|jt
| df| jd |r`| nd d|I d H }	t||	dS )NrH  )rJ  rI  rY   r   rc  rr  rd  )rj  rJ  r  rs  r5  r   r   rk  rf  r.   r   rt  r   ru  r9   r9   r<   ry    sD   






z$AgentExecutor._aperform_agent_actionc                 C  s  dd | j D }tdd | j D ddgd}g }d}d	}t }| ||rm| j|||||d
}	t|	tr=| j|	||d
S ||	 t	|	dkr]|	d }
| 
|
}|dur]| j|||d
S |d7 }t | }| ||s&| jj| j|fi |}| j|||d
S )z(Run text through and get agent response.c                 S  r=  r9   r  r  r9   r9   r<   r>  L  r?  z'AgentExecutor._call.<locals>.<dictcomp>c                 S  r
  r9   r  r  r9   r9   r<   r  O  r  z'AgentExecutor._call.<locals>.<listcomp>rH  redZexcluded_colorsr           r  rR  N)ra   r&   timerE  r\  rp   r   rM  extendr   _get_tool_returnr5  r_   rS   r;   r   r  rV  rX  rB   rA  rC  
start_timenext_step_outputZnext_step_actionZtool_returnr8   r9   r9   r<   _callE  sJ   


zAgentExecutor._callc              	     s  dd | j D }tdd | j D dgd}g }d}d}t }zt| j4 I d	H  | ||r| j|||||d
I d	H }	t|	trY| j	|	||d
I d	H W  d	  I d	H  W S |
|	 t|	dkr|	d }
| |
}|d	ur| j	|||d
I d	H W  d	  I d	H  W S |d7 }t | }| ||s1| jj| j|fi |}| j	|||d
I d	H W  d	  I d	H  W S 1 I d	H sw   Y  W d	S  ttjfy   | jj| j|fi |}| j	|||d
I d	H  Y S w )z.Async run text through and get agent response.c                 S  r=  r9   r  r  r9   r9   r<   r>  {  r?  z(AgentExecutor._acall.<locals>.<dictcomp>c                 S  r
  r9   r  r  r9   r9   r<   r  ~  r  z(AgentExecutor._acall.<locals>.<listcomp>rH  r  r   r  Nr  rR  )ra   r&   r  r1   r$  rE  rw  rp   r   rO  r  r   r  r5  r_   rS   TimeoutErrorr{  r  r9   r9   r<   _acallt  sr   





4"zAgentExecutor._acallr  Tuple[AgentAction, str]Optional[AgentFinish]c                 C  s`   |\}}dd | j D }d}t| jjdkr| jjd }|j|v r.||j jr.t||idS dS )z&Check if the tool is a returning tool.c                 S  r=  r9   r  r  r9   r9   r<   r>    r?  z2AgentExecutor._get_tool_return.<locals>.<dictcomp>r8   r   rY   N)ra   r   r5  r=   r  rs  r   )r;   r  rq  r   rV  Zreturn_value_keyr9   r9   r<   r    s   
zAgentExecutor._get_tool_returnc                 C  s>   t | jtr| jdkr|| j d  S t| jr| |S |S )Nr   )rp   r'  rB  ri  )r;   rB   r9   r9   r<   re    s   



z)AgentExecutor._prepare_intermediate_stepsinputUnion[Dict[str, Any], Any]r   Optional[RunnableConfig]Iterator[AddableDict]c                 k  s\    t |}t| ||df|d|d|d|ddd|}|D ]}|V  q&dS )	a  Enables streaming over steps taken to reach final output.

        Args:
            input: Input to the agent.
            config: Config to use.
            kwargs: Additional arguments.

        Yields:
            AddableDict: Addable dictionary.
        rD   r:  metadatarun_namerun_idTr:  r  r  r  Zyield_actionsNr#   r,   r-  r;   r  r   rE   iteratorstepr9   r9   r<   r     s$   	zAgentExecutor.streamAsyncIterator[AddableDict]c                 K sf   t |}t| ||df|d|d|d|ddd|}|2 z	3 dH W }|V  q&6 dS )	a	  Async enables streaming over steps taken to reach final output.

        Args:
            input: Input to the agent.
            config: Config to use.
            kwargs: Additional arguments.

        Yields:
            AddableDict: Addable dictionary.
        rD   r:  r  r  r  Tr  Nr  r  r9   r9   r<   r     s$   	zAgentExecutor.astreamr@   )
r   r  ra   rb   rD   r   rE   r   r3   r  r  )r,  r   r3   r   )r3   r3  r   )
r   r   rD   r   r8  r   r9  r   r3   r,   r   )r  rT   r3   r%   )rA  rB  rC  rD  r3   r   )r8   r   rB   r   r  rF  r3   r   )r8   r   rB   r   r  rN  r3   r   )r,  rP  r3   rQ  )rV  rW  rX  rY  r   rY  rB   rC   r  rF  r3   rQ  )rV  rW  rX  rY  r   rY  rB   rC   r  rF  r3   r]  )
rV  rW  rX  rY  rq  r   r  rF  r3   r   )rV  rW  rX  rY  r   rY  rB   rC   r  rN  r3   rQ  )rV  rW  rX  rY  r   rY  rB   rC   r  rN  r3   rx  )
rV  rW  rX  rY  rq  r   r  rN  r3   r   )r   rY  r  rF  r3   r   )r   rY  r  rN  r3   rY  )r  r  r3   r  )rB   rC   r3   rC   )r  r  r   r  rE   r   r3   r  )r  r  r   r  rE   r   r3   r  )(r   r   r   r   r   r!  r#  r$  rS   r%  r'  r   r(  r)   r*  r2  r   r5  r   r7  r;  rR   r<  r@  rE  rM  rO  rU  r\  rZ  rl  rw  rv  ry  r  r  r  re  r   r   r9   r9   r9   r<   r    s   
 









R-Z,2
>
"r  )`r   
__future__r   r{  r   loggingr  abcr   pathlibr   typingr   r   r   r   r	   r
   r   r   r   r   r   r   Zlangchain_core._apir   Zlangchain_core.agentsr   r   r   Zlangchain_core.callbacksr   r   r   r   r   r   Zlangchain_core.exceptionsr   Zlangchain_core.language_modelsr   Zlangchain_core.messagesr   Zlangchain_core.output_parsersr   Zlangchain_core.promptsr   Zlangchain_core.prompts.few_shotr   Zlangchain_core.prompts.promptr    Zlangchain_core.runnablesr!   r"   r#   Zlangchain_core.runnables.utilsr$   Zlangchain_core.toolsr%   Zlangchain_core.utils.inputr&   Zpydanticr'   r(   r)   Ztyping_extensionsr*   Zlangchain._api.deprecationr+   Zlangchain.agents.agent_iteratorr,   Zlangchain.agents.agent_typesr-   Zlangchain.agents.toolsr.   Zlangchain.chains.baser/   Zlangchain.chains.llmr0   Zlangchain.utilities.asyncior1   	getLoggerr   r   r2   r   r   r   r   r   r   r   r  rP  r4  r  r9   r9   r9   r<   <module>   s|    4 
 + 
muS  &