a
    •˜ëjÛC  ã                   @  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 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 *e+¡Z,G dd„ dƒZ-dS )é    )Ú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                   @  sª  e Zd ZU dZdLd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d d2d3œd4d5„Zd6dœd7d8„Zd9d:d.d;œd<d=„Zd9d>d.d;œd?d@„Zd:d.dAœdBdC„Zd>d.dAœdDdE„ZdFd:d.dGœdHdI„ZdFd>d.dGœdJdK„ZdS )MÚ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 )aQ  Initialize the AgentExecutorIterator.

        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)   ú^/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/langchain/agents/agent_iterator.pyÚ__init__-   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$   c   s    zAgentExecutorIterator.inputsÚNone)r$   r-   c                 C  s   | j  |¡| _d S ©N)r#   Zprep_inputsr,   )r(   r$   r)   r)   r*   r$   h   s    c                 C  s   | j S )z"The AgentExecutor to iterate over.)r&   r.   r)   r)   r*   r#   l   s    z$AgentExecutorIterator.agent_executor)r#   r-   c                 C  s   || _ | j| _d S r0   )r&   r$   )r(   r#   r)   r)   r*   r#   q   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   ó    z:AgentExecutorIterator.name_to_tool_map.<locals>.<dictcomp>)r#   Útoolsr.   r)   r)   r*   Úname_to_tool_mapw   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)   r1   r3   r)   r)   r*   Ú
<listcomp>€   r6   z7AgentExecutorIterator.color_mapping.<locals>.<listcomp>ZgreenZred)Zexcluded_colors)r   r#   r7   r.   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.

        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.   r)   r)   r*   r'   „   s
    
zAgentExecutorIterator.resetc                 C  s4   |  j d7  _ t ¡ | j | _t d| j | j¡ dS )z?Increment the number of iterations and update the time elapsed.é   z$Agent Iterations: %s (%.2fs elapsed)N)r>   r@   rA   r?   r;   r<   r.   r)   r)   r*   Úupdate_iterations‘   s    ýz'AgentExecutorIterator.update_iterationszdict[str, Any]zBUnion[CallbackManagerForChainRun, AsyncCallbackManagerForChainRun]r   )ÚoutputsÚrun_managerr-   c                 C  s2   t | jj| j|dd�ƒ}| jr.t|jd�|t< |S )zµMake final outputs for the iterator.

        Args:
            outputs: The outputs from the agent executor.
            run_manager: The run manager to use for callbacks.
        T)Zreturn_only_outputs)r   )r   r#   Zprep_outputsr$   r    r   r   r   )r(   rD   rE   Zprepared_outputsr)   r)   r*   Úmake_final_outputs›   s    ýÿz(AgentExecutorIterator.make_final_outputszIterator[AddableDict])r(   r-   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r’t|tƒrÄt|g|jd�V  q’t|tƒr’t|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 )z/Create an async iterator for the AgentExecutor.z"Initialising AgentExecutorIteratorr1   ©ÚactionsÚmessages©ZstepsrI   Úintermediate_stepN)#r;   r<   r'   r   Ú	configurer%   r#   Úverboser   r   Úon_chain_startr   r$   r   r   Ú_should_continuer>   r?   Z_iter_next_stepr8   r:   r=   Úappendr!   Ú
isinstancer
   r   rI   r   Ú_consume_next_steprC   Ú_process_next_step_outputÚBaseExceptionÚon_chain_errorÚ_stop©	r(   Zcallback_managerrE   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r²t|tƒrìt|g|jd�V  q²t|tƒr²t|g|jd�V  q²6 | 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  �qš1 I dH �s�0    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ÈCreate an async iterator for the AgentExecutor.

        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)r1   NrG   rJ   rK   )'r;   r<   r'   r   rL   r%   r#   rM   r   r   rN   r   r$   r   r   r   Zmax_execution_timerO   r>   r?   Z_aiter_next_stepr8   r:   r=   rP   r!   rQ   r
   r   rI   r   rR   rC   Ú_aprocess_next_step_outputÚTimeoutErrorÚasyncioÚ_astoprT   rU   rW   r)   r)   r*   Ú	__aiter__ô   sz    
ù	üþû

þ

þþ
LzAgentExecutorIterator.__aiter__z1Union[AgentFinish, list[tuple[AgentAction, str]]]r   )Únext_step_outputrE   r-   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 )	z�Process the output of the next step.

        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©rE   ú+Updated intermediate_steps with step outputrB   r   N©rK   )r;   r<   rQ   r   Ú_returnr=   ÚextendÚlenr#   Ú_get_tool_returnr   ©r(   rb   rE   Znext_step_actionZtool_returnr)   r)   r*   rS   E  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 )	z›Process the output of the next async step.

        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 logicrc   Nrd   rB   r   re   )r;   r<   rQ   r   Ú_areturnr=   rg   rh   r#   ri   r   rj   r)   r)   r*   r]   b  s    


ÿ
z0AgentExecutorIterator._aprocess_next_step_output)rE   r-   c                 C  s8   t  d¡ | jjj| jj| jfi | j¤Ž}| j||d�S )zuStop the iterator.

        Stop the iterator and raise a StopIteration exception with the stopped response.
        ú;Stopping agent prematurely due to triggering stop conditionrc   )	r;   Úwarningr#   Ú_action_agentÚreturn_stopped_responseÚearly_stopping_methodr=   r$   rf   ©r(   rE   rY   r)   r)   r*   rV     s    
þýzAgentExecutorIterator._stopc                 Ã  s>   t  d¡ | jjj| jj| jfi | j¤Ž}| j||d�I dH S )zŽStop the async iterator.

        Stop the async iterator and raise a StopAsyncIteration exception with
        the stopped response.
        rl   rc   N)	r;   rm   r#   rn   ro   rp   r=   r$   rk   rq   r)   r)   r*   r`   �  s    
þýzAgentExecutorIterator._astopr   )rY   rE   r-   c                 C  s4   | j j|| j|d�}|j|d< | |¡ |  ||¡S )z(Return the final output of the iterator.rc   rI   )r#   rf   r=   rI   Úon_chain_endrF   ©r(   rY   rE   Zreturned_outputr)   r)   r*   rf   ›  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.rc   NrI   )r#   rk   r=   rI   rr   rF   rs   r)   r)   r*   rk   ª  s    ý
zAgentExecutorIterator._areturn)N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r+   Ú__annotations__Úpropertyr$   Úsetterr#   r8   r:   r'   rC   rF   r\   ra   rS   r]   rV   r`   rf   rk   r)   r)   r)   r*   r   *   sR   
 üõ"-
@Qr   ).Ú
__future__r   r_   Úloggingr@   Úcollections.abcr   r   Útypingr   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   Ú	getLoggerrt   r;   r   r)   r)   r)   r*   Ú<module>   s&   
