o
    Jjg                     @  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 eOePZQG dd de>ZRG dd  d e>ZSG d!d" d"e,eeef  ZTG d#d$ d$e,eee ef  ZUG d%d& d&eRZVG d'd( d(eSZWed)d*d+d,G d-d. d.eRZXed)d*d+d,G d/d0 d0eRZYG d1d2 d2e:ZZeeeeef  Z[eeVeWf Z\G d3d4 d4eJ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)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 selfr8   r8   N/var/www/html/zoom/venv/lib/python3.10/site-packages/langchain/agents/agent.pyreturn_values?      z#BaseSingleActionAgent.return_valuesOptional[List[str]]c                 C  s   d S Nr8   r9   r8   r8   r;   get_allowed_toolsD   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.
        Nr8   r:   rA   rC   rD   r8   r8   r;   planG       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.
        Nr8   rH   r8   r8   r;   aplanZ       zBaseSingleActionAgent.aplanc                 C  rF   7Return the input keys.

        :meta private:
        Nr8   r9   r8   r8   r;   
input_keysm   rJ   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.
        forcer7   3Agent stopped due to iteration limit or time limit. 'Got unsupported early_stopping_method ``r   
ValueErrorr:   rR   rA   rD   r8   r8   r;   return_stopped_responseu   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_   r`   rb   rD   r8   r8   r;   from_llm_and_tools   s   z(BaseSingleActionAgent.from_llm_and_toolsc                 C  rd   z#Return Identifier of an agent type.re   r9   r8   r8   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_dumprj   rf   
isinstancer,   rS   value)r:   rD   _dictrl   	__class__r8   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_okrl   Agent z does not support saving.jsonw   indentNz.yamlz.ymlFdefault_flow_style must be json or yaml)ro   rS   r   parentmkdirrt   rf   suffixopenjsondumpendswithyamlr\   )r:   ru   	save_pathdirectory_path
agent_dictfr8   r8   r;   save   s"   


""zBaseSingleActionAgent.savec                 C     i S #Return logging kwargs for tool run.r8   r9   r8   r8   r;   tool_run_logging_kwargs   s   z-BaseSingleActionAgent.tool_run_logging_kwargsr2   r3   r2   r>   r?   rA   rB   rC   r   rD   r   r2   rE   rR   rS   rA   rB   rD   r   r2   r   )
r_   r   r`   ra   rb   rc   rD   r   r2   r1   r2   rS   rD   r   r2   r   ru   rv   r2   rw   r2   r   )__name__
__module____qualname____doc__propertyr<   r@   r   rI   rM   rQ   r^   classmethodrh   rj   rt   r   r   __classcell__r8   r8   rr   r;   r1   <   s.    


#r1   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.r2   r3   c                 C  r4   r5   r8   r9   r8   r8   r;   r<      r=   z"BaseMultiActionAgent.return_valuesr>   c                 C  rF   )z]Get allowed tools.

        Returns:
            Optional[List[str]]: Allowed tools.
        Nr8   r9   r8   r8   r;   r@      s   z&BaseMultiActionAgent.get_allowed_toolsNrA   rB   rC   r   rD   r   %Union[List[AgentAction], AgentFinish]c                 K  rF   )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.
        Nr8   rH   r8   r8   r;   rI      rJ   zBaseMultiActionAgent.planc                   rK   )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.
        Nr8   rH   r8   r8   r;   rM   	  rN   zBaseMultiActionAgent.aplanc                 C  rF   rO   r8   r9   r8   r8   r;   rQ     rJ   zBaseMultiActionAgent.input_keysrR   rS   r   c                 K  rT   )rU   rV   r7   z$Agent stopped due to max iterations.rX   rY   rZ   r[   r]   r8   r8   r;   r^   $  s
   
z,BaseMultiActionAgent.return_stopped_responsec                 C  rd   ri   re   r9   r8   r8   r;   rj   @  rk   z BaseMultiActionAgent._agent_typer   c                   s4   t   }z
t| j|d< W |S  ty   Y |S w )*Return dictionary representation of agent.rl   )rm   rn   rS   rj   rf   r:   rD   rq   rr   r8   r;   rt   E  s   
zBaseMultiActionAgent.dictru   rv   rw   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")
        rl   r{   z does not support saving.Trx   r|   r}   r~   r   Nr   Fr   r   )ro   rS   r   rt   rf   r   r   r   r   r   r   r   r   r\   )r:   ru   r   r   r   r   r8   r8   r;   r   N  s"   


""zBaseMultiActionAgent.savec                 C  r   r   r8   r9   r8   r8   r;   r   u  rk   z,BaseMultiActionAgent.tool_run_logging_kwargsr   r   r?   rA   rB   rC   r   rD   r   r2   r   r   r   r   r   r   )r   r   r   r   r   r<   r@   r   rI   rM   rQ   r^   rj   rt   r   r   r   r8   r8   rr   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.textrS   r2   rE   c                 C  rF   )z$Parse text into agent action/finish.Nr8   r:   r   r8   r8   r;   parse~  rJ   zAgentOutputParser.parseN)r   rS   r2   rE   r   r   r   r   r   r   r8   r8   r8   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   rS   r2   r   c                 C  rF   )zParse text into agent actions/finish.

        Args:
            text: Text to parse.

        Returns:
            Union[List[AgentAction], AgentFinish]:
                List of agent actions or agent finish.
        Nr8   r   r8   r8   r;   r     rJ   z"MultiActionAgentOutputParser.parseN)r   rS   r2   r   r   r8   r8   r8   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]]runnabler3   input_keys_argreturn_keys_argTboolstream_runnablearbitrary_types_allowedr2   c                 C     | j S r6   r   r9   r8   r8   r;   r<     r=   zRunnableAgent.return_valuesc                 C  r   )zReturn the input keys.r   r9   r8   r8   r;   rQ     r=   zRunnableAgent.input_keysNrA   rB   rC   r   rD   r   rE   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.
        rA   NrC   configr   r   streaminvoker:   rA   rC   rD   inputsfinal_outputchunkr8   r8   r;   rI     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.
        rA   NrC   r   r   r   astreamainvoker   r8   r8   r;   rM     s    
zRunnableAgent.aplanr   r?   r   r   r   r   r   __annotations__r   r   r   r(   model_configr   r<   rQ   rI   rM   r8   r8   r8   r;   r     s&   
 'r   c                   @  r   )RunnableMultiActionAgentr   z5Runnable[dict, Union[List[AgentAction], AgentFinish]]r   r3   r   r   Tr   r   r   r2   c                 C  r   r   r   r9   r8   r8   r;   r<     r=   z&RunnableMultiActionAgent.return_valuesc                 C  r   )QReturn the input keys.

        Returns:
            List of input keys.
        r   r9   r8   r8   r;   rQ     s   z#RunnableMultiActionAgent.input_keysNrA   rB   rC   r   rD   r   r   c                 K  r   r   r   r   r8   r8   r;   rI   '  s   
zRunnableMultiActionAgent.planc                   r   r   r   r   r8   r8   r;   rM   N  s    
zRunnableMultiActionAgent.aplanr   r?   r   r   r8   r8   r8   r;   r     s&   
 *r   z0.1.0zpUse new agent constructor methods like create_react_agent, create_json_agent, create_structured_chat_agent, etc.z1.0)message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.r/   	llm_chainr   output_parserr3   stopr2   c                 C     t t| jjdh S )r   rA   listsetr   rQ   r9   r8   r8   r;   rQ     s   zLLMSingleActionAgent.input_keysrD   r   r   c                      t   }|d= |S r   r   rm   rt   r   rr   r8   r;   rt        
zLLMSingleActionAgent.dictNrA   rB   rC   r   rE   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.
        rA   r   rC   Nr8   )r   runr   r   r   r:   rA   rC   rD   r7   r8   r8   r;   rI     s   zLLMSingleActionAgent.planc                   s0   | j jd|| j|d|I dH }| j|S )rL   r   Nr8   )r   arunr   r   r   r   r8   r8   r;   rM     s   zLLMSingleActionAgent.aplanc                 C  s&   dt | jdkrddS | jd dS )r   rX   r   
llm_prefixobservation_prefix)lenr   r9   r8   r8   r;   r     s
   z,LLMSingleActionAgent.tool_run_logging_kwargsr   r   r?   r   r   )r   r   r   r   r   r   rQ   rt   rI   rM   r   r   r8   r8   rr   r;   r   z  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.
    r/   r   r   r   Nr>   allowed_toolsrD   r   r2   r   c                   r   r   r   r   rr   r8   r;   rt     r   z
Agent.dictc                 C  r   )zGet allowed tools.)r   r9   r8   r8   r;   r@     s   zAgent.get_allowed_toolsr3   c                 C  r4   r5   r8   r9   r8   r8   r;   r<     r=   zAgent.return_valuesr   rS   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   r8   r8   r;   	_fix_text  s   	zAgent._fix_textc                 C  s    d| j   d| j   gS )N
z
	)r   rstripr9   r8   r8   r;   _stop  s   zAgent._stoprA   rB   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.rX   r   )logr   r   )r:   rA   thoughtsactionobservationr8   r8   r;   _construct_scratchpad  s
   
zAgent._construct_scratchpadrC   r   rE   c                 K  s4   | j |fi |}| jjdd|i|}| j|S )rG   rC   Nr8   )get_full_inputsr   predictr   r   )r:   rA   rC   rD   full_inputsfull_outputr8   r8   r;   rI     s   z
Agent.planc                   sF   | j |fi |}| jjdd|i|I dH }| j|I dH }|S )rL   rC   Nr8   )r   r   apredictr   aparse)r:   rA   rC   rD   r   r   agent_outputr8   r8   r;   rM   ,  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:   rA   rD   r   
new_inputsr   r8   r8   r;   r   B  s   
zAgent.get_full_inputsc                 C  r   )rP   r  r   r9   r8   r8   r;   rQ   T  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   promptinput_variablesloggerwarningappendro   r    templater   r   r\   type)r:   r  r8   r8   r;   validate_prompt\  s   


zAgent.validate_promptc                 C  rF   )z&Prefix to append the observation with.Nr8   r9   r8   r8   r;   r   y  rJ   zAgent.observation_prefixc                 C  rF   )z#Prefix to append the LLM call with.Nr8   r9   r8   r8   r;   r   ~  rJ   zAgent.llm_prefixr`   ra   r   c                 C  rF   )zCreate a prompt for this class.

        Args:
            tools: Tools to use.

        Returns:
            BasePromptTemplate: Prompt template.
        Nr8   rg   r`   r8   r8   r;   create_prompt  rJ   zAgent.create_promptrw   c                 C  rF   )zgValidate that appropriate tools are passed in.

        Args:
            tools: Tools to use.
        Nr8   r  r8   r8   r;   _validate_tools  s   zAgent._validate_toolsc                 K  rF   )z)Get default output parser for this class.Nr8   )rg   rD   r8   r8   r;   _get_default_output_parser  rJ   z Agent._get_default_output_parserr_   r   rb   rc   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  rb   c                 S     g | ]}|j qS r8   name.0toolr8   r8   r;   
<listcomp>      z,Agent.from_llm_and_tools.<locals>.<listcomp>)r   r   r   Nr8   )r  r/   r  r  )	rg   r_   r`   rb   r   rD   r   
tool_names_output_parserr8   r8   r;   rh     s   
zAgent.from_llm_and_toolsrR   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'].
        rV   r7   rW   rX   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 Nr8   )r   r   r   r   r   r   r   r   r   ro   r\   )r:   rR   rA   rD   r   r   r   r  r   r   parsed_outputr8   r8   r;   r^     s4   

zAgent.return_stopped_responsec                 C  s   | j | jdS )r   r   r   r9   r8   r8   r;   r     s   zAgent.tool_run_logging_kwargsr   r   r   )r   rS   r2   rS   )rA   rB   r2   r   r?   r   )rA   rB   rD   r   r2   r   r2   r*   r   )r`   ra   r2   r   )r`   ra   r2   rw   )rD   r   r2   r   )NN)r_   r   r`   ra   rb   rc   r   r  rD   r   r2   r   r   r   )r   r   r   r   r   r   rt   r@   r   r<   r   r   r   rI   rM   r   rQ   r)   r  r   r   r   r   r  r  r  rh   r^   r   r   r8   r8   rr   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.
_ExceptionrS   r  zException tooldescriptionNqueryrun_manager#Optional[CallbackManagerForToolRun]r2   c                 C  s   |S r?   r8   r:   r#  r$  r8   r8   r;   _run	  s   zExceptionTool._run(Optional[AsyncCallbackManagerForToolRun]c                   s   |S r?   r8   r&  r8   r8   r;   _arun  s   zExceptionTool._arunr?   )r#  rS   r$  r%  r2   rS   )r#  rS   r$  r(  r2   rS   )	r   r   r   r   r  r   r"  r'  r)  r8   r8   r8   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]agentra   r`   Fr   return_intermediate_steps   zOptional[int]max_iterationsNzOptional[float]max_execution_timerV   rS   rR   z8Union[bool, str, Callable[[OutputParserException], str]]handle_parsing_errorszTUnion[int, Callable[[List[Tuple[AgentAction, str]]], List[Tuple[AgentAction, str]]]]trim_intermediate_stepsrC   r   rD   r   r2   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,  r`   rC   Nr8   r8   )rg   r,  r`   rC   rD   r8   r8   r;   from_agent_and_toolsL  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  r8   r  r  r8   r8   r;   r  w  r  z0AgentExecutor.validate_tools.<locals>.<listcomp>zAllowed tools (z!) different than provided tools (c                 S  r  r8   r  r  r8   r8   r;   r  z  r  ))r,  r`   r@   r   r\   )r:   r,  r`   r   r8   r8   r;   validate_toolsf  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   )getro   r!   
OutputType	Exceptionr   r
   r   r   popr   r   )rg   r8  r,  output_type_multi_actionr   r8   r8   r;   validate_runnable_agent~  s&   



z%AgentExecutor.validate_runnable_agent2Union[BaseSingleActionAgent, BaseMultiActionAgent]c                 C  s   t | jtrtt| jS | jS )aG  Type cast self.agent.

        The .agent attribute type includes Runnable, but is converted to 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.
        )ro   r,  r!   r   RunnableAgentTyper9   r8   r8   r;   _action_agent  s   
zAgentExecutor._action_agentru   rv   rw   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:   ru   r8   r8   r;   r     s   	zAgentExecutor.savec                 C  s   | j |S )zZSave the underlying agent.

        Args:
            file_path: Path to save to.
        )rC  r   rD  r8   r8   r;   
save_agent  s   zAgentExecutor.save_agent)include_run_infoasync_r   rF  rG  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.
        )tagsrF  )r+   rH  )r:   r   rC   rF  rG  r8   r8   r;   iter  s   zAgentExecutor.iterr3   c                 C  s   | j jS )rP   )rC  rQ   r9   r8   r8   r;   rQ     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:
        rA   )r-  rC  r<   r9   r8   r8   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 r8   r  r  r8   r8   r;   
<dictcomp>      z-AgentExecutor.lookup_tool.<locals>.<dictcomp>)r`   )r:   r  r8   r8   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/  r0  )r:   rO  rQ  r8   r8   r;   _should_continue  s   

zAgentExecutor._should_continuer7   r   rA   r   r$  $Optional[CallbackManagerForChainRun]r   c                 C  s.   |r|j |d| jd |j}| jr||d< |S Ngreen)colorverboserA   on_agent_finishrX  r<   r-  r:   r7   rA   r$  r   r8   r8   r;   _return  s   zAgentExecutor._return)Optional[AsyncCallbackManagerForChainRun]c                   s6   |r|j |d| jdI d H  |j}| jr||d< |S rU  rY  r[  r8   r8   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 )Nr2     c                 S  s"   g | ]}t |tr|j|jfqS r8   )ro   r   r   r   r  ar8   r8   r;   r  *  s
    

z4AgentExecutor._consume_next_step.<locals>.<listcomp>)ro   r   r   )r:   r8  r8   r8   r;   _consume_next_step#  s   z AgentExecutor._consume_next_stepname_to_tool_mapDict[str, BaseTool]color_mappingDict[str, str]rB   c              
   C  s"   |  dd | |||||D S )Nc                 S  s   g | ]}|qS r8   r8   rb  r8   r8   r;   r  7  s    z1AgentExecutor._take_next_step.<locals>.<listcomp>)rd  _iter_next_stepr:   re  rg  r   rA   r$  r8   r8   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.
        rC   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!  rV  rW  rX  rW  rC   r   r   )_prepare_intermediate_stepsrC  rI   	get_childr   ro   r1  r   r\   rS   send_to_llmr   
llm_outputcallabler   on_agent_actionr   r   r   
tool_inputrX  r   r   _perform_agent_action)r:   re  rg  r   rA   r$  r7   eraise_errorr   r   tool_run_kwargsactionsagent_actionr8   r8   r;   ri  C  sz   






(
zAgentExecutor._iter_next_stepr  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 )NrV  rq  rX   r   rr  requested_tool_nameavailable_tool_namesrs  )ry  r  return_directrC  r   r   rz  rX  ru  r-   r   keysr   
r:   re  rg  r  r$  r  r  rW  r~  r   r8   r8   r;   r{    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?   r8   rb  r8   r8   r;   r    s
    z2AgentExecutor._atake_next_step.<locals>.<listcomp>)rd  _aiter_next_steprj  r8   r8   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 )rm  rC   NFrn  ro  rp  r!  rr  rs  c                   s   g | ]
}  |qS r8   )_aperform_agent_action)r  r  rg  re  r$  r:   r8   r;   r    s    z2AgentExecutor._aiter_next_step.<locals>.<listcomp>)rt  rC  rM   ru  r   ro   r1  r   r\   rS   rv  r   rw  rx  r   r   r   r   rz  rX  r   r   asynciogather)r:   re  rg  r   rA   r$  r7   r|  r}  r   r   r~  r  r  resultr   r8   r  r;   r    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 )NrV  )rX  rW  rX   r   rr  r  rs  )ry  rX  r  r  rC  r   r   rz  ru  r-   r   r  r   r  r8   r8   r;   r  !  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  rK  r8   r  r  r8   r8   r;   rL  Q  rM  z'AgentExecutor._call.<locals>.<dictcomp>c                 S  r  r8   r  r  r8   r8   r;   r  T  r  z'AgentExecutor._call.<locals>.<listcomp>rV  redexcluded_colorsr           r$  ra  N)r`   r&   timerS  rk  ro   r   r\  extendr   _get_tool_returnrC  r^   rR   r:   r   r$  re  rg  rA   rO  rQ  
start_timenext_step_outputnext_step_actiontool_returnr7   r8   r8   r;   _callJ  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  rK  r8   r  r  r8   r8   r;   rL    rM  z(AgentExecutor._acall.<locals>.<dictcomp>c                 S  r  r8   r  r  r8   r8   r;   r    r  z(AgentExecutor._acall.<locals>.<listcomp>rV  r  r   r  Nr  ra  )r`   r&   r  r0   r0  rS  r  ro   r   r^  r  r   r  rC  r^   rR   TimeoutErrorr  r  r8   r8   r;   _acally  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  rK  r8   r  r  r8   r8   r;   rL    rM  z2AgentExecutor._get_tool_return.<locals>.<dictcomp>r7   r   rX   N)r`   r   rC  r<   r  r  r   )r:   r  r  r   re  return_value_keyr8   r8   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   )ro   r3  rP  rx  )r:   rA   r8   r8   r;   rt    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.
        rC   rH  metadatarun_namerun_idTrH  r  r  r  yield_actionsNr#   r+   r9  r:   r  r   rD   iteratorstepr8   r8   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.
        rC   rH  r  r  r  Tr  Nr  r  r8   r8   r;   r     s$   	zAgentExecutor.astreamr?   )
r,  r+  r`   ra   rC   r   rD   r   r2   r*  r  )r8  r   r2   r   )r2   rA  r   )
r   r   rC   r   rF  r   rG  r   r2   r+   r   )r  rS   r2   r%   )rO  rP  rQ  rR  r2   r   )r7   r   rA   r   r$  rT  r2   r   )r7   r   rA   r   r$  r]  r2   r   )r8  r_  r2   r`  )re  rf  rg  rh  r   rh  rA   rB   r$  rT  r2   r`  )re  rf  rg  rh  r   rh  rA   rB   r$  rT  r2   rl  )
re  rf  rg  rh  r  r   r$  rT  r2   r   )re  rf  rg  rh  r   rh  rA   rB   r$  r]  r2   r`  )re  rf  rg  rh  r   rh  rA   rB   r$  r]  r2   r  )
re  rf  rg  rh  r  r   r$  r]  r2   r   )r   rh  r$  rT  r2   r   )r   rh  r$  r]  r2   rh  )r  r  r2   r  )rA   rB   r2   rB   )r  r  r   r  rD   r   r2   r  )r  r  r   r  rD   r   r2   r  )(r   r   r   r   r   r-  r/  r0  rR   r1  r3  r   r4  r)   r6  r@  r   rC  r   rE  rI  rQ   rJ  rN  rS  r\  r^  rd  rk  ri  r{  r  r  r  r  r  r  rt  r   r   r8   r8   r8   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   langchain_core._apir   langchain_core.agentsr   r   r   langchain_core.callbacksr   r   r   r   r   r   langchain_core.exceptionsr   langchain_core.language_modelsr   langchain_core.messagesr   langchain_core.output_parsersr   langchain_core.promptsr   langchain_core.prompts.few_shotr   langchain_core.prompts.promptr    langchain_core.runnablesr!   r"   r#   langchain_core.runnables.utilsr$   langchain_core.toolsr%   langchain_core.utils.inputr&   pydanticr'   r(   r)   typing_extensionsr*   langchain.agents.agent_iteratorr+   langchain.agents.agent_typesr,   langchain.agents.toolsr-   langchain.chains.baser.   langchain.chains.llmr/   langchain.utilities.asyncior0   	getLoggerr   r  r1   r   r   r   r   r   r   r   r   r_  rB  r*  r8   r8   r8   r;   <module>   sz    4 
 + 
muS  &