o
    {qi                     @  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Zddl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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lAmBZBmCZC ddlDmEZE ddlFmGZG ddlHmIZI ddlJmKZK ddlLmMZM ddlNmOZO ddlPmQZQ eReSZTG dd  d e>ZUG d!d" d"e>ZVG d#d$ d$e,eeef  ZWG d%d& d&e,eeXe ef  ZYG d'd( d(eUZZG d)d* d*eVZ[ed+eEd,d-G d.d/ d/eUZ\ed+eEd,d-G d0d1 d1eUZ]G d2d3 d3e:Z^eXeeeef  Z_eeZe[f Z`G d4d5 d5eMZadS )6zEChain that takes in an input and produces an action and action input.    )annotationsN)abstractmethod)AsyncIteratorIteratorSequence)Path)AnyCallableOptional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override)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 selfr7   r7   ]/home/app/PaddleOCR-VL/.venv_paddleocr/lib/python3.10/site-packages/langchain/agents/agent.pyreturn_values=      z#BaseSingleActionAgent.return_valuesOptional[list[str]]c                 C  s   d S Nr7   r8   r7   r7   r:   get_allowed_toolsB   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.
        Nr7   r9   r@   rB   rC   r7   r7   r:   planE       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.
        Nr7   rG   r7   r7   r:   aplanX       zBaseSingleActionAgent.aplanc                 C  rE   7Return the input keys.

        :meta private:
        Nr7   r8   r7   r7   r:   
input_keysk   rI   z BaseSingleActionAgent.input_keysearly_stopping_methodstrr   c                 K  *   |dkrt ddidS d| d}t|)  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.
        forcer6   3Agent stopped due to iteration limit or time limit. 'Got unsupported early_stopping_method ``r   
ValueErrorr9   rQ   r@   rC   msgr7   r7   r:   return_stopped_responses   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   rC   r7   r7   r:   from_llm_and_tools   s   z(BaseSingleActionAgent.from_llm_and_toolsc                 C  rd   z#Return Identifier of an agent type.re   r8   r7   r7   r:   _agent_type      z!BaseSingleActionAgent._agent_typebuiltins.dictc                   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+   rR   value)r9   rC   _dictrm   	__class__r7   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'd|  d}t||jdkrL|d}t	j
||dd	 W d
   d
S 1 sEw   Y  d
S |jdrr|d}tj
||dd W d
   d
S 1 skw   Y  d
S | d}t|)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   rR   r   parentmkdirru   rf   suffixopenjsondumpendswithyamlr[   )r9   rv   	save_pathdirectory_path
agent_dictr]   fr7   r7   r:   save   s"   
""
zBaseSingleActionAgent.savec                 C     i S #Return logging kwargs for tool run.r7   r8   r7   r7   r:   tool_run_logging_kwargs   s   z-BaseSingleActionAgent.tool_run_logging_kwargsr1   r2   r1   r=   r>   r@   rA   rB   r   rC   r   r1   rD   rQ   rR   r@   rA   rC   r   r1   r   )
r_   r   r`   ra   rb   rc   rC   r   r1   r0   r1   rR   rC   r   r1   rl   rv   rw   r1   rx   r1   rl   )__name__
__module____qualname____doc__propertyr;   r?   r   rH   rL   rP   r^   classmethodrh   rj   ru   r   r   __classcell__r7   r7   rs   r:   r0   :   s.    


"r0   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.r1   r2   c                 C  r3   r4   r7   r8   r7   r7   r:   r;      r<   z"BaseMultiActionAgent.return_valuesr=   c                 C  rE   )z]Get allowed tools.

        Returns:
            Optional[List[str]]: Allowed tools.
        Nr7   r8   r7   r7   r:   r?      s   z&BaseMultiActionAgent.get_allowed_toolsNr@   rA   rB   r   rC   r   %Union[list[AgentAction], AgentFinish]c                 K  rE   )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.
        Nr7   rG   r7   r7   r:   rH      rI   zBaseMultiActionAgent.planc                   rJ   )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.
        Nr7   rG   r7   r7   r:   rL     rM   zBaseMultiActionAgent.aplanc                 C  rE   rN   r7   r8   r7   r7   r:   rP     rI   zBaseMultiActionAgent.input_keysrQ   rR   r   c                 K  rS   )rT   rU   r6   z$Agent stopped due to max iterations.rW   rX   rY   rZ   r\   r7   r7   r:   r^      s   z,BaseMultiActionAgent.return_stopped_responsec                 C  rd   ri   re   r8   r7   r7   r:   rj   :  rk   z BaseMultiActionAgent._agent_typerl   c                   sH   t   }tt t| j|d< W d   |S 1 sw   Y  |S )*Return dictionary representation of agent.rm   N)rn   ro   
contextlibsuppressrf   rR   rj   r9   rC   rr   rs   r7   r:   ru   ?  s   

zBaseMultiActionAgent.dictrv   rw   rx   c                 C  s   t |tr	t|n|}|  }d|vrd|  d}t||j}|jddd |jdkrL|d}t	j
||dd	 W d
   d
S 1 sEw   Y  d
S |jdrr|d}tj
||dd W d
   d
S 1 skw   Y  d
S | d}t|)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   rR   r   ru   rf   r   r   r   r   r   r   r   r   r[   )r9   rv   r   r   r]   r   r   r7   r7   r:   r   F  s"   
""
zBaseMultiActionAgent.savec                 C  r   r   r7   r8   r7   r7   r:   r   l  rk   z,BaseMultiActionAgent.tool_run_logging_kwargsr   r   r>   r@   rA   rB   r   rC   r   r1   r   r   r   r   r   r   )r   r   r   r   r   r;   r?   r   rH   rL   rP   r^   rj   ru   r   r   r   r7   r7   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.textrR   r1   rD   c                 C  rE   )z$Parse text into agent action/finish.Nr7   r9   r   r7   r7   r:   parseu  rI   zAgentOutputParser.parseN)r   rR   r1   rD   r   r   r   r   r   r   r7   r7   r7   r:   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   rR   r1   r   c                 C  rE   )zParse text into agent actions/finish.

        Args:
            text: Text to parse.

        Returns:
            Union[List[AgentAction], AgentFinish]:
                List of agent actions or agent finish.
        Nr7   r   r7   r7   r:   r     rI   z"MultiActionAgentOutputParser.parseN)r   rR   r1   r   r   r7   r7   r7   r:   r   z  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]]runnabler2   input_keys_argreturn_keys_argTboolstream_runnableZarbitrary_types_allowedr1   c                 C     | j S r5   r   r8   r7   r7   r:   r;     r<   zRunnableAgent.return_valuesc                 C  r   )zReturn the input keys.r   r8   r7   r7   r:   rP     r<   zRunnableAgent.input_keysNr@   rA   rB   r   rC   r   rD   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.
        r@   NrB   configr   r   streamZinvoker9   r@   rB   rC   inputsfinal_outputchunkr7   r7   r:   rH     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.
        r@   NrB   r   r   r   astreamZainvoker   r7   r7   r:   rL     s$   
zRunnableAgent.aplanr   r>   r   r   r   r   r   __annotations__r   r   r   r%   Zmodel_configr   r;   rP   rH   rL   r7   r7   r7   r:   r     s&   
 'r   c                   @  r   )RunnableMultiActionAgentr   z5Runnable[dict, Union[list[AgentAction], AgentFinish]]r   r2   r   r   Tr   r   r   r1   c                 C  r   r   r   r8   r7   r7   r:   r;     r<   z&RunnableMultiActionAgent.return_valuesc                 C  r   )QReturn the input keys.

        Returns:
            List of input keys.
        r   r8   r7   r7   r:   rP     s   z#RunnableMultiActionAgent.input_keysNr@   rA   rB   r   rC   r   r   c                 K  r   r   r   r   r7   r7   r:   rH      s   
zRunnableMultiActionAgent.planc                   r   r   r   r   r7   r7   r:   rL   G  s$   
zRunnableMultiActionAgent.aplanr   r>   r   r   r7   r7   r7   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.r.   	llm_chainr   output_parserr2   stopr1   c                 C     t t| jjdh S )r   r@   listsetr   rP   r8   r7   r7   r:   rP     s   zLLMSingleActionAgent.input_keysrC   r   rl   c                      t   }|d= |S r   r   rn   ru   r   rs   r7   r:   ru        
zLLMSingleActionAgent.dictNr@   rA   rB   r   rD   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.
        r@   r   rB   Nr7   )r   runr   r   r   r9   r@   rB   rC   r6   r7   r7   r:   rH     s   zLLMSingleActionAgent.planc                   s0   | j jd|| j|d|I dH }| j|S )rK   r   Nr7   )r   arunr   r   r   r   r7   r7   r:   rL     s   zLLMSingleActionAgent.aplanc                 C  s&   dt | jdkrddS | jd dS )r   rW   r   
llm_prefixobservation_prefix)lenr   r8   r7   r7   r:   r     s
   z,LLMSingleActionAgent.tool_run_logging_kwargsr   r   r>   r   r   )r   r   r   r   r   r   rP   ru   rH   rL   r   r   r7   r7   rs   r:   r   u  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_toolsrC   r   r1   rl   c                   r   r   r   r   rs   r7   r:   ru     r   z
Agent.dictc                 C  r   )zGet allowed tools.)r   r8   r7   r7   r:   r?     s   zAgent.get_allowed_toolsr2   c                 C  r3   r4   r7   r8   r7   r7   r:   r;     r<   zAgent.return_valuesr   rR   c                 C     d}t |)zsFix the text.

        Args:
            text: Text to fix.

        Returns:
            str: Fixed text.
        z(fix_text not implemented for this agent.r[   )r9   r   r]   r7   r7   r:   	_fix_text  s   	zAgent._fix_textc                 C  s    d| j   d| j   gS )N
z
	)r   rstripr8   r7   r7   r:   _stop  s   zAgent._stopr@   rA   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.rW   r   )logr   r   )r9   r@   thoughtsactionobservationr7   r7   r:   _construct_scratchpad  s
   
zAgent._construct_scratchpadrB   r   rD   c                 K  s4   | j |fi |}| jjdd|i|}| j|S )rF   rB   Nr7   )get_full_inputsr   predictr   r   r9   r@   rB   rC   full_inputsfull_outputr7   r7   r:   rH     s   z
Agent.planc                   sB   | j |fi |}| jjdd|i|I dH }| j|I dH S )rK   rB   Nr7   )r   r   Zapredictr   Zaparser   r7   r7   r:   rL   #  s   zAgent.aplanbuiltins.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   )r9   r@   rC   r   
new_inputsr7   r7   r:   r   8  s   
zAgent.get_full_inputsc                 C  r   )rO   r   r   r8   r7   r7   r:   rP   K  s   zAgent.input_keysaftermoder'   c                 C  sz   | j j}d|jvr;td |jd t|tr"| jd7  _| S t|t	r0| j
d7  _
| S dt| }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   typer[   )r9   r  r]   r7   r7   r:   validate_promptS  s   


zAgent.validate_promptc                 C  rE   )z&Prefix to append the observation with.Nr7   r8   r7   r7   r:   r   q  rI   zAgent.observation_prefixc                 C  rE   )z#Prefix to append the LLM call with.Nr7   r8   r7   r7   r:   r   v  rI   zAgent.llm_prefixr`   ra   r   c                 C  rE   )zCreate a prompt for this class.

        Args:
            tools: Tools to use.

        Returns:
            BasePromptTemplate: Prompt template.
        Nr7   rg   r`   r7   r7   r:   create_prompt{  rI   zAgent.create_promptrx   c                 C  rE   )zgValidate that appropriate tools are passed in.

        Args:
            tools: Tools to use.
        Nr7   r  r7   r7   r:   _validate_tools  rI   zAgent._validate_toolsc                 K  rE   )z)Get default output parser for this class.Nr7   )rg   rC   r7   r7   r:   _get_default_output_parser  rI   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 r7   name.0toolr7   r7   r:   
<listcomp>      z,Agent.from_llm_and_tools.<locals>.<listcomp>)r   r   r   Nr7   )r
  r.   r	  r  )	rg   r_   r`   rb   r   rC   r   Z
tool_namesZ_output_parserr7   r7   r:   rh     s   
zAgent.from_llm_and_toolsrQ   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 d	| }t
|)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'].
        rU   r6   rV   rW   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 Nr7   )r   r   r   r   r   r   r   r   r   rp   r[   )r9   rQ   r@   rC   r   r   r   r   r   r   Zparsed_outputr]   r7   r7   r:   r^     s6   

zAgent.return_stopped_responsec                 C  s   | j | jdS )r   r   r   r8   r7   r7   r:   r     s   zAgent.tool_run_logging_kwargsr   r   r   )r   rR   r1   rR   )r@   rA   r1   r   r>   r   )r@   rA   rC   r   r1   r   r1   r'   r   )r`   ra   r1   r   )r`   ra   r1   rx   )rC   r   r1   r   )NN)r_   r   r`   ra   rb   rc   r   r  rC   r   r1   r   r   r   )r   r   r   r   r   r   ru   r?   r   r;   r   r   r   rH   rL   r   rP   r&   r  r   r   r   r   r	  r
  r  rh   r^   r   r   r7   r7   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.
_ExceptionrR   r  zException tooldescriptionNqueryrun_manager#Optional[CallbackManagerForToolRun]r1   c                 C  s   |S r>   r7   r9   r  r  r7   r7   r:   _run  s   zExceptionTool._run(Optional[AsyncCallbackManagerForToolRun]c                   s   |S r>   r7   r  r7   r7   r:   _arun  s   zExceptionTool._arunr>   )r  rR   r  r  r1   rR   )r  rR   r  r  r1   rR   )	r   r   r   r   r  r   r  r  r   r7   r7   r7   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%e&	ddd~dZ'e&	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_timerU   rR   rQ   z8Union[bool, str, Callable[[OutputParserException], str]]handle_parsing_errorszTUnion[int, Callable[[list[tuple[AgentAction, str]]], list[tuple[AgentAction, str]]]]trim_intermediate_stepsrB   r   rC   r   r1   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`   rB   Nr7   r7   )rg   r#  r`   rB   rC   r7   r7   r:   from_agent_and_toolsC  s   z"AgentExecutor.from_agent_and_toolsr   r   r'   c                 C  sZ   | j }| j}| }|dur+t|dd |D kr+d| ddd |D  d}t|| 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  s   h | ]}|j qS r7   r  r  r7   r7   r:   	<setcomp>m  s    z/AgentExecutor.validate_tools.<locals>.<setcomp>zAllowed tools (z!) different than provided tools (c                 S  r  r7   r  r  r7   r7   r:   r  r  r  z0AgentExecutor.validate_tools.<locals>.<listcomp>))r#  r`   r?   r   r[   )r9   r#  r`   r   r]   r7   r7   r:   validate_tools]  s   zAgentExecutor.validate_toolsbeforevaluesru   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   )rg   r0  r#  output_type_Zmulti_actionr   r7   r7   r:   validate_runnable_agentw  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   RunnableAgentTyper8   r7   r7   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   )r9   rv   r]   r7   r7   r:   r     s   
zAgentExecutor.savec                 C  s   | j |S )zZSave the underlying agent.

        Args:
            file_path: Path to save to.
        )r9  r   )r9   rv   r7   r7   r:   
save_agent  s   zAgentExecutor.save_agent)include_run_infoasync_r   r;  r<  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.
        )tagsr;  )r*   r=  )r9   r   rB   r;  r<  r7   r7   r:   iter  s   zAgentExecutor.iterr2   c                 C  s   | j jS )rO   )r9  rP   r8   r7   r7   r:   rP     s   zAgentExecutor.input_keysc                 C  s   | j rg | jjdS | jjS )z@Return the singular output key.

        :meta private:
        r@   )r$  r9  r;   r8   r7   r7   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 r7   r  r  r7   r7   r:   
<dictcomp>      z-AgentExecutor.lookup_tool.<locals>.<dictcomp>)r`   )r9   r  r7   r7   r:   lookup_tool  s   	zAgentExecutor.lookup_tool
iterationsinttime_elapsedfloatc                 C  s,   | j d ur|| j krdS | jd u p|| jk S )NF)r&  r'  )r9   rD  rF  r7   r7   r:   _should_continue  s   zAgentExecutor._should_continuer6   r   r@   r   r  $Optional[CallbackManagerForChainRun]dict[str, Any]c                 C  s.   |r|j |d| jd |j}| jr||d< |S Ngreen)colorverboser@   Zon_agent_finishrN  r;   r$  r9   r6   r@   r  r   r7   r7   r:   _return  s   zAgentExecutor._return)Optional[AsyncCallbackManagerForChainRun]c                   s6   |r|j |d| jdI d H  |j}| jr||d< |S rK  rO  rP  r7   r7   r:   _areturn  s   zAgentExecutor._areturnNextStepOutput1Union[AgentFinish, list[tuple[AgentAction, str]]]c                 C  s<   t |d trt|dkrd}t||d S dd |D S )Nr)     z>Expected a single AgentFinish output, but got multiple values.c                 S  s"   g | ]}t |tr|j|jfqS r7   )rp   r   r   r   r  ar7   r7   r:   r  "  s   " z4AgentExecutor._consume_next_step.<locals>.<listcomp>)rp   r   r   r[   )r9   r0  r]   r7   r7   r:   _consume_next_step  s   z AgentExecutor._consume_next_stepname_to_tool_mapdict[str, BaseTool]color_mappingdict[str, str]rA   c              
   C  s   |  t| |||||S r>   )rY  r   _iter_next_stepr9   rZ  r\  r   r@   r  r7   r7   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;d|}	t|	|t	|}
t| jtrV|j
rSt	|j}t	|j}
nd}nt| jt	r`| j}nt| jrk| |}nd}	t|	|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.
        rB   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  rL  rM  rN  rM  rB   r   r   )_prepare_intermediate_stepsr9  rH   	get_childr   rp   r(  r   r[   rR   send_to_llmr   
llm_outputcallabler   on_agent_actionr   r  r   
tool_inputrN  r   r   _perform_agent_action)r9   rZ  r\  r   r@   r  r6   eraise_errorr]   r   r   tool_run_kwargsactionsagent_actionr7   r7   r:   r^  8  s~   








*zAgentExecutor._iter_next_stepru  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 )NrL  rf  rW   r   rg  Zrequested_tool_nameZavailable_tool_namesrh  )rn  r  return_directr9  r   r   ro  rN  rj  r,   r   keysr   
r9   rZ  r\  ru  r  r  rw  rM  rs  r   r7   r7   r:   rp    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>   r7   rW  r7   r7   r:   r    s
    z2AgentExecutor._atake_next_step.<locals>.<listcomp>)rY  _aiter_next_stepr_  r7   r7   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 } ztjtr0j }nd}|r>d|}	t|	|t	|}
tjtrY|j
rVt	|j}t	|j}
nd}ntjt	rcj}ntjrn|}nd}	t|	|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 )rb  rB   NFrc  rd  re  r  rg  rh  c                   s   g | ]
}  |qS r7   )_aperform_agent_action)r  ru  r\  rZ  r  r9   r7   r:   r    s    z2AgentExecutor._aiter_next_step.<locals>.<listcomp>)ri  r9  rL   rj  r   rp   r(  r   r[   rR   rk  r   rl  rm  r   r   r  r   ro  rN  r   r   asynciogather)r9   rZ  r\  r   r@   r  r6   rq  rr  r]   r   r   rs  rt  ru  resultr   r7   r~  r:   rz    sz   







(
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 )NrL  )rN  rM  rW   r   rg  rv  rh  )rn  rN  r  rw  r9  r   r   ro  rj  r,   r   rx  r   ry  r7   r7   r:   r}    sH   






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@  r7   r  r  r7   r7   r:   rA  L  rB  z'AgentExecutor._call.<locals>.<dictcomp>c                 S  r  r7   r  r  r7   r7   r:   r  O  r  z'AgentExecutor._call.<locals>.<listcomp>rL  redZexcluded_colorsr           r  rV  N)r`   r#   timerH  r`  rp   r   rQ  extendr   _get_tool_returnr9  r^   rQ   r9   r   r  rZ  r\  r@   rD  rF  
start_timenext_step_outputZnext_step_actionZtool_returnr6   r7   r7   r:   _callE  sV   


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@  r7   r  r  r7   r7   r:   rA    rB  z(AgentExecutor._acall.<locals>.<dictcomp>c                 S  r  r7   r  r  r7   r7   r:   r    r  z(AgentExecutor._acall.<locals>.<listcomp>rL  r  r   r  Nr  rV  )r`   r#   r  r/   r'  rH  r{  rp   r   rS  r  r   r  r9  r^   rQ   TimeoutErrorr  r  r7   r7   r:   _acall{  s   





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@  r7   r  r  r7   r7   r:   rA    rB  z2AgentExecutor._get_tool_return.<locals>.<dictcomp>r6   r   rW   N)r`   r   r9  r;   r  rw  r   )r9   r  ru  r   rZ  Zreturn_value_keyr7   r7   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*  rE  rm  )r9   r@   r7   r7   r:   ri    s   



z)AgentExecutor._prepare_intermediate_stepsinputUnion[dict[str, Any], Any]r   Optional[RunnableConfig]Iterator[AddableDict]c                 k  sV    t |}t| ||df|d|d|d|ddd|}|E dH  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.
        rB   r=  metadatarun_namerun_idTr=  r  r  r  Zyield_actionsNr    r*   r1  )r9   r  r   rC   iteratorr7   r7   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.
        rB   r=  r  r  r  Tr  Nr  )r9   r  r   rC   r  stepr7   r7   r:   r     s$   	zAgentExecutor.astreamr>   )
r#  r"  r`   ra   rB   r   rC   r   r1   r!  r  )r0  ru   r1   r   )r1   r7  r   )
r   r   rB   r   r;  r   r<  r   r1   r*   r   )r  rR   r1   r"   )rD  rE  rF  rG  r1   r   )r6   r   r@   r   r  rI  r1   rJ  )r6   r   r@   r   r  rR  r1   rJ  )r0  rT  r1   rU  )rZ  r[  r\  r]  r   r]  r@   rA   r  rI  r1   rU  )rZ  r[  r\  r]  r   r]  r@   rA   r  rI  r1   ra  )
rZ  r[  r\  r]  ru  r   r  rI  r1   r   )rZ  r[  r\  r]  r   r]  r@   rA   r  rR  r1   rU  )rZ  r[  r\  r]  r   r]  r@   rA   r  rR  r1   r|  )
rZ  r[  r\  r]  ru  r   r  rR  r1   r   )r   r]  r  rI  r1   rJ  )r   r]  r  rR  r1   r]  )r  r  r1   r  )r@   rA   r1   rA   )r  r  r   r  rC   r   r1   r  )r  r  r   r  rC   r   r1   r  ))r   r   r   r   r   r$  r&  r'  rQ   r(  r*  r   r+  r&   r.  r6  r   r9  r   r:  r>  rP   r?  rC  rH  rQ  rS  rY  r`  r^  rp  r{  rz  r}  r  r  r  ri  r(   r   r   r7   r7   r7   r:   r!    s   
 





	
	
T-\.9
I
r!  )br   
__future__r   r  builtinsr   r   loggingr  abcr   collections.abcr   r   r   pathlibr   typingr   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'   r(   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.llmr.   Zlangchain.utilities.asyncior/   	getLoggerr   r  r0   r   r   r   r   r   r   r   r   r  rT  r8  r!  r7   r7   r7   r:   <module>   s     
 ) 
owS  '