
    NgF@                    4   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j,        e-          Z. G d d          Z/dS )    )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        dAd            Z	edBd             Z
ed>d!            ZdCd"ZdCd#ZdDd)ZdEd-ZdFd/ZdGd3ZdHd5ZdId6ZdJd7ZdKd:ZdLd;ZdS )MAgentExecutorIteratorzIterator for AgentExecutor.NF)tagsmetadatarun_namerun_idinclude_run_infoyield_actionsagent_executorr   inputsr   	callbacksr   r!   Optional[list[str]]r"   Optional[Dict[str, Any]]r#   Optional[str]r$   Optional[UUID]r%   boolr&   c                   || _         || _        || _        || _        || _        || _        || _        || _        |	| _        | 	                                 dS )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_executorr(   r)   r!   r"   r#   r$   r%   r&   reset)
selfr'   r(   r)   r!   r"   r#   r$   r%   r&   s
             [/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain/agents/agent_iterator.py__init__zAgentExecutorIterator.__init__1   sX    B  ."	   0*

    Dict[str, str]_inputsreturnc                    | j         S )z The inputs to the AgentExecutor.)r7   r2   s    r3   r(   zAgentExecutorIterator.inputsf   s     |r5   Nonec                D    | j                             |          | _        d S N)r'   prep_inputsr7   )r2   r(   s     r3   r(   zAgentExecutorIterator.inputsk   s    *66v>>r5   c                    | j         S )z"The AgentExecutor to iterate over.)r0   r:   s    r3   r'   z$AgentExecutorIterator.agent_executoro   s     ##r5   c                ,    || _         | j        | _        d S r=   )r0   r(   )r2   r'   s     r3   r'   z$AgentExecutorIterator.agent_executort   s    -kr5   Dict[str, BaseTool]c                .    d | j         j        D             S )z!A mapping of tool names to tools.c                    i | ]
}|j         |S  name.0tools     r3   
<dictcomp>z:AgentExecutorIterator.name_to_tool_map.<locals>.<dictcomp>}   s    FFFD	4FFFr5   )r'   toolsr:   s    r3   name_to_tool_mapz&AgentExecutorIterator.name_to_tool_mapz   s     GFD,?,EFFFFr5   c                P    t          d | j        j        D             ddg          S )z"A mapping of tool names to colors.c                    g | ]	}|j         
S rD   rE   rG   s     r3   
<listcomp>z7AgentExecutorIterator.color_mapping.<locals>.<listcomp>   s    ===4TY===r5   greenred)excluded_colors)r   r'   rK   r:   s    r3   color_mappingz#AgentExecutorIterator.color_mapping   s:     !==4#6#<===$e,
 
 
 	
r5   c                    t                               d           g | _        d| _        d| _        t          j                    | _        dS )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_timer:   s    r3   r1   zAgentExecutorIterator.reset   s?    
 	GHHHAC)++r5   c                    | xj         dz  c_         t          j                    | j        z
  | _        t                              d| j          d| j        dd           dS )zQ
        Increment the number of iterations and update the time elapsed.
           zAgent Iterations: z (z.2fz
s elapsed)N)rX   rZ   r[   rY   rU   rV   r:   s    r3   update_iterationsz'AgentExecutorIterator.update_iterations   sg     	1 IKK$/9UUUD4EUUUU	
 	
 	
 	
 	
r5   outputsDict[str, Any]run_managerBUnion[CallbackManagerForChainRun, AsyncCallbackManagerForChainRun]r   c                    t          | j                            | j        |d                    }| j        rt          |j                  |t          <   |S )NT)return_only_outputs)r$   )r   r'   prep_outputsr(   r%   r   r$   r   )r2   r_   ra   prepared_outputss       r3   make_final_outputsz(AgentExecutorIterator.make_final_outputs   se     ',,W$ -  
 

   	K(/{7I(J(J(JW%r5   r2   'AgentExecutorIterator'Iterator[AddableDict]c           	   #    K   t                               d           |                                  t          j        | j        | j        j        | j        j        | j        | j        j        | j	        | j        j	                  }|
                    t          | j                  | j        | j        | j                  }	 | j                            | j        | j                  r/g }| j                            | j        | j        | j        | j        |          D ]{}|                    |           | j        r]t1          |t2                    rt5          |g|j                  V  Mt1          |t8                    rt5          |g|j                  V  || j                            |          }|                                  |                     ||          }d|v}| j        r|r|V  |rd S | j                            | j        | j                  /n(# t@          $ r}|!                    |            d }~ww xY w| "                    |          V  d S )Nz"Initialising AgentExecutorIteratorrE   actionsmessagesstepsrm   intermediate_step)#rU   rV   r1   r   	configurer)   r'   verboser!   r"   on_chain_startr   r(   r$   r#   _should_continuerX   rY   _iter_next_steprL   rS   rW   appendr&   
isinstancer   r   rm   r   _consume_next_stepr^   _process_next_step_outputBaseExceptionon_chain_error_stop	r2   callback_managerra   next_step_seqchunk	next_stepoutputis_finales	            r3   __iter__zAgentExecutorIterator.__iter__   s     9:::

*4N)'I$M(
 
 '55$%&&KK	 6 
 
'	%66!2  #
 13!0@@)&K+  V VE "((/// ) V%e[99 V"-ug"W"W"WWWWW'y99 V"-UGen"U"U"UUUU !/BB=QQ	&&(((77	;OO.f< ) !X ! LLL FG %66!2  #H  	 	 	&&q)))	
 jj%%%%%%%s   =D-H ,&H 
H8H33H8AsyncIterator[AddableDict]c           	      K   t                               d           |                                  t          j        | j        | j        j        | j        j        | j        | j        j        | j	        | j        j	                  }|
                    t          | j                  | j        | j        | j                   d{V }	 t          | j        j                  4 d{V  | j                            | j        | j                  rPg }| j                            | j        | j        | j        | j        |          2 3 d{V }|                    |           | j        r_t5          |t6                    rt9          |g|j                  W V  St5          |t<                    rt9          |g|j                  W V  6 | j                            |          }|                                   | !                    ||           d{V }d|v}| j        r|r|W V  |r	 ddd          d{V  dS | j                            | j        | j                  P	 ddd          d{V  n# 1 d{V swxY w Y   nd# tD          tF          j"        f$ r" | $                    |           d{V W V  Y dS tJ          $ r!}|&                    |           d{V   d}~ww xY w| $                    |           d{V W V  dS )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)rE   Nrk   rn   rp   )'rU   rV   r1   r   rq   r)   r'   rr   r!   r"   rs   r   r(   r$   r#   r   max_execution_timert   rX   rY   _aiter_next_steprL   rS   rW   rv   r&   rw   r   r   rm   r   rx   r^   _aprocess_next_step_outputTimeoutErrorasyncio_astoprz   r{   r}   s	            r3   	__aiter__zAgentExecutorIterator.__aiter__   s     
 	ABBB

/9N)'I$M(
 
 -;;$%&&KK	 < 
 
 
 
 
 
 
 
1	&t':'MNN * * * * * * * *)::OT%6  )
 57M'+':'K'K-*/#( ( " " " " " " "e &,,U333  - ")%== "&1-2Gen'" '" '" !" !" !" !" !" ",E9!=!= "&1+0'EN'" '" '" !" !" !" !"!(* !% 3 F F} U UI**,,,#'#B#B!;$ $      F  3&@H  - % %$ U* * * * * * * * * * * * * *)::OT%6  ) )* * * * * * * * * * * * * * * * * * * * * * * * * * *V g23 	 	 	K000000000000FF 	 	 	,,Q/////////	
 KK,,,,,,,,,,,,,,s\   I> "AI,=G CI, I> 3&I,I> ,
I66I> 9I6:I> >4K5	K>KKnext_step_output1Union[AgentFinish, List[Tuple[AgentAction, str]]]r   c                   t                               d           t          |t                    r1t                               d           |                     ||          S | j                            |           t                               d           t          |          dk    r;|d         }| 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ra   +Updated intermediate_steps with step outputr]   r   Nrp   )rU   rV   rw   r   _returnrW   extendlenr'   _get_tool_returnr   r2   r   ra   next_step_actiontool_returns        r3   ry   z/AgentExecutorIterator._process_next_step_output8  s     	;<<<&44 	KLLT   << 0k<JJJ&&'7888BCCC   A%%/2->>?OPPK&||K[|III-=>>>>r5   r   c                  K   t                               d           t          |t                    r7t                               d           |                     ||           d{V S | j                            |           t                               d           t          |          dk    rA|d         }| j        	                    |          }||                     ||           d{V S t          |          S )	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   r]   r   r   )rU   rV   rw   r   _areturnrW   r   r   r'   r   r   r   s        r3   r   z0AgentExecutorIterator._aprocess_next_step_outputT  s      	ABBB&44 	RLLU   '7[QQQQQQQQQ&&'7888BCCC   A%%/2->>?OPPK&!]];K]PPPPPPPPP-=>>>>r5   c                    t                               d            | j        j        j        | j        j        | j        fi | j        }|                     ||          S )zb
        Stop the iterator and raise a StopIteration exception with the stopped response.
        ;Stopping agent prematurely due to triggering stop conditionr   )	rU   warningr'   _action_agentreturn_stopped_responseearly_stopping_methodrW   r(   r   r2   ra   r   s      r3   r|   zAgentExecutorIterator._stopp  si     	TUUUJ$2J5#
 
 k
 

 ||F|<<<r5   c                   K   t                               d            | j        j        j        | j        j        | j        fi | j        }|                     ||           d{V S )zu
        Stop the async iterator and raise a StopAsyncIteration exception with
        the stopped response.
        r   r   N)	rU   r   r'   r   r   r   rW   r(   r   r   s      r3   r   zAgentExecutorIterator._astop}  s      
 	TUUUJ$2J5#
 
 k
 

 ]]6{]CCCCCCCCCr5   r   r   c                    | j                             || j        |          }|j        |d<   |                    |           |                     ||          S )z:
        Return the final output of the iterator.
        r   rm   )r'   r   rW   rm   on_chain_endrg   r2   r   ra   returned_outputs       r3   r   zAgentExecutorIterator._return  sc     -55D+ 6 
 
 '-o
#  111&&DDDr5   c                   K   | j                             || j        |           d{V }|j        |d<   |                    |           d{V  |                     ||          S )z@
        Return the final output of the async iterator.
        r   Nrm   )r'   r   rW   rm   r   rg   r   s       r3   r   zAgentExecutorIterator._areturn  s       !% 3 < <D+ != !
 !
 
 
 
 
 
 
 '-o
#&&777777777&&DDDr5   r=   )r'   r   r(   r   r)   r   r!   r*   r"   r+   r#   r,   r$   r-   r%   r.   r&   r.   )r8   r6   )r(   r   r8   r;   )r8   r   )r'   r   r8   r;   )r8   rA   )r8   r;   )r_   r`   ra   rb   r8   r   )r2   rh   r8   ri   )r8   r   )r   r   ra   r   r8   r   )r   r   ra   r   r8   r   )ra   r   r8   r   )ra   r   r8   r   )r   r   ra   r   r8   r   )r   r   ra   r   r8   r   )__name__
__module____qualname____doc__r4   __annotations__propertyr(   setterr'   rL   rS   r1   r^   rg   r   r   ry   r   r|   r   r   r   rD   r5   r3   r    r    .   ss        %%  $	* %)-1"&!%!&#* * * * * *X &&&&   X ]? ? ? ]? $ $ $ X$ " " " "
 G G G XG 
 
 
 X

& 
& 
& 
&
 
 
 
       "<& <& <& <&|J- J- J- J-X? ? ? ?8? ? ? ?8= = = =D D D DE E E EE E E E E Er5   r    )0
__future__r   r   loggingrZ   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   rU   r    rD   r5   r3   <module>r      s%   " " " " " "   
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
               
              + * * * * * * * * * * * 6 6 6 6 6 6 ) ) ) ) ) ) 8 8 8 8 8 8 $ $ $ $ $ $ 7 7 7 7 7 7 EDDDDDDDD		8	$	$tE tE tE tE tE tE tE tE tE tEr5   