
    3fi                    F   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mZ ddlmZ ddl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-m.Z. ddl/m0Z0 ddl1m2Z2m3Z3m4Z4 ddl5m6Z6 ddl7m8Z8 ddl9m:Z: ddl;m<Z<m=Z=m>Z> ddl?m@Z@mAZA ddlBmCZC ddlDmEZE ddlFmGZG ddlHmIZI ddlJmKZK ddlLmMZM ddlNmOZO  ej                  eQ      ZR G d d e<      ZS G d! d"e<      ZT G d# d$e*eez           ZU G d% d&e*eVe   ez           ZW G d' d(eS      ZX G d) d*eT      ZY ed+eCd,-       G d. d/eS             ZZ ed+eCd,-       G d0 d1eS             Z[ G d2 d3e8      Z\eVeez  ez     Z]eXeYz  Z^ G d4 d5eK      Z_y)6zEChain that takes in an input and produces an action and action input.    )annotationsN)abstractmethod)AsyncIteratorCallableIteratorSequence)Path)Any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                      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e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    \/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langchain_classic/agents/agent.pyreturn_valuesz#BaseSingleActionAgent.return_values:        z    c                     y)Get allowed tools.Nr5   r6   s    r8   get_allowed_toolsz'BaseSingleActionAgent.get_allowed_tools?   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.
        Nr5   r7   intermediate_steps	callbackskwargss       r8   planzBaseSingleActionAgent.planC       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.
        Nr5   rA   s       r8   aplanzBaseSingleActionAgent.aplanV           c                     yReturn the input keys.Nr5   r6   s    r8   
input_keysz BaseSingleActionAgent.input_keysi   rF   r;   c                J    |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.

        Returns:
            Agent finish object.

        Raises:
            ValueError: If `early_stopping_method` is not supported.
        forcer4   3Agent stopped due to iteration limit or time limit. 'Got unsupported early_stopping_method ``r   
ValueErrorr7   early_stopping_methodrB   _msgs        r8   return_stopped_responsez-BaseSingleActionAgent.return_stopped_responsen   sA    & !G+PQ  88M7NaPo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:
            Agent object.
        NotImplementedError)clsllmtoolscallback_managerrD   s        r8   from_llm_and_toolsz(BaseSingleActionAgent.from_llm_and_tools   s
    & "!r;   c                    t         z#Return Identifier of an agent type.r_   r6   s    r8   _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)zuReturn dictionary representation of agent.

        Returns:
            Dictionary representation of agent.
        N_type)super
model_dumprh   r`   
isinstancer*   strvalue)r7   rD   _dictrk   	__class__s       r8   dictzBaseSingleActionAgent.dict   ss     "$	$$E eY' -E'N  "E'N # 	E	s   A AAc                4   t        |t              rt        |      n|}|j                  }|j	                  dd       | j                         }d|vrd|  d}t        |      |j                  dk(  r3|j                  d      5 }t        j                  ||d	       d
d
d
       y
|j                  j                  d      r3|j                  d      5 }t        j                  ||d       d
d
d
       y
| d}t        |      # 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:
        ```python
        # If working with agent executor
        agent.agent.save(file_path="path/agent.yaml")
        ```
        Tparentsexist_okrk   Agent z does not support saving.jsonw   indentNz.yamlz.ymlFdefault_flow_style must be json or yaml)rn   ro   r	   parentmkdirrs   r`   suffixopenjsondumpendswithyamlrX   )r7   	file_path	save_pathdirectory_path
agent_dictr\   fs          r8   savezBaseSingleActionAgent.save   s    (2)S'ADOy	"))TD9 YY[
*$4& 89C%c**w&$ 3		*a23 3&&'89$ C		*aEBC C K45CS/!3 3C C   DDDDc                    i S #Return logging kwargs for tool run.r5   r6   s    r8   tool_run_logging_kwargsz-BaseSingleActionAgent.tool_run_logging_kwargs       	r;   return	list[str]r   list[str] | NoneNrB   list[tuple[AgentAction, str]]rC   r   rD   r
   r   AgentAction | AgentFinishrZ   ro   rB   r   r[   r
   r   r   )
rb   r   rc   Sequence[BaseTool]rd   BaseCallbackManager | NonerD   r
   r   r0   r   ro   rD   r
   r   builtins.dictr   z
Path | strr   Noner   r   )__name__
__module____qualname____doc__propertyr9   r>   r   rE   rI   rO   r]   classmethodre   rh   r'   rs   r   r   __classcell__rr   s   @r8   r0   r0   7   s^   )    $9  	
 
# $   $9  	
 
# $ %  %" : 	
 
8 
 8<	"" "" 5	"
 " 
" "( " "  " "Dr;   r0   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ed fd	       Zdd
ZddZ xZS )BaseMultiActionAgentzBase Multi Action Agent class.c                    dgS r2   r5   r6   s    r8   r9   z"BaseMultiActionAgent.return_values   r:   r;   c                     y)zHGet allowed tools.

        Returns:
            Allowed tools.
        Nr5   r6   s    r8   r>   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.
        Nr5   rA   s       r8   rE   zBaseMultiActionAgent.plan   rF   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.
        Nr5   rA   s       r8   rI   zBaseMultiActionAgent.aplan   rJ   rK   c                     yrM   r5   r6   s    r8   rO   zBaseMultiActionAgent.input_keys  rF   r;   c                J    |dk(  rt        ddid      S d| d}t        |      )rQ   rR   r4   z$Agent stopped due to max iterations.rT   rU   rV   rW   rY   s        r8   r]   z,BaseMultiActionAgent.return_stopped_response  s:    & !G+*PQSUVV78M7NaPor;   c                    t         rg   r_   r6   s    r8   rh   z BaseMultiActionAgent._agent_type1  ri   r;   c                    t         |          }t        j                  t              5  t        | j                        |d<   ddd       |S # 1 sw Y   |S xY w)*Return dictionary representation of agent.rk   N)rl   rm   
contextlibsuppressr`   ro   rh   r7   rD   rq   rr   s      r8   rs   zBaseMultiActionAgent.dict6  sO     "$  !45 	3 !1!12E'N	3	3s   AAc                4   t        |t              rt        |      n|}| j                         }d|vrd|  d}t	        |      |j
                  }|j                  dd       |j                  dk(  r3|j                  d      5 }t        j                  ||d	       d
d
d
       y
|j                  j                  d      r3|j                  d      5 }t        j                  ||d       d
d
d
       y
| d}t        |      # 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:
        ```python
        # If working with agent executor
        agent.agent.save(file_path="path/agent.yaml")
        ```
        rk   rx   z does not support saving.Tru   ry   rz   r{   r|   Nr~   Fr   r   )rn   ro   r	   rs   r`   r   r   r   r   r   r   r   r   rX   )r7   r   r   r   r\   r   r   s          r8   r   zBaseMultiActionAgent.save>  s   " (2)S'ADOy	 YY[
*$4& 9:C%c**"))TD9w&$ 3		*a23 3&&'89$ C		*aEBC C K45CS/!3 3C Cr   c                    i S r   r5   r6   s    r8   r   z,BaseMultiActionAgent.tool_run_logging_kwargsd  r   r;   r   r   r   rB   r   rC   r   rD   r
   r   list[AgentAction] | AgentFinishr   r   r   r   r   )r   r   r   r   r   r9   r>   r   rE   rI   rO   r]   rh   r'   rs   r   r   r   r   s   @r8   r   r      s   (    $9  	
 
) $   $9  	
 
) $ %  %" : 	
 
2 " "  $"L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.Nr5   r7   texts     r8   parsezAgentOutputParser.parsel  rF   r;   N)r   ro   r   r   r   r   r   r   r   r   r5   r;   r8   r   r   i  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:
            List of agent actions or agent finish.
        Nr5   r   s     r8   r   z"MultiActionAgentOutputParser.parsey  rF   r;   N)r   ro   r   r   r   r5   r;   r8   r   r   q  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, AgentAction | AgentFinish]runnabler   input_keys_argreturn_keys_argTboolstream_runnablearbitrary_types_allowedc                    | j                   S r3   r   r6   s    r8   r9   zRunnableAgent.return_values       ###r;   c                    | j                   S rN   r   r6   s    r8   rO   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.
        rB   NrC   configr   r   streaminvoker7   rB   rC   rD   inputsfinal_outputchunks          r8   rE   zRunnableAgent.plan      " FFE02DE  --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.
        rB   NrC   r   r   r   astreamainvoker   s          r8   rI   zRunnableAgent.aplan  s     " FFE02DE   $}}44#Y/  5   * *e  '#(L E)L!%!6!6#Y/ "7 " L *   	2   6A<A7A5A7 .A<.A:/A<5A77A<r   r   r   r   r   r   r   __annotations__r   r   r   r$   model_configr   r9   rO   rE   rI   r5   r;   r8   r   r     s    %77/ "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   z/Runnable[dict, list[AgentAction] | AgentFinish]r   r   r   r   Tr   r   r   c                    | j                   S r   r   r6   s    r8   r9   z&RunnableMultiActionAgent.return_values  r   r;   c                    | j                   S )QReturn the input keys.

        Returns:
            List of input keys.
        r   r6   s    r8   rO   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          r8   rE   zRunnableMultiActionAgent.plan  r   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          r8   rI   zRunnableMultiActionAgent.aplan7  s     " FFE02DE   $}}44#Y/  5   * *e  '#(L E)L!%!6!6#Y/ "7 " L
 *   r   r   r   r   r   r5   r;   r8   r   r     s    %==0 "NI"!#OY# OT   $L $ $ # #  $"9" " 	"
 
)"N  $(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e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.r-   	llm_chainr   output_parserr   stopc                Z    t        t        | j                  j                        dhz
        S )r   rB   listsetr   rO   r6   s    r8   rO   zLLMSingleActionAgent.input_keysq  s'     C1126J5KKLLr;   c                *    t         |          }|d= |S r   r   rl   rs   r   s      r8   rs   zLLMSingleActionAgent.dictz       /"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.
        rB   r   rC   r5   )r   runr   r   r   r7   rB   rC   rD   r4   s        r8   rE   zLLMSingleActionAgent.plan  sO    " $## 
1
 	
 !!''//r;   c                   K    | j                   j                  d|| j                  |d| d{   }| j                  j	                  |      S 7 w)rH   r	  Nr5   )r   arunr   r   r   r  s        r8   rI   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   rT   r   
llm_prefixobservation_prefix)lenr   r6   s    r8   r   z,LLMSingleActionAgent.tool_run_logging_kwargs  s8     (+DII!(;"
 	
AE1
 	
r;   r   r   r   r   r   )r   r   r   r   r   r   rO   r'   rs   rE   rI   r   r   r   s   @r8   r   r   b  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<   	 ed fd	       Zdd
Ze	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.
    r-   r   r   r   Nr   allowed_toolsc                *    t         |          }|d= |S r  r  r   s      r8   rs   z
Agent.dict  r  r;   c                    | j                   S )r=   )r  r6   s    r8   r>   zAgent.get_allowed_tools  s    !!!r;   c                    dgS r2   r5   r6   s    r8   r9   zAgent.return_values  r:   r;   c                v    d| j                   j                          d| j                   j                          gS )N
z
	)r  rstripr6   s    r8   _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.rT   r  )logr  r  )r7   rB   thoughtsactionobservations        r8   _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 )r@   rC   r5   )get_full_inputsr   predictr   r   r7   rB   rC   rD   full_inputsfull_outputs         r8   rE   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)rH   rC   Nr5   )r$  r   apredictr   aparser&  s         r8   rI   zAgent.aplan  se     " +d**+=HH3DNN33WiW;WW''..{;;; X;s!   5A#A"A#A!A#!A#c                N    | j                  |      }|| j                  d}i ||S )a!  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:
            Full inputs for the LLMChain.
        agent_scratchpadr   )r"  r  )r7   rB   rD   r  
new_inputss        r8   r$  zAgent.get_full_inputs  s3     --.@A*2DJJG
'&'J''r;   c                Z    t        t        | j                  j                        dhz
        S )rN   r.  r  r6   s    r8   rO   zAgent.input_keys.  s'     C1126H5IIJJr;   aftermodec                |   | 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 dt        |       }t        |      | S )aC  Validate that prompt matches format.

        Args:
            values: Values to validate.

        Returns:
            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appendrn   r   templater   r   typerX   )r7   r5  r\   s      r8   validate_promptzAgent.validate_prompt3  s     &&V%;%;;NN= ""))*<=&.1#99  F$9:!77  4DL>B o%r;   c                     y)z&Prefix to append the observation with.Nr5   r6   s    r8   r  zAgent.observation_prefixQ  rF   r;   c                     y)z#Prefix to append the LLM call with.Nr5   r6   s    r8   r  zAgent.llm_prefixV  rF   r;   c                     y)zCreate a prompt for this class.

        Args:
            tools: Tools to use.

        Returns:
            Prompt template.
        Nr5   ra   rc   s     r8   create_promptzAgent.create_prompt[  rF   r;   c                     y)zgValidate that appropriate tools are passed in.

        Args:
            tools: Tools to use.
        Nr5   r@  s     r8   _validate_toolszAgent._validate_toolsg  rF   r;   c                     y)z)Get default output parser for this class.Nr5   )ra   rD   s     r8   _get_default_output_parserz Agent._get_default_output_parsero  rF   r;   c                    | j                  |       t        || j                  |      |      }|D cg c]  }|j                   }}|xs | j	                         }	 | d|||	d|S c c}w )aH  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 object.
        )rb   r5  rd   )r   r  r   r5   )rC  r-   rA  namerE  )
ra   rb   rc   rd   r   rD   r   tool
tool_names_output_parsers
             r8   re   zAgent.from_llm_and_toolst  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 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:
            Agent finish object.

        Raises:
            ValueError: If `early_stopping_method` is not in ['force', 'generate'].
        rR   r4   rS   rT   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 r5   )r   r  r  r  r  r   r%  r   r   rn   rX   )r7   rZ   rB   rD   r  r   r!  r/  r'  r(  parsed_outputr\   s               r8   r]   zAgent.return_stopped_response  s"   ( !G+PQ  !J.H'9 #FJJ&001+b@QR VH /7

KJ2V2z2K0$..00?;?K ..44[AM-5$$ +6DD()+ 	 or;   c                4    | j                   | j                  dS )r   r  r  r6   s    r8   r   zAgent.tool_run_logging_kwargs  s     //"&"9"9
 	
r;   r   r   r   )rB   r   r   zstr | list[BaseMessage]r   r   )rB   r   rD   r
   r   zbuiltins.dict[str, Any]r   r&   r   )rc   r   r   r   )rc   r   r   r   )rD   r
   r   r   )NN)rb   r   rc   r   rd   r   r   zAgentOutputParser | NonerD   r
   r   r  )rZ   ro   rB   r   rD   r
   r   r   r   )r   r   r   r   r   r  r'   rs   r>   r   r9   r  r"  rE   rI   r$  rO   r%   r<  r   r  r  r   rA  rC  rE  re   r]   r   r   r   s   @r8   r  r    s<    $$$)&*M#*H "   
 
	9	 
!	  $595 5 	5
 
#50  $<9< < 	<
 
#<*(9( ( 
!	(& K K '" #: 5  5 2  2      8  8 
 8<26!
!
 "!
 5	!

 0!
 !
 
!
 !
F5"5 :5 	5
 
5n
r;   r  c                  r    e Zd ZU dZdZded<   	 dZded<   	 e	 d
	 	 	 	 	 dd       Ze	 d
	 	 	 	 	 dd	       Z	y)ExceptionToolz!Tool that just returns the query.
_Exceptionro   rG  zException tooldescriptionNc                    |S r   r5   r7   queryrun_managers      r8   _runzExceptionTool._run  s	     r;   c                   K   |S wr   r5   rU  s      r8   _arunzExceptionTool._arun  s      s   r   )rV  ro   rW  z CallbackManagerForToolRun | Noner   ro   )rV  ro   rW  z%AsyncCallbackManagerForToolRun | Noner   ro   )
r   r   r   r   rG  r   rS  r'   rX  rZ  r5   r;   r8   rQ  rQ    s    +D#'K'" 9= 6 
	   >B ; 
	 r;   rQ  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e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&e	 d5	 	 	 	 	 	 	 dLd3       Z'e	 d5	 	 	 	 	 	 	 dMd4       Z(y)NAgentExecutorzAgent that is using tools.7BaseSingleActionAgent | BaseMultiActionAgent | Runnableagentr   rc   Fr   return_intermediate_steps   z
int | Nonemax_iterationsNzfloat | Nonemax_execution_timerR   ro   rZ   z3bool | str | Callable[[OutputParserException], str]handle_parsing_errorszNint | Callable[[list[tuple[AgentAction, str]]], list[tuple[AgentAction, str]]]trim_intermediate_stepsc                     | d|||d|S )zCreate from agent and tools.

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

        Returns:
            Agent executor object.
        )r^  rc   rC   r5   r5   )ra   r^  rc   rC   rD   s        r8   from_agent_and_toolsz"AgentExecutor.from_agent_and_tools"  s)    &  

 	
 	
r;   r1  r2  c                   | j                   }| j                  }|j                         }|Rt        |      |D ch c]  }|j                   c}k7  r,d| d|D cg c]  }|j                   c} d}t        |      | S c c}w c c}w )zValidate that tools are compatible with agent.

        Args:
            values: Values to validate.

        Returns:
            Validated values.

        Raises:
            ValueError: If allowed tools are different than provided tools.
        zAllowed tools (z!) different than provided tools ())r^  rc   r>   r  rG  rX   )r7   r^  rc   r  rH  r\   s         r8   validate_toolszAgentExecutor.validate_tools<  s     



//1$]);"'@
DII@
 *
 "- 1#:?#@$DII#@"AD  S/!@

 $As   A?B
beforec                d   |j                  d      }|rjt        |t              rZ	 |j                  }|t        t
           t        z  k(  }|j                  dd      }|rt        ||      |d<   |S t        ||      |d<   |S # t        $ r d}Y Et        $ r t        j                  d       d}Y fw xY w)zConvert runnable to agent if passed in.

        Args:
            values: Values to validate.

        Returns:
            Validated values.
        r^  Fz.Unexpected error getting OutputType from agentr   T)r   r   )getrn   r   
OutputTyper  r   r   	TypeError	Exceptionr7  	exceptionpopr   r   )ra   valuesr^  output_typemulti_actionr   s         r8   validate_runnable_agentz%AgentExecutor.validate_runnable_agentV  s     

7#Zx0N#..  +d;.?+.MM$jj):DAO":"$3#w 	 #0"$3#w '  %$ %  !QR$%s   B   B/B/.B/c                z    t        | j                  t              rt        d| 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.
        RunnableAgentType)rn   r^  r   r   r6   s    r8   _action_agentzAgentExecutor._action_agentz  s.     djj(++TZZ88zzr;   c                    d}t        |      )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(...)`)rX   )r7   r   r\   s      r8   r   zAgentExecutor.save  s    ! 	
 or;   c                8    | j                   j                  |      S )zZSave the underlying agent.

        Args:
            file_path: Path to save to.
        )ry  r   )r7   r   s     r8   
save_agentzAgentExecutor.save_agent  s     !!&&y11r;   )include_run_infoasync_c               6    t        | ||| j                  |      S )aP  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:
            Agent executor iterator object.
        )tagsr}  )r)   r  )r7   r   rC   r}  r~  s        r8   iterzAgentExecutor.iter  s$    & %-
 	
r;   c                .    | j                   j                  S r   )ry  rO   r6   s    r8   rO   zAgentExecutor.input_keys  s     !!,,,r;   c                z    | j                   rg | j                  j                  dS | j                  j                  S )zReturn the singular output key.rB   )r_  ry  r9   r6   s    r8   output_keyszAgentExecutor.output_keys  s<     ))LT''55L7KLL!!///r;   c                \    | j                   D ci c]  }|j                  | c}|   S c c}w )zwLookup tool by name.

        Args:
            name: Name of tool.

        Returns:
            Tool object.
        )rc   rG  )r7   rG  rH  s      r8   lookup_toolzAgentExecutor.lookup_tool  s)     -1JJ7D		47==7s   )c                x    | j                   || j                   k\  ry| j                  d u xs || j                  k  S )NF)ra  rb  )r7   
iterationstime_elapseds      r8   _should_continuezAgentExecutor._should_continue  s?    *zT=P=P/P&&$.X,AXAX2XXr;   c                    |r|j                  |d| j                         |j                  }| j                  r||d<   |S Ngreen)colorverboserB   on_agent_finishr  r9   r_  r7   r4   rB   rW  r   s        r8   _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        r8   _areturnzAgentExecutor._areturn  sa      -- .   
 ++))1CL-.s   $AA
$Ac                    t        |d   t              r t        |      dk7  rd}t        |      |d   S |D cg c]+  }t        |t              s|j
                  |j                  f- c}S c c}w )Nrd     z>Expected a single AgentFinish output, but got multiple values.)rn   r   r  rX   r   r   r!  )r7   rs  r\   as       r8   _consume_next_stepz AgentExecutor._consume_next_step  sa     fRj+.6{aV o%":39VaZ9=U1==)VVVs   A+A+c                \    | j                  t        | j                  |||||                  S r   )r  r  _iter_next_step)r7   name_to_tool_mapcolor_mappingr   rB   rW  s         r8   _take_next_stepzAgentExecutor._take_next_step  s<     &&$$$!&

 
	
r;   c              #  t  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d|}	t        |	      |t        |      }
t        | j                  t              r:|j                  r+t        |j                        }t        |j                        }
n_d}n\t        | j                  t              r| j                  }n5t        | j                        r| j                  |      }nd}	t        |	      |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.
        rC   NFAn output parsing error occurred. In order to pass this error back to the agent and have it try again, pass `handle_parsing_errors=True` to the AgentExecutor. This is the error: Invalid or incomplete response.Got unexpected type of `handle_parsing_errors`rR  r  r  r  r  rC   r   r!  )_prepare_intermediate_stepsry  rE   	get_childr   rn   rc  r   rX   ro   send_to_llmr!  
llm_outputcallabler   on_agent_actionr   rQ  r
  
tool_inputr  r   r   _perform_agent_action)r7   r  r  r   rB   rW  r4   eraise_errorr\   r   r!  tool_run_kwargsactionsagent_actions                  r8   r  zAgentExecutor._iter_next_step  s=    0	!%!A!ABT!U -T'',,"5@+//1d F^ fk*L )=6(6# 	L	# 	L,, 	 	e % '	$44d;"&"<"<<#* +,0  !o1,q6D$44d;=="%amm"4Kq||,D"BKD66<"88$445"88;F o1, {DAF++F'+B"00HHJO--/--!!5@+//1d	
 "K 6{CCO'	s1   H8AB AH8
H5#FH0+H80H55H8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  rT   r  r  requested_tool_nameavailable_tool_namesr  )r  rH  return_directry  r   r
  r  r  r  r+   r  keysr   
r7   r  r  r  rW  rH  r  r  r  r!  s
             r8   r  z#AgentExecutor._perform_agent_actiond  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r   )r  _aiter_next_step)r7   r  r  r   rB   rW  r  s          r8   _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d|}	t        |	      |t        |      }
t        | j                  t              r:|j                  r+t        |j                        }t        |j                        }
n_d}n\t        | j                  t              r| j                  }n5t        | j                        r| j                  |      }nd}	t        |	      |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  rC   NFr  r  r  rR  r  r  )r  ry  rI   r  r   rn   rc  r   rX   ro   r  r!  r  r  r   r   rQ  r  r  r  r   r   asynciogather_aperform_agent_action)r7   r  r  r   rB   rW  r4   r  r  r\   r   r!  r  r  r  resultr   s                    r8   r  zAgentExecutor._aiter_next_step  st    .	!%!A!ABT!U 44--33"5@+//1d  FZ fk*L )=6(6# 	L	 ~~ %, ! ++$! 	

 

  	EK	I
 % %	$44d;"&"<"<<#* +,0  !o1,q6D$44d;=="%amm"4Kq||,D"BKD66<"88$445"88;F o1, {DAF"00HHJO 4 4 4!!!5@+//1d	!
 "!  K 6{CCK%	f

sg   I*AC 	C
C A
I*I"3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  rT   r  r  r  r  )r  r  rH  r  ry  r   r  r  r  r+   r  r  r   r  s
             r8   r  z$AgentExecutor._aperform_agent_action  st     -- .     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FC	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           rW  r  )rc   rG  r"   timer  r  rn   r   r  extendr  _get_tool_returnry  r]   rZ   r7   r   rW  rH  r  r  rB   r  r  
start_timenext_step_outputnext_step_actiontool_returnr4   s                 r8   _callzAgentExecutor._call"  s    9=

CDIItOCC)#'::.4TYY.$e,
 =?
YY[
##J=#33 "'  4   *K8||$& + $   %%&67#$)#3A#6 "334DE*<<#*$/ (  
 !OJ99;3L7 ##J=8 <##;;&&
 

 ||F$6K|PP[ 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  )rc   rG  r"   r  r.   rb  r  r  rn   r   r  r  r  r  ry  r]   rZ   TimeoutErrorr  r  s                 r8   _acallzAgentExecutor._acallX  s     9=

CDIItOCC)#'::.4TYY.$I
 =?
YY[
4	&t'>'>? ' '++JE-1-B-B(%*$/ .C . ($ ""2K@%)]],.(3 &3 &  ' ' '  '--.>?+,1+;A+>(&*&;&;<L&M&2)- + 2,7 *7 * $-' ' '8 !OJ#'99;#;L9 ++JE: D++CC..& 
 "]]& + +  G' ' ' D /'( ',$-'FG' ' ' 'P g223 	?T''??**" 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.r4   r   rT   N)rc   rG  r  ry  r9   rH  r  r   )r7   r  r  r!  rH  r  return_value_keys          r8   r  zAgentExecutor._get_tool_return  s    
 %5!k8<

CDIItOCC#t!!//014#11??B !11 !2!23AA!;/   Ds   Bc                    t        | j                  t              r| j                  dkD  r|| j                   d  S t        | j                        r| j                  |      S |S )Nr   )rn   re  intr  )r7   rB   s     r8   r  z)AgentExecutor._prepare_intermediate_steps  s_    
 t33S9,,q0%t'C'C&C&EFFD001//0BCC!!r;   c           	   +     K   t        |      }t        | ||j                  d      f|j                  d      |j                  d      |j                  d      |j                  d      dd|}|E d{    y7 w)	zEnables streaming over steps taken to reach final output.

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

        Yields:
            Addable dictionary.
        rC   r  metadatarun_namerun_idTr  r  r  r  yield_actionsNr   r)   rm  )r7   inputr   rD   iterators        r8   r   zAgentExecutor.stream  s}     " v&(JJ{#

 F#ZZ
+ZZ
+::h'

 

 s   A0A:2A83A:c           	      K   t        |      }t        | ||j                  d      f|j                  d      |j                  d      |j                  d      |j                  d      dd|}|2 3 d{   }| 7 
6 yw)	zAsync enables streaming over steps taken to reach final output.

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

        Yields:
            Addable dictionary.
        rC   r  r  r  r  Tr  Nr  )r7   r  r   rD   r  steps         r8   r   zAgentExecutor.astream  s     " v&(JJ{#

 F#ZZ
+ZZ
+::h'

 

 # 	 	$J	(s*   A-B/B 3A>4B 7B>B  Br   )
r^  r]  rc   r   rC   r   rD   r
   r   r\  rO  )rs  rs   r   r
   )r   z,BaseSingleActionAgent | BaseMultiActionAgentr   )
r   r
   rC   r   r}  r   r~  r   r   r)   r   )rG  ro   r   r!   )r  r  r  floatr   r   )r4   r   rB   r  rW  !CallbackManagerForChainRun | Noner   dict[str, Any])r4   r   rB   r  rW  &AsyncCallbackManagerForChainRun | Noner   r  )rs  NextStepOutputr   +AgentFinish | list[tuple[AgentAction, str]])r  dict[str, BaseTool]r  dict[str, str]r   r  rB   r   rW  r  r   r  )r  r  r  r  r   r  rB   r   rW  r  r   z/Iterator[AgentFinish | AgentAction | AgentStep])
r  r  r  r  r  r   rW  r  r   r   )r  r  r  r  r   r  rB   r   rW  r  r   r  )r  r  r  r  r   r  rB   r   rW  r  r   z4AsyncIterator[AgentFinish | AgentAction | AgentStep])
r  r  r  r  r  r   rW  r  r   r   )r   r  rW  r  r   r  )r   r  rW  r  r   r  )r  ztuple[AgentAction, str]r   zAgentFinish | None)rB   r   r   r   )r  dict[str, Any] | Anyr   RunnableConfig | NonerD   r
   r   zIterator[AddableDict])r  r  r   r  rD   r
   r   zAsyncIterator[AddableDict]))r   r   r   r   r   r_  ra  rb  rZ   rc  re  r   rg  r%   rj  rv  r   ry  r'   r   r|  r  rO   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r   r5   r;   r8   r\  r\    s   $BB3-&+t+3!#NJ#9 (,+ ")3( RWNV 	 V 
  $	
F
 "
 	

 
 

 
2 '" #2 (#   $ D     2  $

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

 
 
 

6 - - 0 0	>Y :>	 ! 7	
 
" ?C	 ! <	
 
"	W	W 
5	W" :>
-
 &
 	

 :
 7
 
5
4 :>M-M &M 	M
 :M 7M 
9Mh :>%G-%G &%G "	%G
 7%G 
%GZ ?C
-
 &
 	

 :
 <
 
5
6 ?CU-U &U 	U
 :U <U 
>Ux ?C)G-)G &)G "	)G
 <)G 
)G\ :>4Q4Q 74Q 
	4Qr ?CGG <G 
	GR1 
*"9" 
'"  )-# & 	
 
 <  )-# & 	
 
$ r;   r\  )`r   
__future__r   r  builtinsr   r   loggingr  abcr   collections.abcr   r   r   r   pathlibr	   typingr
   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&   r'   "langchain_classic._api.deprecationr(   'langchain_classic.agents.agent_iteratorr)   $langchain_classic.agents.agent_typesr*   langchain_classic.agents.toolsr+   langchain_classic.chains.baser,   langchain_classic.chains.llmr-   #langchain_classic.utilities.asyncior.   	getLoggerr   r7  r0   r   r   r  r   r   r   r   r  rQ  r  rx  r\  r5   r;   r8   <module>r     s   K "        G G 
  * E E  < < / : 5 A 8 L L 6 ) 8 ; ; , H I : 6 / 1 ?			8	$cI cLI9 IX3({)BC 3T+&45(i) iXn3 nb %
Q
0 Q

Q
h %
T
! T

T
nH 2 kK/);<!$<< LE Lr;   