
    9|h                    J   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j                  eR      ZS G d de>      ZT G d  d!e>      ZU G d" d#e,eeef            ZV G d$ d%e,eee   ef            ZW G d& d'eT      ZX G d( d)eU      ZY ed*eDd+,       G d- d.eT             ZZ ed*eDd+,       G d/ d0eT             Z[ G d1 d2e:      Z\eeeeef      Z]eeXeYf   Z^ G d3 d4eL      Z_y)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                      e Zd ZdZedd       ZddZe	 d	 	 	 	 	 	 	 dd       Ze	 d	 	 	 	 	 	 	 dd       Z	eedd              Z
	 	 	 	 	 	 	 	 ddZe	 d	 	 	 	 	 	 	 	 	 dd       Zedd	       Zd fd
ZddZddZ xZS )BaseSingleActionAgentzBase Single Action Agent class.c                    dgS Return values of the agent.output selfs    U/var/www/html/test/engine/venv/lib/python3.12/site-packages/langchain/agents/agent.pyreturn_valuesz#BaseSingleActionAgent.return_values@        z    c                     y Nr9   r:   s    r<   get_allowed_toolsz'BaseSingleActionAgent.get_allowed_toolsE   s    r?   c                     y)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;   intermediate_steps	callbackskwargss       r<   planzBaseSingleActionAgent.planH       r?   c                   K   yw)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   rE   s       r<   aplanzBaseSingleActionAgent.aplan[           c                     y7Return the input keys.

        :meta private:
        Nr9   r:   s    r<   
input_keysz BaseSingleActionAgent.input_keysn   rJ   r?   c                F    |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;   early_stopping_methodrF   rH   s       r<   return_stopped_responsez-BaseSingleActionAgent.return_stopped_responsev   sC    ( !G+PQSU  9:O9PPQR r?   c                    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)clsllmtoolscallback_managerrH   s        r<   from_llm_and_toolsz(BaseSingleActionAgent.from_llm_and_tools   s
    & "!r?   c                    t         z#Return Identifier of an agent type.ra   r:   s    r<   _agent_typez!BaseSingleActionAgent._agent_type   
     "!r?   c                    t         |          }	 | j                  }t	        |t
              rt        |j                        |d<   |S |||d<   |S # t        $ r d}Y @w xY w)z{Return dictionary representation of agent.

        Returns:
            Dict: Dictionary representation of agent.
        N_type)super
model_dumprj   rb   
isinstancer.   strvalue)r;   rH   _dictrm   	__class__s       r<   dictzBaseSingleActionAgent.dict   ss     "$	$$E eY' -E'N  "E'N # 	E	s   A AAc                   t        |t              rt        |      }n|}|j                  }|j	                  dd       | j                         }d|vrt        d|  d      |j                  dk(  r.t        |d      5 }t        j                  ||d	       d
d
d
       y
|j                  j                  d      r.t        |d      5 }t        j                  ||d       d
d
d
       y
t        | d      # 1 sw Y   y
xY w# 1 sw Y   y
xY w)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default_flow_style must be json or yaml)rp   rq   r   parentmkdirru   rb   suffixopenjsondumpendswithyamlr\   )r;   	file_path	save_pathdirectory_path
agent_dictfs         r<   savezBaseSingleActionAgent.save   s    i%YI!I"))TD9 YY[
*$%tf4L&MNNw&i% 3		*a23 3&&'89i% C		*aEBC C 	{*?@AA3 3C C   <C5D5C>D
c                    i S #Return logging kwargs for tool run.r9   r:   s    r<   tool_run_logging_kwargsz-BaseSingleActionAgent.tool_run_logging_kwargs   s    	r?   return	List[str]r   Optional[List[str]]rA   rF   List[Tuple[AgentAction, str]]rG   r   rH   r   r   Union[AgentAction, AgentFinish]r^   rq   rF   r   rH   r   r   r   )
rd   r   re   Sequence[BaseTool]rf   Optional[BaseCallbackManager]rH   r   r   r4   r   rq   rH   r   r   r	   r   zUnion[Path, str]r   Noner   r	   )__name__
__module____qualname____doc__propertyr=   rB   r   rI   rM   rS   r_   classmethodrg   rj   ru   r   r   __classcell__rt   s   @r<   r4   r4   =   sP   )    $9  	
 
) $   $9  	
 
) $   " : 	
 
< 
 ;?	"" "" 8	"
 " 
" "( " ""!BFr?   r4   c                       e Zd ZdZedd       ZddZe	 d	 	 	 	 	 	 	 dd       Ze	 d	 	 	 	 	 	 	 dd       Z	eedd              Z
	 	 	 	 	 	 	 	 ddZedd       Zd fd	Zdd
ZddZ xZS )BaseMultiActionAgentzBase Multi Action Agent class.c                    dgS r6   r9   r:   s    r<   r=   z"BaseMultiActionAgent.return_values   r>   r?   c                     y)z]Get allowed tools.

        Returns:
            Optional[List[str]]: Allowed tools.
        Nr9   r:   s    r<   rB   z&BaseMultiActionAgent.get_allowed_tools   s     r?   c                     y)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   rE   s       r<   rI   zBaseMultiActionAgent.plan   rJ   r?   c                   K   yw)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   rE   s       r<   rM   zBaseMultiActionAgent.aplan
  rN   rO   c                     yrQ   r9   r:   s    r<   rS   zBaseMultiActionAgent.input_keys  rJ   r?   c                F    |dk(  rt        ddid      S t        d| d      )rU   rV   r8   z$Agent stopped due to max iterations.rX   rY   rZ   r[   r]   s       r<   r_   z,BaseMultiActionAgent.return_stopped_response%  s<    ( !G+*PQSUVV9:O9PPQR r?   c                    t         ri   ra   r:   s    r<   rj   z BaseMultiActionAgent._agent_typeA  rk   r?   c                v    t         |          }	 t        | j                        |d<   |S # t        $ r Y |S w xY w)*Return dictionary representation of agent.rm   )rn   ro   rq   rj   rb   r;   rH   rs   rt   s      r<   ru   zBaseMultiActionAgent.dictF  sI    "$	 !1!12E'N  # 		s   + 	88c                   t        |t              rt        |      }n|}| j                         }d|vrt	        d|  d      |j
                  }|j                  dd       |j                  dk(  r.t        |d      5 }t        j                  ||d	       d
d
d
       y
|j                  j                  d      r.t        |d      5 }t        j                  ||d       d
d
d
       y
t        | d      # 1 sw Y   y
xY w# 1 sw Y   y
xY w)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   rz   z does not support saving.Trw   r{   r|   r}   r~   Nr   Fr   r   )rp   rq   r   ru   rb   r   r   r   r   r   r   r   r   r\   )r;   r   r   r   r   r   s         r<   r   zBaseMultiActionAgent.saveO  s   " i%YI!I YY[
*$%tf4M&NOO"))TD9w&i% 3		*a23 3&&'89i% C		*aEBC C 	{*?@AA3 3C Cr   c                    i S r   r9   r:   s    r<   r   z,BaseMultiActionAgent.tool_run_logging_kwargsv  s	     	r?   r   r   rA   rF   r   rG   r   rH   r   r   %Union[List[AgentAction], AgentFinish]r   r   r   r   r   )r   r   r   r   r   r=   rB   r   rI   rM   rS   r_   rj   ru   r   r   r   r   s   @r<   r   r      s   (    $9  	
 
/ $   $9  	
 
/ $   " : 	
 
8 " "%BNr?   r   c                  "    e Zd ZdZedd       Zy)AgentOutputParserz=Base class for parsing agent output into agent action/finish.c                     y)z$Parse text into agent action/finish.Nr9   r;   texts     r<   parsezAgentOutputParser.parse  rJ   r?   N)r   rq   r   r   r   r   r   r   r   r   r9   r?   r<   r   r   |  s    G3 3r?   r   c                  "    e Zd ZdZedd       Zy)MultiActionAgentOutputParserzBase class for parsing agent output into agent actions/finish.

    This is used for agents that can return multiple actions.
    c                     y)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   s     r<   r   z"MultiActionAgentOutputParser.parse  rJ   r?   N)r   rq   r   r   r   r9   r?   r<   r   r     s    
 	 	r?   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
      Z	e
dd       Ze
dd       Z	 d	 	 	 	 	 	 	 ddZ	 d	 	 	 	 	 	 	 ddZy)RunnableAgentAgent powered by Runnables.z/Runnable[dict, Union[AgentAction, AgentFinish]]runnabler   input_keys_argreturn_keys_argTboolstream_runnablearbitrary_types_allowedc                    | j                   S r7   r   r:   s    r<   r=   zRunnableAgent.return_values       ###r?   c                    | j                   S )zReturn the input keys.r   r:   s    r<   rS   zRunnableAgent.input_keys  s     """r?   Nc                    i |d|i}d}| j                   r0| j                  j                  |d|i      D ]  }||}||z  } |S | j                  j                  |d|i      }|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.
        rF   NrG   configr   r   streaminvoker;   rF   rG   rH   inputsfinal_outputchunks          r<   rI   zRunnableAgent.plan  s    " JFI35GHI  --fk9=U-V *'#(L E)L	*   ==//Y?W/XLr?   c                   K   i |d|i}d}| j                   r3| j                  j                  |d|i      2 3 d{   }||}||z  }| j                  j                  |d|i       d{   }|S 7 86 |S 7 w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.
        rF   NrG   r   r   r   astreamainvoker   s          r<   rM   zRunnableAgent.aplan  s     ( JFI35GHI   $}}44Y7  5   * *e  '#(L E)L!%!6!6Y7 "7 " L *   2   6A<A7A5A7 .A<.A:/A<5A77A<r   rA   r   r   r   r   r   __annotations__r   r   r   r)   model_configr   r=   rS   rI   rM   r9   r?   r<   r   r     s    %==/ "NI"!#OY# OT   $L $ $ # #  $"9" " 	"
 
)"N  $(9( ( 	(

(r?   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
      Z	e
dd       Ze
dd       Z	 d	 	 	 	 	 	 	 ddZ	 d	 	 	 	 	 	 	 ddZy)RunnableMultiActionAgentr   z5Runnable[dict, Union[List[AgentAction], AgentFinish]]r   r   r   r   Tr   r   r   c                    | j                   S r   r   r:   s    r<   r=   z&RunnableMultiActionAgent.return_values  r   r?   c                    | j                   S )QReturn the input keys.

        Returns:
            List of input keys.
        r   r:   s    r<   rS   z#RunnableMultiActionAgent.input_keys  s     """r?   Nc                    i |d|i}d}| j                   r0| j                  j                  |d|i      D ]  }||}||z  } |S | j                  j                  |d|i      }|S r   r   r   s          r<   rI   zRunnableMultiActionAgent.plan(  s    ( JFI35GHI  --fk9=U-V *'#(L E)L	*   ==//Y?W/XLr?   c                   K   i |d|i}d}| j                   r3| j                  j                  |d|i      2 3 d{   }||}||z  }| j                  j                  |d|i       d{   }|S 7 86 |S 7 wr   r   r   s          r<   rM   zRunnableMultiActionAgent.aplanO  s     ( JFI35GHI   $}}44Y7  5   * *e  '#(L E)L!%!6!6Y7 "7 " L *   	r   r   rA   r   r   r9   r?   r<   r   r     s    %CC0 "NI"!#OY# OT   $L $ $ # #  $%9% % 	%

%T  $)9) ) 	)

)r?   r   z0.1.0z1.0)messageremovalc                       e Zd ZU dZded<   	 ded<   	 ded<   	 edd       Zd fd	Z	 d	 	 	 	 	 	 	 dd
Z	 d	 	 	 	 	 	 	 ddZ	ddZ
 xZS )LLMSingleActionAgentz$Base class for single action agents.r1   	llm_chainr   output_parserr   stopc                Z    t        t        | j                  j                        dhz
        S )r   rF   listsetr   rS   r:   s    r<   rS   zLLMSingleActionAgent.input_keys  s'     C1126J5KKLLr?   c                *    t         |          }|d= |S r   r   rn   ru   r   s      r<   ru   zLLMSingleActionAgent.dict      /"r?   c                     | j                   j                  d|| j                  |d|}| j                  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.
        rF   r   rG   r9   )r   runr   r   r   r;   rF   rG   rH   r8   s        r<   rI   zLLMSingleActionAgent.plan  sO    " $## 
1
 	
 !!''//r?   c                   K    | j                   j                  d|| j                  |d| d{   }| j                  j	                  |      S 7 w)rL   r  Nr9   )r   arunr   r   r   r  s        r<   rM   zLLMSingleActionAgent.aplan  s]     " +t~~** 
1
 	
 
 !!''//
s   .AA Ac                ^    dt        | j                        dk(  rddS | j                  d   dS )r   rX   r   
llm_prefixobservation_prefix)lenr   r:   s    r<   r   z,LLMSingleActionAgent.tool_run_logging_kwargs  s8     (+DII!(;"
 	
AE1
 	
r?   r   r   rA   r   r   )r   r   r   r   r   r   rS   ru   rI   rM   r   r   r   s   @r<   r   r   {  s     /$$$)
O%M M  $090 0 	0
 
)08  $090 0 	0
 
)02
r?   r   c                      e Zd ZU dZded<   	 ded<   	 dZded<   	 d fd	Zdd
Zed d       Z	d!dZ
ed d       Z	 	 	 	 d"dZ	 d#	 	 	 	 	 	 	 d$dZ	 d#	 	 	 	 	 	 	 d$dZ	 	 	 	 	 	 d%dZed d       Z ed      d&d       Zeed'd              Zeed'd              Zeed(d              Zed)d       Zeed*d              Ze	 	 d+	 	 	 	 	 	 	 	 	 	 	 d,d       Z	 	 	 	 	 	 	 	 d-dZd.dZ x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.
    r1   r   r   r   Nr   allowed_toolsc                *    t         |          }|d= |S r   r  r   s      r<   ru   z
Agent.dict  r  r?   c                    | j                   S )zGet allowed tools.)r  r:   s    r<   rB   zAgent.get_allowed_tools  s    !!!r?   c                    dgS r6   r9   r:   s    r<   r=   zAgent.return_values  r>   r?   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   s     r<   	_fix_textzAgent._fix_text  s     CDDr?   c                v    d| j                   j                          d| j                   j                          gS )N
z
	)r  rstripr:   s    r<   _stopzAgent._stop  sB     ((//1234**11345
 	
r?   c                ~    d}|D ]5  \  }}||j                   z  }|d| j                   | d| j                   z  }7 |S )zJConstruct the scratchpad that lets the agent continue its thought process.rX   r  )logr  r  )r;   rF   thoughtsactionobservations        r<   _construct_scratchpadzAgent._construct_scratchpad  s[     #5 	WFK

"H"T445k]"T__DUVVH	W r?   c                     | j                   |fi |} | j                  j                  dd|i|}| j                  j	                  |      S )rD   rG   r9   )get_full_inputsr   predictr   r   )r;   rF   rG   rH   full_inputsfull_outputs         r<   rI   z
Agent.plan  sQ    " +d**+=HH,dnn,,PyPKP!!''44r?   c                   K    | j                   |fi |} | j                  j                  dd|i| d{   }| j                  j	                  |       d{   }|S 7 )7 w)rL   rG   Nr9   )r"  r   apredictr   aparse)r;   rF   rG   rH   r$  r%  agent_outputs          r<   rM   zAgent.aplan'  sj     " +d**+=HH3DNN33WiW;WW!//66{CC XCs!   5A%A!"A%A#A%#A%c                R    | j                  |      }|| 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;   rF   rH   r  
new_inputsr$  s         r<   r"  zAgent.get_full_inputs=  s8     --.@A*2DJJG
..:.r?   c                Z    t        t        | j                  j                        dhz
        S )rR   r,  r   r:   s    r<   rS   zAgent.input_keysO  s'     C1126H5IIJJr?   aftermodec                x   | j                   j                  }d|j                  vrt        j	                  d       |j                  j                  d       t        |t              r|xj                  dz  c_        | S t        |t              r|xj                  dz  c_
        | 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appendrp   r!   templater    r   r\   type)r;   r3  s     r<   validate_promptzAgent.validate_promptW  s     &&V%;%;;NN= ""))*<=&.1#99
 	 F$9:!77  !#>tF|n!MNNr?   c                     y)z&Prefix to append the observation with.Nr9   r:   s    r<   r  zAgent.observation_prefixt  rJ   r?   c                     y)z#Prefix to append the LLM call with.Nr9   r:   s    r<   r  zAgent.llm_prefixy  rJ   r?   c                     y)zCreate a prompt for this class.

        Args:
            tools: Tools to use.

        Returns:
            BasePromptTemplate: Prompt template.
        Nr9   rc   re   s     r<   create_promptzAgent.create_prompt~  rJ   r?   c                     y)zgValidate that appropriate tools are passed in.

        Args:
            tools: Tools to use.
        Nr9   r>  s     r<   _validate_toolszAgent._validate_tools  s     	r?   c                     y)z)Get default output parser for this class.Nr9   )rc   rH   s     r<   _get_default_output_parserz Agent._get_default_output_parser  rJ   r?   c                    | j                  |       t        || j                  |      |      }|D cg c]  }|j                   }}|xs | j	                         }	 | d|||	d|S c c}w )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.
        )rd   r3  rf   )r   r  r   r9   )rA  r1   r?  namerC  )
rc   rd   re   rf   r   rH   r   tool
tool_names_output_parsers
             r<   rg   zAgent.from_llm_and_tools  s    * 	E"$$U+-
	
 -22Ddii2
2&J#*H*H*J 
$(
 	
 	
 3s   A(c                   |dk(  rt        ddid      S |dk(  rd}|D ]5  \  }}||j                  z  }|d| j                   | d| j                   z  }7 |dz  }|| j                  d}i ||} | j
                  j                  d
i |}	| j                  j                  |	      }
t        |
t               r|
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   r8   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 r9   )r   r  r  r  r  r   r#  r   r   rp   r\   )r;   r^   rF   rH   r  r  r  r-  r$  r%  parsed_outputs              r<   r_   zAgent.return_stopped_response  s   ( !G+PQSU  #j0H'9 #FJJ&001+b@QR VH /7

KJ2V2z2K0$..00?;?K ..44[AM-5$$ #Hk#:KHH,-/ r?   c                4    | j                   | j                  dS )r   r
  r
  r:   s    r<   r   zAgent.tool_run_logging_kwargs  s     //"&"9"9
 	
r?   r   r   r   )r   rq   r   rq   )rF   r   r   zUnion[str, List[BaseMessage]]rA   r   )rF   r   rH   r   r   Dict[str, Any]r   r+   r   )re   r   r   r   )re   r   r   r   )rH   r   r   r   )NN)rd   r   re   r   rf   r   r   zOptional[AgentOutputParser]rH   r   r   r  r   r   )r   r   r   r   r   r  ru   rB   r   r=   r  r  r   rI   rM   r"  rS   r*   r:  r   r  r  r   r?  rA  rC  rg   r_   r   r   r   s   @r<   r  r    s/    $$$))-M&-F"  	E 
 
"?	&  $595 5 	5
 
)50  $9  	
 
),"?KN	$ K K '" #8 5  5 2  2      8  8 
 ;?59!
!
 "!
 8	!

 3!
 !
 
!
 !
F5"5 :5 	5
 
5n
r?   r  c                  ^    e Zd ZU dZdZded<   	 dZded<   	 	 d
	 	 	 	 	 ddZ	 d
	 	 	 	 	 dd	Zy)ExceptionToolz!Tool that just returns the query.
_Exceptionrq   rE  zException tooldescriptionNc                    |S rA   r9   r;   queryrun_managers      r<   _runzExceptionTool._run  s	    
 r?   c                   K   |S wrA   r9   rT  s      r<   _arunzExceptionTool._arun  s     
 s   rA   )rU  rq   rV  z#Optional[CallbackManagerForToolRun]r   rq   )rU  rq   rV  z(Optional[AsyncCallbackManagerForToolRun]r   rq   )	r   r   r   r   rE  r   rR  rW  rY  r9   r?   r<   rP  rP    sn    +D#'K'"
 <@ 9 
	 AE > 
	r?   rP  c                      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	 d5	 	 	 	 	 	 	 	 	 d6d       Z ed      d7d       Z ed      ed8d              Zed9d       Zd:dZd:dZ	 d5ddd 	 	 	 	 	 	 	 	 	 d;d!Zed<d"       Zed<d#       Zd=d$Zd>d%Z	 d5	 	 	 	 	 	 	 d?d&Z	 d5	 	 	 	 	 	 	 d@d'Z	 	 	 	 dAd(Z	 d5	 	 	 	 	 	 	 	 	 	 	 dBd)Z	 d5	 	 	 	 	 	 	 	 	 	 	 dCd*Z	 d5	 	 	 	 	 	 	 	 	 dDd+Z	 d5	 	 	 	 	 	 	 	 	 	 	 dEd,Z	 d5	 	 	 	 	 	 	 	 	 	 	 dFd-Z 	 d5	 	 	 	 	 	 	 	 	 dGd.Z!	 d5	 	 	 	 	 dHd/Z"	 d5	 	 	 	 	 dId0Z#	 	 	 	 dJd1Z$	 	 	 	 dKd2Z%	 d5	 	 	 	 	 	 	 dLd3Z&	 d5	 	 	 	 	 	 	 dMd4Z'y)NAgentExecutorzAgent that is using tools.<Union[BaseSingleActionAgent, BaseMultiActionAgent, Runnable]agentr   re   Fr   return_intermediate_steps   zOptional[int]max_iterationsNzOptional[float]max_execution_timerV   rq   r^   z8Union[bool, str, Callable[[OutputParserException], str]]handle_parsing_errorszTUnion[int, Callable[[List[Tuple[AgentAction, str]]], List[Tuple[AgentAction, str]]]]trim_intermediate_stepsc                     | 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]  re   rG   r9   r9   )rc   r]  re   rG   rH   s        r<   from_agent_and_toolsz"AgentExecutor.from_agent_and_toolsG  s)    &  

 	
 	
r?   r/  r0  c           	         | j                   }| j                  }|j                         }|Yt        |      t        |D cg c]  }|j                   c}      k7  r*t        d| d|D cg c]  }|j                   c} d      | S c c}w c c}w )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.
        zAllowed tools (z!) different than provided tools ())r]  re   rB   r   rE  r\   )r;   r]  re   r  rF  s        r<   validate_toolszAgentExecutor.validate_toolsa  s     



//1$=!S)F$)))F%GG %m_ 5'>C'Dd		'D&EQH   *G (Es   B
'Bbeforec                <   |j                  d      }|rpt        |t              r`	 |j                  }|t        t
        t           t        f   k(  }|j                  dd      }|rt        ||      |d<   |S t        ||      |d<   |S # t        $ r}d}Y d}~Hd}~ww xY w)zConvert runnable to agent if passed in.

        Args:
            values: Values to validate.

        Returns:
            Dict: Validated values.
        r]  FNr   T)r   r   )getrp   r"   
OutputTyper   r   r   r   	Exceptionpopr   r   )rc   valuesr]  output_typemulti_action_r   s          r<   validate_runnable_agentz%AgentExecutor.validate_runnable_agenty  s     

7#Zx0T#..  +eD4E{4R.SS$jj):DAO":"O#w  #0"O#w   %$%s   B 	BBBc                    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:   s    r<   _action_agentzAgentExecutor._action_agent  s.     djj(+)4::66::r?   c                    t        d      )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;   r   s     r<   r   zAgentExecutor.save  s     !
 	
r?   c                8    | j                   j                  |      S )zZSave the underlying agent.

        Args:
            file_path: Path to save to.
        )rw  r   ry  s     r<   
save_agentzAgentExecutor.save_agent  s     !!&&y11r?   )include_run_infoasync_c               6    t        | ||| j                  |      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  )r;   r   rG   r|  r}  s        r<   iterzAgentExecutor.iter  s$    & %-
 	
r?   c                .    | j                   j                  S )rR   )rw  rS   r:   s    r<   rS   zAgentExecutor.input_keys  s     !!,,,r?   c                z    | j                   r| j                  j                  dgz   S | j                  j                  S )z@Return the singular output key.

        :meta private:
        rF   )r^  rw  r=   r:   s    r<   output_keyszAgentExecutor.output_keys  s:     ))%%337K6LLL%%333r?   c                \    | j                   D ci c]  }|j                  | c}|   S c c}w )zLookup tool by name.

        Args:
            name: Name of tool.

        Returns:
            BaseTool: Tool object.
        )re   rE  )r;   rE  rF  s      r<   lookup_toolzAgentExecutor.lookup_tool  s)     -1JJ7D		47==7s   )c                t    | j                   || j                   k\  ry| j                  || j                  k\  ryy)NFT)r`  ra  )r;   
iterationstime_elapseds      r<   _should_continuezAgentExecutor._should_continue  s>    *zT=P=P/P##/ 7 77r?   c                    |r|j                  |d| j                         |j                  }| j                  r||d<   |S Ngreen)colorverboserF   on_agent_finishr  r=   r^  r;   r8   rF   rV  r   s        r<   _returnzAgentExecutor._return  sE     ''gt||'T++))1CL-.r?   c                   K   |r&|j                  |d| j                         d {    |j                  }| j                  r||d<   |S 7 #wr  r  r  s        r<   _areturnzAgentExecutor._areturn  s_      --gt|| .    ++))1CL-.s   $AA
$Ac                    t        |d   t              rt        |      dk(  sJ |d   S |D cg c]+  }t        |t              s|j                  |j
                  f- c}S c c}w )Nrc     )rp   r   r  r   r  r  )r;   rp  as      r<   _consume_next_stepz AgentExecutor._consume_next_step  sc     fRj+.v;!###": 4:./Z9=U1==)  s   A A c           	     p    | j                  | j                  |||||      D cg c]  }| c}      S c c}w rA   )r  _iter_next_stepr;   name_to_tool_mapcolor_mappingr   rF   rV  r  s          r<   _take_next_stepzAgentExecutor._take_next_step)  sN     && --$!&	 	
 	
	s   	3c              #  |  K   	 | j                  |      } | j                  j                  |fd|r|j                         ndi|}t        |t,              r| yt        |t              r|g}n|}|D ]  }|  |D ]  }| j/                  ||||        y# t        $ r}t        | j                  t              r| j                   }nd}|rt        dt        |             t        |      }	t        | j                  t              r:|j                  r+t        |j                        }
t        |j                        }	n\d}
nYt        | j                  t              r| j                  }
n2t        | j                        r| j                  |      }
nt        d      t        d|
|	      }|r|j                  |d	       | j                  j!                         } t#               j$                  |j&                  f| j(                  d|r|j                         ndd
|}
t+        ||
       Y d}~yd}~ww xY ww)Take a single step in the thought-action-observation loop.

        Override this to take control of how the agent makes and acts on choices.
        rG   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`rQ  r  r  r  r  rG   r  r  )_prepare_intermediate_stepsrw  rI   	get_childr   rp   rb  r   r\   rq   send_to_llmr  
llm_outputcallabler   on_agent_actionr   rP  r  
tool_inputr  r   r   _perform_agent_action)r;   r  r  r   rF   rV  r8   eraise_errorr   r  tool_run_kwargsactionsagent_actions                 r<   r  zAgentExecutor._iter_next_step>  s9    .	!%!A!ABT!U -T'',,"5@+//1d FZ fk*L fk*hGG# 	L	# 	L,, -{ 	g % %	$44d;"&"<"<<# * +.a&3  q6D$44d;=="%amm"4Kq||,D"BKD66<"88$445"88; !QRR {DAF++F'+B"00HHJO--/--!!5@+//1d	
 "K 6{CCK%	s1   H<AB AH<
H9$FH4/H<4H99H<c                f   |r|j                  |d       |j                  |v r||j                     }|j                  }||j                     }| j                  j	                         }|rd|d<    |j
                  |j                  f| j                  ||r|j                         nd d|}	ny| j                  j	                         } t               j
                  |j                  t        |j                               df| j                  d |r|j                         nd d|}	t        ||	      S )Nr  r  rX   r  r  requested_tool_nameavailable_tool_namesr  )r  rF  return_directrw  r   r  r  r  r  r/   r   keysr   
r;   r  r  r  rV  rF  r  r  r  r  s
             r<   r  z#AgentExecutor._perform_agent_action  s;    ''G'D 00#L$5$56D ..M!,"3"34E"00HHJO02-"$((''5@+//1d	
 "K #00HHJO++-+++7+<+<,01A1F1F1H,I	
 5@+//1d	 "	K +FFr?   c           	        K   | j                  | j                  |||||      2 cg c3 d {   }|7 6 c}      S c c}w wrA   )r  _aiter_next_stepr  s          r<   _atake_next_stepzAgentExecutor._atake_next_step  s]      &&  $44$!& 	 	 	 	
 	
	s&   #A=5
35
=5
=Ac                 K   	 | j                  |      } | j                  j                  |fd|r|j                         ndi| d{   }t        |t*              r| yt        |t              r|g}n|}|D ]  }| 	 t-        j.                  |D cg c]  }| j1                  ||||       c}  d{   }|D ]  }| 	 y7 # t        $ r}t        | j                  t              r| j                   }nd}|rt        dt        |             t        |      }	t        | j                  t              r:|j                  r+t        |j                        }
t        |j                        }	n\d}
nYt        | j                  t              r| j                  }
n2t        | j                        r| j                  |      }
nt        d      t        d|
|	      }| j                  j                         } t!               j"                  |j$                  f| j&                  d|r|j                         ndd| d{  7  }
t)        ||
	       Y d}~yd}~ww xY wc c}w 7 w)
r  rG   NFr  r  r  rQ  r  r  )r  rw  rM   r  r   rp   rb  r   r\   rq   r  r  r  r  r   r   rP  r  r  r  r   r   asynciogather_aperform_agent_action)r;   r  r  r   rF   rV  r8   r  r  r   r  r  r  r  resultr   s                   r<   r  zAgentExecutor._aiter_next_step  sp    ,	!%!A!ABT!U 44--33"5@+//1d  FV fk*L fk*hGG# 	L	 ~~
 %,	 ! ++$m\;
 
  	EK	E
 % #	$44d;"&"<"<<# * +.a&3  q6D$44d;=="%amm"4Kq||,D"BKD66<"88$445"88; !QRR {DAF"00HHJO 4 4 4!!!5@+//1d	!
 "!  K 6{CCG#	h
sg   I.AC 	C
C AI.I&4I.;I+<I.C 
I#E*IIII.I##	I.c                  K   |r&|j                  || j                  d       d {    |j                  |v r||j                     }|j                  }||j                     }| j                  j                         }|rd|d<    |j                  |j                  f| j                  ||r|j                         nd d| d {   }	n| j                  j                         } t               j                  |j                  t        |j                               df| j                  d |r|j                         nd d| d {   }	t        ||	      S 7 27 7 w)Nr  )r  r  rX   r  r  r  r  )r  r  rF  r  rw  r   r  r  r  r/   r   r  r   r  s
             r<   r  z$AgentExecutor._aperform_agent_action  sq     --dll' .     00#L$5$56D ..M!,"3"34E"00HHJO02- )		''!5@+//1d	!
 "! K #00HHJO 2 2 2+7+<+<,01A1F1F1H,I	!
 5@+//1d	! "	! 	K +FF?	s5   $EEBEEBEEEEEc                   | j                   D ci c]  }|j                  | }}t        | j                   D cg c]  }|j                   c}ddg      }g }d}d}t        j                         }	| j	                  ||      r| j                  |||||      }
t        |
t              r| j                  |
||      S |j                  |
       t        |
      dk(  r,|
d   }| j                  |      }|| j                  |||      S |dz  }t        j                         |	z
  }| j	                  ||      r | j                  j                  | j                  |fi |}| j                  |||      S c c}w c c}w )z(Run text through and get agent response.r  redexcluded_colorsr           rV  r  )re   rE  r'   timer  r  rp   r   r  extendr  _get_tool_returnrw  r_   r^   r;   r   rV  rF  r  r  rF   r  r  
start_timenext_step_outputnext_step_actiontool_returnr8   s                 r<   _callzAgentExecutor._callE  s    9=

CDIItOCC)#'::.4TYY.%@P
 =?
YY[
##J=#33 "'  4   *K8||$&8k $   %%&67#$)#3A#6 "334DE*<<#%7[ (   !OJ99;3L/ ##J=0 <##;;&&(:
>D
 ||F$6K|PPM D /s
   E2E7c                  K   | j                   D ci c]  }|j                  | }}t        | j                   D cg c]  }|j                   c}dg      }g }d}d}t        j                         }		 t	        | j
                        4 d{    | j                  ||      r| j                  |||||       d{   }
t        |
t              r-| j                  |
||       d{   cddd      d{    S |j                  |
       t        |
      dk(  rE|
d   }| j                  |      }|-| j                  |||       d{   cddd      d{    S |dz  }t        j                         |	z
  }| j                  ||      r | j                  j                  | j                   |fi |}| j                  |||       d{   cddd      d{    S c c}w c c}w 7 d7 77 7 7 7 7 /7 !# 1 d{  7  sw Y   yxY w# t"        t$        j"                  f$ rH  | j                  j                  | j                   |fi |}| j                  |||       d{  7  cY S w xY ww)z.Async run text through and get agent response.r  r  r   r  Nr  r  )re   rE  r'   r  r2   ra  r  r  rp   r   r  r  r  r  rw  r_   r^   TimeoutErrorr  r  s                 r<   _acallzAgentExecutor._acallt  s     9=

CDIItOCC)#'::.4TYY.	
 =?
YY[
*	&t'>'>? ! !++JE-1-B-B(%*$/ .C . ($ ""2K@%)]],.(3 &3 &  ! ! !  '--.>?+,1+;A+>(&*&;&;<L&M&2)- +-?[ *7 * $-! ! !4 !OJ#'99;#;L5 ++JE6 D++CC..0BFL "]].K +  ?! ! ! D /!( !,$-!>?! ! ! !D g223 	?T''??**,>BHF * '    	s6  I<G%I<G*$I<2H G/H ,H;G2<+H'G5(H+H 7G88H <I<=AHG;HH G=H  I<!.H?HG?HH H H $I</H 2H5H8H ;H=H ?HH H	H
HH I<H AI90I31I96I<8I99I<c                D   |\  }}| j                   D ci c]  }|j                  | }}d}t        | j                  j                        dkD  r| j                  j                  d   }|j
                  |v r'||j
                     j                  rt        ||id      S yc c}w )z&Check if the tool is a returning tool.r8   r   rX   N)re   rE  r  rw  r=   rF  r  r   )r;   r  r  r  rF  r  return_value_keys          r<   r  zAgentExecutor._get_tool_return  s     %5!k8<

CDIItOCC#t!!//014#11??B 00 1 12@@"%{3   Ds   Bc                    t        | j                  t              r| j                  dkD  r|| j                   d  S t        | j                        r| j                  |      S |S )Nr   )rp   rd  intr  )r;   rF   s     r<   r  z)AgentExecutor._prepare_intermediate_steps  s_     t33S9,,q0%t'C'C&C&EFFd223//0BCC%%r?   c           	   +     K   t        |      }t        | ||j                  d      f|j                  d      |j                  d      |j                  d      |j                  d      dd|}|D ]  }|  yw)	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.
        rG   r  metadatarun_namerun_idTr  r  r  r  yield_actionsNr$   r-   rl  r;   inputr   rH   iteratorsteps         r<   r   zAgentExecutor.stream  s       v&(JJ{#

 F#ZZ
+ZZ
+::h'

 

  	DJ	s   A7A9c           	      K   t        |      }t        | ||j                  d      f|j                  d      |j                  d      |j                  d      |j                  d      dd|}|2 3 d{   }| 7 
6 yw)	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.
        rG   r  r  r  r  Tr  Nr  r  s         r<   r   zAgentExecutor.astream  s     " v&(JJ{#

 F#ZZ
+ZZ
+::h'

 

 # 	 	$J	(s*   A-B/B 3A>4B 7B>B  BrA   )
r]  r\  re   r   rG   r   rH   r   r   r[  rN  )rp  r	   r   r   )r   z2Union[BaseSingleActionAgent, BaseMultiActionAgent]r   )
r   r   rG   r   r|  r   r}  r   r   r-   r   )rE  rq   r   r&   )r  r  r  floatr   r   )r8   r   rF   r   rV  $Optional[CallbackManagerForChainRun]r   rM  )r8   r   rF   r   rV  )Optional[AsyncCallbackManagerForChainRun]r   rM  )rp  NextStepOutputr   1Union[AgentFinish, List[Tuple[AgentAction, str]]])r  Dict[str, BaseTool]r  Dict[str, str]r   r  rF   r   rV  r  r   r  )r  r  r  r  r   r  rF   r   rV  r  r   z4Iterator[Union[AgentFinish, AgentAction, AgentStep]])
r  r  r  r  r  r   rV  r  r   r   )r  r  r  r  r   r  rF   r   rV  r  r   r  )r  r  r  r  r   r  rF   r   rV  r  r   z9AsyncIterator[Union[AgentFinish, AgentAction, AgentStep]])
r  r  r  r  r  r   rV  r  r   r   )r   r  rV  r  r   rM  )r   r  rV  r  r   r  )r  zTuple[AgentAction, str]r   zOptional[AgentFinish])rF   r   r   r   )r  Union[Dict[str, Any], Any]r   Optional[RunnableConfig]rH   r   r   zIterator[AddableDict])r  r  r   r  rH   r   r   zAsyncIterator[AddableDict])(r   r   r   r   r   r^  r`  ra  r^   rb  rd  r   rf  r*   ri  rt  r   rw  r   r{  r  rS   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r   r9   r?   r<   r[  r[    s   $GG3-&+t+3$&NM&9 +/. ")3( 	 S  	    
  $	
K
 "
 	

 
 

 
2 '" #. (#  $:  
2  $

 "'

 

 
 
 

6 - - 4 4	>	 =A	 ! :	
 
" BF	 ! ?	
 
	$		:	" =A
-
 &
 	

 :
 :
 
;
6 =AK-K &K 	K
 :K :K 
>Kd =A%G-%G &%G "	%G
 :%G 
%GZ BF
-
 &
 	

 :
 ?
 
;
6 BFS-S &S 	S
 :S ?S 
CSt BF'G-'G &'G "	'G
 ?'G 
'GX =A-Q-Q :-Q 
	-Qd BF<< ?< 
	<| 7	$&"?&	&&  ,0) ) 	
 
D ,0) ) 	
 
$r?   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._api.deprecationr,   langchain.agents.agent_iteratorr-   langchain.agents.agent_typesr.   langchain.agents.toolsr/   langchain.chains.baser0   langchain.chains.llmr1   langchain.utilities.asyncior2   	getLoggerr   r5  r4   r   r   r   r   r   r   r  rP  r  rv  r[  r9   r?   r<   <module>r     s   K "           * E E  < < / : 5 A 8 L L 6 ) 8 ; ; " @ A 2 . ' ) 7			8	$gI gTR9 Rj3({K/G)HI 3U4,k9:;*j) jZr3 rj %
P
0 P

P
f %
a
! a

a
H	H . eKi?@A-)AAB wE wr?   