
    hSA                    ,   d dl mZ d dlZd dlZd dlZd dlmZ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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jT                  e+      Z, G d d      Z-y)    )annotationsN)AsyncIteratorIterator)TYPE_CHECKINGAnyOptional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/eduruby.in/venv/lib/python3.12/site-packages/langchain/agents/agent_iterator.py__init__zAgentExecutorIterator.__init__-   sP    B  ."	   0*

    dict[str, str]_inputsc                    | j                   S )z The inputs to the AgentExecutor.)r4   r.   s    r0   r,   zAgentExecutorIterator.inputsb   s     ||r2   c                D    | j                   j                  |      | _        y N)r/   prep_inputsr4   )r.   r,   s     r0   r,   zAgentExecutorIterator.inputsg   s    **66v>r2   c                    | j                   S )z"The AgentExecutor to iterate over.)r+   r6   s    r0   r/   z$AgentExecutorIterator.agent_executork   s     ###r2   c                4    || _         | j                  | _        y r8   )r+   r,   )r.   r/   s     r0   r/   z$AgentExecutorIterator.agent_executorp   s    -kkr2   c                j    | j                   j                  D ci c]  }|j                  | c}S c c}w )z!A mapping of tool names to tools.)r/   toolsnamer.   tools     r0   name_to_tool_mapz&AgentExecutorIterator.name_to_tool_mapv   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   r/   r=   r>   r?   s     r0   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_timer6   s    r0   r-   zAgentExecutorIterator.reset   s5    
 	GHAC))+r2   c                    | xj                   dz  c_         t        j                         | j                  z
  | _        t        j                  d| j                   | j                         y)zQ
        Increment the number of iterations and update the time elapsed.
           z$Agent Iterations: %s (%.2fs elapsed)N)rK   rM   rN   rL   rH   rI   r6   s    r0   update_iterationsz'AgentExecutorIterator.update_iterations   sH     	1 IIK$//92OO	
r2   c                    t        | j                  j                  | j                  |d            }| j                  rt        |j                        |t        <   |S )NT)return_only_outputs)r!   )r   r/   prep_outputsr,   r"   r   r!   r   )r.   outputsrun_managerprepared_outputss       r0   make_final_outputsz(AgentExecutorIterator.make_final_outputs   s\     ',,$( - 
   (/{7I7I(JW%r2   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r>   actionsmessagesstepsr]   intermediate_step)#rH   rI   r-   r   	configurer$   r/   verboser   r   on_chain_startr   r,   r!   r    _should_continuerK   rL   _iter_next_steprA   rF   rJ   appendr#   
isinstancer   r   r]   r   _consume_next_steprQ   _process_next_step_outputBaseExceptionon_chain_error_stop	r.   callback_managerrV   next_step_seqchunk	next_stepoutputis_finales	            r0   __iter__zAgentExecutorIterator.__iter__   s7    9:

*44NN))''II$$MM((
 '55$%%&KKKK	 6 
(	%%66!! 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I %%66!!T 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)rZ   Nr[   r^   r`   )'rH   rI   r-   r   ra   r$   r/   rb   r   r   rc   r   r,   r!   r    r   max_execution_timerd   rK   rL   _aiter_next_steprA   rF   rJ   rf   r#   rg   r   r   r]   r   rh   rQ   _aprocess_next_step_outputTimeoutErrorasyncio_astoprj   rk   rm   s	            r0   	__aiter__zAgentExecutorIterator.__aiter__   s    
 	AB

/99NN))''II$$MM((
 -;;$%%&KKKK	 < 
 
5	&t':':'M'MN . .))::OO%% 57M'+':':'K'K--**//#( " "e &,,U3  --)%=&1-2G-2^^'" !" ",E9!=&1+0'-2^^'" !"3. .n KK,,,}
." (. !% 3 3 F F} UI**,#'#B#B!#$  F  3&@H  --$]. . .))::OO%%. . . .^ 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rV   +Updated intermediate_steps with step outputrP   r   r`   )rH   rI   rg   r   _returnrJ   extendlenr/   _get_tool_returnr   r.   next_step_outputrV   next_step_actiontool_returns        r0   ri   z/AgentExecutorIterator._process_next_step_output=  s     	;<&4LLT << 0k<JJ&&'78BC  A%/2-->>?OPK&||K[|II-=>>r2   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   rP   r   r   )rH   rI   rg   r   _areturnrJ   r   r   r/   r   r   r   s        r0   ry   z0AgentExecutorIterator._aprocess_next_step_outputY  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   )	rH   warningr/   _action_agentreturn_stopped_responseearly_stopping_methodrJ   r,   r   r.   rV   rr   s      r0   rl   zAgentExecutorIterator._stopu  sj     	TUJ$$22JJ55##
 kk

 ||F|<<r2   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)	rH   r   r/   r   r   r   rJ   r,   r   r   s      r0   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]   )r/   r   rJ   r]   on_chain_endrX   r.   rr   rV   returned_outputs       r0   r   zAgentExecutorIterator._return  s_     --55### 6 

 '-oo
#  1&&DDr2   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]   )r/   r   rJ   r]   r   rX   r   s       r0   r   zAgentExecutorIterator._areturn  sy      !% 3 3 < <### != !
 

 '-oo
#&&777&&DD
 	8s!   ,A1A-'A1A/A1/A1r8   )r/   r   r,   r   r$   r   r   r%   r   r&   r    r'   r!   r(   r"   r)   r#   r)   )returnr3   )r,   r   r   None)r   r   )r/   r   r   r   )r   zdict[str, BaseTool])r   r   )rU   zdict[str, Any]rV   zBUnion[CallbackManagerForChainRun, AsyncCallbackManagerForChainRun]r   r   )r.   r   r   zIterator[AddableDict])r   zAsyncIterator[AddableDict])r   1Union[AgentFinish, list[tuple[AgentAction, str]]]rV   r   r   r   )r   r   rV   r   r   r   )rV   r   r   r   )rV   r   r   r   )rr   r   rV   r   r   r   )rr   r   rV   r   r   r   )__name__
__module____qualname____doc__r1   __annotations__propertyr,   setterr/   rA   rF   r-   rQ   rX   ru   r}   ri   ry   rl   r|   r   r    r2   r0   r   r   *   s   %  $	* %)-1"&!%!&#*%* * 	* "* +*  * * * *X 
&&  ]]? ? $ $ " "
 G G 
 

&

   X  
	 &=&~N-`?K? 0? 
	?8?K? 5? 
	?8=DEE 0E 
	E"EE 5E 
	Er2   r   ).
__future__r   r{   loggingrM   collections.abcr   r   typingr   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   rH   r   r   r2   r0   <module>r      st    "    3   
  + * 6 ) 8 $ 7D			8	$EE EEr2   