a
    agF@                     @  s  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rd dl)m*Z*m+Z+ e,e-Z.G d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                   @  s  e Zd ZU dZdMddddddddd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ddZejdddddZedddd Z	e	jddd!d"d Z	ed#dd$d%Z
eddd&d'Zddd(d)Zddd*d+Zd,d-d.d/d0d1Zd2d3d4d5d6Zd7dd8d9Zd:d;d.d<d=d>Zd:d?d.d<d@dAZd;d.dBdCdDZd?d.dBdEdFZdGd;d.dHdIdJZdGd?d.dHdKdLZdS )NAgentExecutorIteratorzIterator for AgentExecutor.NF)tagsmetadatarun_namerun_idinclude_run_infoyield_actionsr   r   r   zOptional[list[str]]zOptional[Dict[str, Any]]zOptional[str]zOptional[UUID]bool)	agent_executorinputs	callbacksr   r    r!   r"   r#   r$   c          
      C  sB   || _ || _|| _|| _|| _|| _|| _|| _|	| _| 	  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$    r,   m/var/www/html/cobodadashboardai.evdpl.com/venv/lib/python3.9/site-packages/langchain/agents/agent_iterator.py__init__1   s    !zAgentExecutorIterator.__init__zDict[str, str]_inputsr(   r   r    r!   r"   r#   r$   )returnc                 C  s   | j S )z The inputs to the AgentExecutor.)r/   r+   r,   r,   r-   r'   f   s    zAgentExecutorIterator.inputsNone)r'   r0   c                 C  s   | j || _d S N)r&   Zprep_inputsr/   )r+   r'   r,   r,   r-   r'   k   s    c                 C  s   | j S )z"The AgentExecutor to iterate over.)r)   r1   r,   r,   r-   r&   o   s    z$AgentExecutorIterator.agent_executor)r&   r0   c                 C  s   || _ | j| _d S r3   )r)   r'   )r+   r&   r,   r,   r-   r&   t   s    zDict[str, BaseTool]c                 C  s   dd | j jD S )z!A mapping of tool names to tools.c                 S  s   i | ]}|j |qS r,   name.0Ztoolr,   r,   r-   
<dictcomp>}       z:AgentExecutorIterator.name_to_tool_map.<locals>.<dictcomp>)r&   toolsr1   r,   r,   r-   name_to_tool_mapz   s    z&AgentExecutorIterator.name_to_tool_mapc                 C  s   t dd | jjD ddgdS )z"A mapping of tool names to colors.c                 S  s   g | ]
}|j qS r,   r4   r6   r,   r,   r-   
<listcomp>   r9   z7AgentExecutorIterator.color_mapping.<locals>.<listcomp>greenred)Zexcluded_colors)r   r&   r:   r1   r,   r,   r-   color_mapping   s    z#AgentExecutorIterator.color_mappingc                 C  s*   t d g | _d| _d| _t | _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_timer1   r,   r,   r-   r*      s
    
zAgentExecutorIterator.resetc                 C  s@   |  j d7  _ t | j | _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)rC   rE   rF   rD   r@   rA   r1   r,   r,   r-   update_iterations   s
    z'AgentExecutorIterator.update_iterationszDict[str, Any]zBUnion[CallbackManagerForChainRun, AsyncCallbackManagerForChainRun]r   )outputsrun_managerr0   c                 C  s2   t | jj| j|dd}| jr.t|jd|t< |S )NT)Zreturn_only_outputs)r"   )r   r&   Zprep_outputsr'   r#   r   r"   r   )r+   rI   rJ   Zprepared_outputsr,   r,   r-   make_final_outputs   s    z(AgentExecutorIterator.make_final_outputsz'AgentExecutorIterator'zIterator[AddableDict])r+   r0   c           	   
   c  sp  t d |   t| j| jj| jj| j| jj| j	| jj	}|j
t| j| j| j| jd}z| j| j| jr*g }| j| j| j| j| j|D ]N}|| | jrt|trt|g|jdV  qt|trt|g|jdV  q| j|}|   | ||}d|v}| jr|r|V  |r^W d S q^W n2 t y^ } z|!|  W Y d }~n
d }~0 0 | "|V  d S )Nz"Initialising AgentExecutorIteratorr4   actionsmessagesZstepsrN   intermediate_step)#r@   rA   r*   r   	configurer(   r&   verboser   r    on_chain_startr   r'   r"   r!   _should_continuerC   rD   Z_iter_next_stepr;   r?   rB   appendr$   
isinstancer   r   rN   r   _consume_next_steprH   _process_next_step_outputBaseExceptionon_chain_error_stop	r+   Zcallback_managerrJ   Znext_step_seqchunkZ	next_stepoutputis_finaler,   r,   r-   __iter__   s^    
	



zAgentExecutorIterator.__iter__zAsyncIterator[AddableDict]c           	   
   C s  t d |   t| j| jj| jj| j| jj| j	| jj	}|j
t| j| j| j| jdI dH }z8t| jj4 I dH  | j| j| jrlg }| j| j| j| j| j|2 zV3 dH W }|| | jrt|trt|g|jdV  qt|trt|g|jdV  q6 | j|}|    | !||I dH }d|v}| jrH|rN|V  |r~W d  I dH  W dS q~W d  I dH  q1 I dH s0    Y  W nd t"t#j"fy   | $|I dH V  Y dS  t%y  } z|&|I dH   W Y d}~n
d}~0 0 | $|I dH 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)r4   NrL   rO   rP   )'r@   rA   r*   r   rQ   r(   r&   rR   r   r    rS   r   r'   r"   r!   r   Zmax_execution_timerT   rC   rD   Z_aiter_next_stepr;   r?   rB   rU   r$   rV   r   r   rN   r   rW   rH   _aprocess_next_step_outputTimeoutErrorasyncio_astoprY   rZ   r\   r,   r,   r-   	__aiter__   sr    
	




LzAgentExecutorIterator.__aiter__z1Union[AgentFinish, List[Tuple[AgentAction, str]]]r   )next_step_outputrJ   r0   c                 C  s   t d t|tr,t d | j||dS | j| t d t|dkrx|d }| j	|}|durx| j||dS t
|d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rJ   +Updated intermediate_steps with step outputrG   r   NrP   )r@   rA   rV   r   _returnrB   extendlenr&   _get_tool_returnr   r+   rg   rJ   Znext_step_actionZtool_returnr,   r,   r-   rX   8  s    	


z/AgentExecutorIterator._process_next_step_outputr   c                   s   t d t|tr2t d | j||dI dH S | j| t d t|dkr|d }| j	|}|dur| j||dI dH S t
|d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 logicrh   Nri   rG   r   rj   )r@   rA   rV   r   _areturnrB   rl   rm   r&   rn   r   ro   r,   r,   r-   rb   T  s    	


z0AgentExecutorIterator._aprocess_next_step_output)rJ   r0   c                 C  s8   t d | jjj| jj| jfi | j}| j||dS )zb
        Stop the iterator and raise a StopIteration exception with the stopped response.
        ;Stopping agent prematurely due to triggering stop conditionrh   )	r@   warningr&   _action_agentreturn_stopped_responseearly_stopping_methodrB   r'   rk   r+   rJ   r^   r,   r,   r-   r[   p  s    
zAgentExecutorIterator._stopc                   s>   t d | jjj| jj| jfi | j}| j||dI dH S )zu
        Stop the async iterator and raise a StopAsyncIteration exception with
        the stopped response.
        rq   rh   N)	r@   rr   r&   rs   rt   ru   rB   r'   rp   rv   r,   r,   r-   re   }  s    
zAgentExecutorIterator._astopr   )r^   rJ   r0   c                 C  s4   | j j|| j|d}|j|d< || | ||S )z:
        Return the final output of the iterator.
        rh   rN   )r&   rk   rB   rN   on_chain_endrK   r+   r^   rJ   Zreturned_outputr,   r,   r-   rk     s    

zAgentExecutorIterator._returnc                   s@   | j j|| j|dI dH }|j|d< ||I dH  | ||S )z@
        Return the final output of the async iterator.
        rh   NrN   )r&   rp   rB   rN   rw   rK   rx   r,   r,   r-   rp     s    
zAgentExecutorIterator._areturn)N)__name__
__module____qualname____doc__r.   __annotations__propertyr'   setterr&   r;   r?   r*   rH   rK   ra   rf   rX   rb   r[   re   rk   rp   r,   r,   r,   r-   r   .   sR   
 ",
>Lr   )0
__future__r   rd   loggingrE   typingr   r   r   r   r   r   r	   r
   r   uuidr   Zlangchain_core.agentsr   r   r   Zlangchain_core.callbacksr   r   r   r   r   Zlangchain_core.load.dumpr   Zlangchain_core.outputsr   Zlangchain_core.runnables.utilsr   Zlangchain_core.toolsr   Zlangchain_core.utils.inputr   Zlangchain.schemar   Zlangchain.utilities.asyncior   Zlangchain.agents.agentr   r   	getLoggerry   r@   r   r,   r,   r,   r-   <module>   s$   ,
