
    9|hF@                    0   d dl mZ d dlZd dlZd dlZd dlmZmZmZm	Z	m
Z
mZmZmZm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 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'm(Z( erd dl)m*Z*m+Z+  ejX                  e-      Z. G d d      Z/y)    )annotationsN)	TYPE_CHECKINGAnyAsyncIteratorDictIteratorListOptionalTupleUnion)UUID)AgentActionAgentFinish	AgentStep)AsyncCallbackManagerAsyncCallbackManagerForChainRunCallbackManagerCallbackManagerForChainRun	Callbacks)dumpd)RunInfo)AddableDict)BaseTool)get_color_mapping)RUN_KEY)asyncio_timeout)AgentExecutorNextStepOutputc                     e Zd ZU dZ	 d&ddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d'dZded<   ded<   ded<   d
ed	<   ded<   ded<   ded<   ded<   ed(d       Zej                  d)d       Zed*d       Z	e	j                  d+d       Z	ed,d       Z
ed(d       Zd-dZd-dZ	 	 	 	 	 	 d.dZd/dZd0dZ	 	 	 	 	 	 d1d Z	 	 	 	 	 	 d2d!Zd3d"Zd4d#Z	 	 	 	 	 	 d5d$Z	 	 	 	 	 	 d6d%Zy)7AgentExecutorIteratorzIterator for AgentExecutor.NF)tagsmetadatarun_namerun_idinclude_run_infoyield_actions	callbacksr   r!   Optional[list[str]]r"   Optional[Dict[str, Any]]r#   Optional[str]r$   Optional[UUID]r%   boolr&   c                   || _         || _        || _        || _        || _        || _        || _        || _        |	| _        | j                          y)a+  
        Initialize the AgentExecutorIterator with the given AgentExecutor,
        inputs, and optional callbacks.

        Args:
            agent_executor (AgentExecutor): The AgentExecutor to iterate over.
            inputs (Any): The inputs to the AgentExecutor.
            callbacks (Callbacks, optional): The callbacks to use during iteration.
                Defaults to None.
            tags (Optional[list[str]], optional): The tags to use during iteration.
                Defaults to None.
            metadata (Optional[Dict[str, Any]], optional): The metadata to use
                during iteration. Defaults to None.
            run_name (Optional[str], optional): The name of the run. Defaults to None.
            run_id (Optional[UUID], optional): The ID of the run. Defaults to None.
            include_run_info (bool, optional): Whether to include run info
                in the output. Defaults to False.
            yield_actions (bool, optional): Whether to yield actions as they
                are generated. Defaults to False.
        N)
_agent_executorinputsr'   r!   r"   r#   r$   r%   r&   reset)
selfagent_executorr/   r'   r!   r"   r#   r$   r%   r&   s
             ^/var/www/html/test/engine/venv/lib/python3.12/site-packages/langchain/agents/agent_iterator.py__init__zAgentExecutorIterator.__init__1   sP    B  ."	   0*

    Dict[str, str]_inputsc                    | j                   S )z The inputs to the AgentExecutor.)r7   r1   s    r3   r/   zAgentExecutorIterator.inputsf   s     ||r5   c                D    | j                   j                  |      | _        y N)r2   prep_inputsr7   )r1   r/   s     r3   r/   zAgentExecutorIterator.inputsk   s    **66v>r5   c                    | j                   S )z"The AgentExecutor to iterate over.)r.   r9   s    r3   r2   z$AgentExecutorIterator.agent_executoro   s     ###r5   c                4    || _         | j                  | _        y r;   )r.   r/   )r1   r2   s     r3   r2   z$AgentExecutorIterator.agent_executort   s    -kkr5   c                j    | j                   j                  D ci c]  }|j                  | c}S c c}w )z!A mapping of tool names to tools.)r2   toolsnamer1   tools     r3   name_to_tool_mapz&AgentExecutorIterator.name_to_tool_mapz   s,     -1,?,?,E,EFD		4FFFs   0c                    t        | j                  j                  D cg c]  }|j                   c}ddg      S c c}w )z"A mapping of tool names to colors.greenred)excluded_colors)r   r2   r@   rA   rB   s     r3   color_mappingz#AgentExecutorIterator.color_mapping   s:     !#'#6#6#<#<=4TYY=$e,
 	
=s   <c                    t         j                  d       g | _        d| _        d| _        t        j
                         | _        y)z}
        Reset the iterator to its initial state, clearing intermediate steps,
        iterations, and time elapsed.
        z0(Re)setting AgentExecutorIterator to fresh stater   g        N)loggerdebugintermediate_steps
iterationstime_elapsedtime
start_timer9   s    r3   r0   zAgentExecutorIterator.reset   s5    
 	GHAC))+r5   c                    | xj                   dz  c_         t        j                         | j                  z
  | _        t        j                  d| j                    d| j                  dd       y)zQ
        Increment the number of iterations and update the time elapsed.
           zAgent Iterations: z (z.2fz
s elapsed)N)rN   rP   rQ   rO   rK   rL   r9   s    r3   update_iterationsz'AgentExecutorIterator.update_iterations   sU     	1 IIK$//9  1D4E4Ec3J*U	
r5   c                    t        | j                  j                  | j                  |d            }| j                  rt        |j                        |t        <   |S )NT)return_only_outputs)r$   )r   r2   prep_outputsr/   r%   r   r$   r   )r1   outputsrun_managerprepared_outputss       r3   make_final_outputsz(AgentExecutorIterator.make_final_outputs   sZ     ',,W$ - 

   (/{7I7I(JW%r5   c           	   #  X  K   t         j                  d       | j                          t        j                  | j
                  | j                  j
                  | j                  j                  | j                  | j                  j                  | j                  | j                  j                        }|j                  t        | j                        | j                  | j                  | j                        }	 | j                  j                  | j                   | j"                        rJg }| j                  j%                  | j&                  | j(                  | j                  | j*                  |      D ]v  }|j-                  |       | j.                  s!t1        |t2              rt5        |g|j6                         Lt1        |t8              s]t5        |g|j6                         x | j                  j;                  |      }| j=                          | j?                  ||      }d|v}| j.                  r|r| |ry | j                  j                  | j                   | j"                        rJ| jE                  |       y # t@        $ r}|jC                  |        d }~ww xY ww)Nz"Initialising AgentExecutorIteratorrA   actionsmessagesstepsr`   intermediate_step)#rK   rL   r0   r   	configurer'   r2   verboser!   r"   on_chain_startr   r/   r$   r#   _should_continuerN   rO   _iter_next_steprD   rI   rM   appendr&   
isinstancer   r   r`   r   _consume_next_steprT   _process_next_step_outputBaseExceptionon_chain_error_stop	r1   callback_managerrY   next_step_seqchunk	next_stepoutputis_finales	            r3   __iter__zAgentExecutorIterator.__iter__   s5    9:

*44NN))''II$$MM((
 '55$%%&KKKK	 6 
'	%%66!2!2
 13!00@@))&&KK++ VE "((/ ))%e[9"-ug"WW'y9"-UGenn"UUV" !//BB=Q	&&(77	;O.f< ))X LG %%66!2!2R jj%%  	&&q)	sD   C5J*8BJ ;J A1J  J*0J 3J*	J'J""J''J*c           	      K   t         j                  d       | j                          t        j                  | j
                  | j                  j
                  | j                  j                  | j                  | j                  j                  | j                  | j                  j                        }|j                  t        | j                        | j                  | j                  | j                         d{   }	 t        | j                  j                         4 d{    | j                  j#                  | j$                  | j&                        rg }| j                  j)                  | j*                  | j,                  | j                  | j.                  |      2 3 d{   }|j1                  |       | j2                  s't5        |t6              rt9        |g|j:                         St5        |t<              sdt9        |g|j:                         ddd      d{    | jI                  |       d{    y7 T7 .7 6 | j                  j?                  |      }| jA                          | jC                  ||       d{  7  }d|v}| j2                  r|r| |r	 ddd      d{  7   y| j                  j#                  | j$                  | j&                        r7 # 1 d{  7  sw Y   xY w# tD        tF        jD                  f$ r  | jI                  |       d{  7   Y ytJ        $ r }|jM                  |       d{  7    d}~ww xY w7 1w)z
        N.B. __aiter__ must be a normal method, so need to initialize async run manager
        on first __anext__ call where we can await it
        z*Initialising AgentExecutorIterator (async)r]   Nr^   ra   rc   )'rK   rL   r0   r   rd   r'   r2   re   r!   r"   rf   r   r/   r$   r#   r   max_execution_timerg   rN   rO   _aiter_next_steprD   rI   rM   ri   r&   rj   r   r   r`   r   rk   rT   _aprocess_next_step_outputTimeoutErrorasyncio_astoprm   rn   rp   s	            r3   	__aiter__zAgentExecutorIterator.__aiter__   s    
 	AB

/99NN))''II$$MM((
 -;;$%%&KKKK	 < 
 
1	&t':':'M'MN * *))::OOT%6%6
 57M'+':':'K'K--**//#( " "e &,,U3  --)%=&1-2Genn'" !" ",E9!=&1+0'ENN'" !"/* *f KK,,,u
*" (* !% 3 3 F F} UI**,#'#B#B!;$  F  3&@H  --$U* * *))::OOT%6%6* * * *V g223 	K0000 	,,Q///	
 -s
  C8M9:I;M9 #L #I$L 'A:K>!I%I&I)K><K>K>!L ,K<-L 1M9M6	M9L IAK>JK>7L KL M9	0K><L >LLLL -M3 MM3	M9M3M.'M*(M..M33M9c                   t         j                  d       t        |t              r(t         j                  d       | j	                  ||      S | j
                  j                  |       t         j                  d       t        |      dk(  r5|d   }| j                  j                  |      }|| j	                  ||      S t        |      S )zj
        Process the output of the next step,
        handling AgentFinish and tool return cases.
        z$Processing output of Agent loop stepzBHit AgentFinish: _return -> on_chain_end -> run final output logicrY   +Updated intermediate_steps with step outputrS   r   rc   )rK   rL   rj   r   _returnrM   extendlenr2   _get_tool_returnr   r1   next_step_outputrY   next_step_actiontool_returns        r3   rl   z/AgentExecutorIterator._process_next_step_output8  s     	;<&4LLT << 0k<JJ&&'78BC  A%/2-->>?OPK&||K[|II-=>>r5   c                  K   t         j                  d       t        |t              r0t         j                  d       | j	                  ||       d{   S | j
                  j                  |       t         j                  d       t        |      dk(  r=|d   }| j                  j                  |      }|| j	                  ||       d{   S t        |      S 7 7 w)	zp
        Process the output of the next async step,
        handling AgentFinish and tool return cases.
        z*Processing output of async Agent loop stepzCHit AgentFinish: _areturn -> on_chain_end -> run final output logicr   Nr   rS   r   r   )rK   rL   rj   r   _areturnrM   r   r   r2   r   r   r   s        r3   r|   z0AgentExecutorIterator._aprocess_next_step_outputT  s      	AB&4LLU '7[QQQ&&'78BC  A%/2-->>?OPK&!]];K]PPP-=>> R Qs%   AC#CA:C#C!C#!C#c                    t         j                  d        | j                  j                  j                  | j                  j
                  | j                  fi | j                  }| j                  ||      S )zb
        Stop the iterator and raise a StopIteration exception with the stopped response.
        ;Stopping agent prematurely due to triggering stop conditionr   )	rK   warningr2   _action_agentreturn_stopped_responseearly_stopping_methodrM   r/   r   r1   rY   ru   s      r3   ro   zAgentExecutorIterator._stopp  sj     	TUJ$$22JJ55##
 kk

 ||F|<<r5   c                  K   t         j                  d        | j                  j                  j                  | j                  j
                  | j                  fi | j                  }| j                  ||       d{   S 7 w)zu
        Stop the async iterator and raise a StopAsyncIteration exception with
        the stopped response.
        r   r   N)	rK   r   r2   r   r   r   rM   r/   r   r   s      r3   r   zAgentExecutorIterator._astop}  st     
 	TUJ$$22JJ55##
 kk

 ]]6{]CCCCs   A<B>B?Bc                    | j                   j                  || j                  |      }|j                  |d<   |j	                  |       | j                  ||      S )z:
        Return the final output of the iterator.
        r   r`   )r2   r   rM   r`   on_chain_endr[   r1   ru   rY   returned_outputs       r3   r   zAgentExecutorIterator._return  s]     --55D++ 6 
 '-oo
#  1&&DDr5   c                   K   | j                   j                  || j                  |       d{   }|j                  |d<   |j	                  |       d{    | j                  ||      S 7 >7 w)z@
        Return the final output of the async iterator.
        r   Nr`   )r2   r   rM   r`   r   r[   r   s       r3   r   zAgentExecutorIterator._areturn  sw      !% 3 3 < <D++ != !
 
 '-oo
#&&777&&DD
 	8s!   ,A1A-'A1A/A1/A1r;   )r2   r   r/   r   r'   r   r!   r(   r"   r)   r#   r*   r$   r+   r%   r,   r&   r,   )returnr6   )r/   r   r   None)r   r   )r2   r   r   r   )r   zDict[str, BaseTool])r   r   )rX   zDict[str, Any]rY   zBUnion[CallbackManagerForChainRun, AsyncCallbackManagerForChainRun]r   r   )r1   z'AgentExecutorIterator'r   zIterator[AddableDict])r   zAsyncIterator[AddableDict])r   1Union[AgentFinish, List[Tuple[AgentAction, str]]]rY   r   r   r   )r   r   rY   r   r   r   )rY   r   r   r   )rY   r   r   r   )ru   r   rY   r   r   r   )ru   r   rY   r   r   r   )__name__
__module____qualname____doc__r4   __annotations__propertyr/   setterr2   rD   rI   r0   rT   r[   rx   r   rl   r|   ro   r   r   r    r5   r3   r    r    .   s   %  $	* %)-1"&!%!&#*%* * 	* "* +*  * * * *X 
&&  ]]? ? $ $ " "
 G G 
 

&
   X  
	 "<&|J-X?K? 0? 
	?8?K? 5? 
	?8=DE!E0JE	EE!E0OE	Er5   r    )0
__future__r   r~   loggingrP   typingr   r   r   r   r   r	   r
   r   r   uuidr   langchain_core.agentsr   r   r   langchain_core.callbacksr   r   r   r   r   langchain_core.load.dumpr   langchain_core.outputsr   langchain_core.runnables.utilsr   langchain_core.toolsr   langchain_core.utils.inputr   langchain.schemar   langchain.utilities.asyncior   langchain.agents.agentr   r   	getLoggerr   rK   r    r   r5   r3   <module>r      sv    "   
 
 
  
  + * 6 ) 8 $ 7D			8	$tE tEr5   