o
    h                  
   @   s:  d dl 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 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mZ dd
lmZmZmZ ddlmZmZ ddlmZ ddl m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z* ddl+m,Z,m-Z- ddl.m/Z/m0Z0m1Z1m2Z2 e rd dl3m4Z4 d dl5m6Z6 d dl7m8Z8 G dd dej9Z:e;e<Z=de=_>e? Z@e@Ae:  e=Be@ deCdeeCeCf fddZDdeCdeCfddZEdeCde
eCeeCeCf f fddZFdeCde
eCeeCeeCeCf f f fd d!ZGd"eeeeCeCf  eeCeCf eCf deCfd#d$ZHi aIdaJG d%d& d&ZKG d'd( d(eLZMG d)d* d*eMZNG d+d, d,eMZOG d-d. d.eMZPG d/d0 d0eMZQd1eKd2eCd3eCdeCfd4d5ZRd6eSfd7d8ZTdKdeCfd9d:ZUd2eCd;eeC deCfd<d=ZVG d>d? d?ZWG d@dA dAeWZXG dBdC dCeWZYG dDdE dEeYZZG dFdG dGeYZ[dHZ\G dIdJ dJZ]dS )L    N)AnyCallableDictListOptionalTupleUnion)_deprecate_method   )is_torch_available)logging)is_pygments_available   )
AgentAudio
AgentImage)BASE_PYTHON_TOOLSFinalAnswerToolsetup_default_tools)HfApiEngineMessageRole)Monitor)
DEFAULT_CODE_SYSTEM_PROMPT DEFAULT_REACT_CODE_SYSTEM_PROMPT DEFAULT_REACT_JSON_SYSTEM_PROMPT PLAN_UPDATE_FINAL_PLAN_REDACTIONPROMPTS_FOR_INITIAL_PLANPROMPTS_FOR_PLAN_UPDATESUPPORTED_PLAN_TYPESSYSTEM_PROMPT_FACTSSYSTEM_PROMPT_FACTS_UPDATEUSER_PROMPT_FACTS_UPDATE)LIST_SAFE_MODULESevaluate_python_code)!DEFAULT_TOOL_DESCRIPTION_TEMPLATEToolget_tool_description_with_args	load_tool)	highlight)Terminal256Formatter)PythonLexerc                   @   s   e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZejee e ejeejee e ejee e ejee e dee e dee e dee e de	e e de
e e dee e iZdd ZdS )CustomFormatterz[38;20mz[33;1mz[31;20mz[32;20mz
[32;20;1mz[31;1mz[37;1mz[38;5;214mz[38;5;214;1mz[0mz%(message)s       !   "   #   $   c                 C   s"   | j |j}t|}||S N)FORMATSgetlevelnor   	Formatterformat)selfrecordlog_fmt	formatter r;   n/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/transformers/agents/agents.pyr6   V   s   

zCustomFormatter.formatN)__name__
__module____qualname__greybold_yellowredgreen
bold_greenbold_red
bold_whiteorangebold_orangeresetr6   r   DEBUGINFOWARNINGERRORCRITICALr2   r;   r;   r;   r<   r*   ;   s2    r*   F	json_blobreturnc                 C   s   z*|  d}dd ttd| D d }| ||d  dd} tj| d	d
}|W S  tjy` } z)|j}| |d |d  dkrFt	dt	d| d|  d| |d |d   dd }~w t
yr } zt	d| d }~ww )N{c                 S   s   g | ]}|  qS r;   )start).0ar;   r;   r<   
<listcomp>f       z#parse_json_blob.<locals>.<listcomp>}r   z\"'F)strictr
   z},
zmJSON is invalid: you probably tried to provide multiple tool calls in one action. PROVIDE ONLY ONE TOOL CALL.z>The JSON blob you used is invalid due to the following error: z.
JSON blob was: z6, decoding failed on that specific part of the blob:
'      '.z Error in parsing the JSON blob: )findlistrefinditerreplacejsonloadsJSONDecodeErrorpos
ValueError	Exception)rO   first_accolade_indexlast_accolade_index	json_dataeplacer;   r;   r<   parse_json_blobc   s0   
rn   	code_blobc              
   C   sT   zd}t || t j}|d W S  ty) } ztd| d| dd }~ww )Nz```(?:py|python)?\n(.*?)\n```r   z@
The code blob you used is invalid: due to the following error: z#
This means that the regex pattern z was not respected: make sure to include code with the correct pattern, for instance:
Thoughts: Your thoughts
Code:
```py
# Your python code here
```<end_action>)r`   searchDOTALLgroupstriprh   rg   )ro   patternmatchrl   r;   r;   r<   parse_code_bloby   s   rv   c                    sr   |  dd dd} t|  d v rd v r d  d fS d v r( d d fS td fddd	D  d
  )Nz```json z```actionaction_inputzMissing keys: c                    s   g | ]}| vr|qS r;   r;   )rS   key	tool_callr;   r<   rU          z(parse_json_tool_call.<locals>.<listcomp>)rx   ry   z	 in blob )rb   rn   rg   )rO   r;   r{   r<   parse_json_tool_call   s   r~   textc              
   C   s   z=d| v r|  dd } d| v r|  dd } |  d\}}d|v r't|}n| dd}| ddd	d|fW S  tyQ } ztd
| dd}~ww )z
    Expects a text in the format: 'Action:', 'Action input:', 'Observation:'. 'Action input:' contains a json string with input arguments.
    Observation:r   Action:r   zAction input:rQ   "rw   \z%Error in parsing the text tool call: zY. Be sure to provide the correct format. DO NOT repeat your previous incorrect tool call.N)splitrn   rs   rb   rh   rg   )r   	tool_name
tool_inputrl   r;   r;   r<   parse_text_tool_call   s    

r   inputc                 C   s4   t | trddd | D S t | tr| d S | S )N
c                 S   s   g | ]}|d  qS )contentr;   )rS   mr;   r;   r<   rU      rV   zto_text.<locals>.<listcomp>r   )
isinstancer_   joindict)r   r;   r;   r<   to_text   s
   

r   c                   @   s   e Zd ZdZddee defddZddefdd	Ze	d
e
eef fddZd dee d
efddZdefddZdefddZdefddZdd Zdd Zdd ZdS )!Toolboxa  
    The toolbox contains all tools that the agent can perform operations with, as well as a few methods to
    manage them.

    Args:
        tools (`List[Tool]`):
            The list of tools to instantiate the toolbox with
        add_base_tools (`bool`, defaults to `False`, *optional*, defaults to `False`):
            Whether to add the tools available within `transformers` to the toolbox.
    Ftoolsadd_base_toolsc                 C   s(   dd |D | _ |r|   |   d S )Nc                 S      i | ]}|j |qS r;   namerS   toolr;   r;   r<   
<dictcomp>   rV   z$Toolbox.__init__.<locals>.<dictcomp>)_toolsr   _load_tools_if_needed)r7   r   r   r;   r;   r<   __init__   s   zToolbox.__init__add_python_interpreterc                 C   sB   t sttada t D ]}|jdks|r| | q|   d S )NTpython_interpreter)_tools_are_initializedr   loggerHUGGINGFACE_DEFAULT_TOOLSvaluesr   add_toolr   )r7   r   r   r;   r;   r<   r      s   
zToolbox.add_base_toolsrP   c                 C      | j S )z&Get all tools currently in the toolboxr   r7   r;   r;   r<   r         zToolbox.toolsNtool_description_templatec                    s   d  fdd| j D S )z
        Returns the description of all tools in the toolbox

        Args:
            tool_description_template (`str`, *optional*):
                The template to use to describe the tools. If not provided, the default template will be used.
        r   c                    s   g | ]}t | qS r;   )r%   r   r   r;   r<   rU      s    z2Toolbox.show_tool_descriptions.<locals>.<listcomp>)r   r   r   )r7   r   r;   r   r<   show_tool_descriptions   s   zToolbox.show_tool_descriptionsr   c                 C   s.   |j | jv rtd|j  d|| j|j < dS )z
        Adds a tool to the toolbox

        Args:
            tool (`Tool`):
                The tool to add to the toolbox.
        zError: tool 'z ' already exists in the toolbox.N)r   r   KeyErrorr7   r   r;   r;   r<   r      s   zToolbox.add_toolr   c                 C   s6   || j vrtd| dt| j   d| j |= dS )z
        Removes a tool from the toolbox

        Args:
            tool_name (`str`):
                The tool to remove from the toolbox.
        Error: tool z< not found in toolbox for removal, should be instead one of .N)r   r   r_   keys)r7   r   r;   r;   r<   remove_tool   s
   
zToolbox.remove_toolc                 C   s>   |j | jvrtd|j  dt| j  d|| j|j < dS )z
        Updates a tool in the toolbox according to its name.

        Args:
            tool (`Tool`):
                The tool to update to the toolbox.
        r   z; not found in toolbox for update, should be instead one of r   N)r   r   r   r_   r   r   r;   r;   r<   update_tool  s
   zToolbox.update_toolc                 C   s
   i | _ dS )zClears the toolboxNr   r   r;   r;   r<   clear_toolbox  s   
zToolbox.clear_toolboxc                 C   sF   | j  D ]\}}t|ts |jd u r|jn|j}t|| j |< qd S r1   )r   itemsr   r$   repo_idtaskr&   )r7   r   r   task_or_repo_idr;   r;   r<   r     s   
zToolbox._load_tools_if_neededc                 C   s2   d}| j  D ]}|d|j d|j d7 }q|S )NzToolbox contents:
	: r   )r   r   r   description)r7   toolbox_descriptionr   r;   r;   r<   __repr__  s   zToolbox.__repr__Fr1   )r=   r>   r?   __doc__r   r$   boolr   r   propertyr   strr   r   r   r   r   r   r   r   r   r;   r;   r;   r<   r      s    r   c                       s    e Zd ZdZ fddZ  ZS )
AgentErrorz-Base class for other agent-related exceptionsc                    s   t  | || _d S r1   )superr   message)r7   r   	__class__r;   r<   r   $  s   
zAgentError.__init__)r=   r>   r?   r   r   __classcell__r;   r;   r   r<   r   !  s    r   c                   @      e Zd ZdZdS )AgentParsingErrorz3Exception raised for errors in parsing in the agentNr=   r>   r?   r   r;   r;   r;   r<   r   )      r   c                   @   r   )AgentExecutionError5Exception raised for errors in execution in the agentNr   r;   r;   r;   r<   r   /  r   r   c                   @   r   )AgentMaxIterationsErrorr   Nr   r;   r;   r;   r<   r   5  r   r   c                   @   r   )AgentGenerationErrorz6Exception raised for errors in generation in the agentNr   r;   r;   r;   r<   r   ;  r   r   toolboxprompt_templater   c                 C   sH   |  |}|d|}d|v r"dd | j D }|dd|}|S )Nz<<tool_descriptions>>z<<tool_names>>c                 S   s   g | ]}d | d qS )rY   r;   )rS   r   r;   r;   r<   rU   F  r}   z,format_prompt_with_tools.<locals>.<listcomp>z, )r   rb   r   r   r   )r   r   r   tool_descriptionsprompt
tool_namesr;   r;   r<   format_prompt_with_toolsA  s   
r   managed_agentsc                 C   s.   d}|   D ]}|d|j d|j 7 }q|S )Na_  
You can also give requests to team members.
Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'request', a long string explaining your request.
Given that this team member is a real human, you should be very verbose in your request.
Here is a list of the team members that you can call:z
- r   )r   r   r   )r   managed_agents_descriptionsagentr;   r;   r<   show_agents_descriptionsL  s   r   c                 C   s$   |d ur|  dt|S |  ddS )Nz<<managed_agents_descriptions>>rw   )rb   r   )r   r   r;   r;   r<   .format_prompt_with_managed_agents_descriptionsW  s   r   authorized_importsc                 C   s    d| vrt d| dt|S )N<<authorized_imports>>z>Tag '<<authorized_imports>>' should be provided in the prompt.)r   rb   r   )r   r   r;   r;   r<   format_prompt_with_imports^  s   r   c                   @   s,  e Zd Zdddi ddddddddfdeee ef dedee	 d	ee	 d
e
dedee dededee
e	e	f  dee deee  defddZedefddZdd Zd-dee dee
e	e	f  fddZdd Zde	d e	de	fd!d"Zd#e	d$e
e	e	f defd%d&Zd'e	d(e	ddfd)d*Zd+d, ZdS ).AgentN   Fr   Tr   
llm_enginesystem_promptr   additional_argsmax_iterationstool_parserr   verbosegrammarr   step_callbacksmonitor_metricsc                 C   s  |d u rt }|d u rt}| jj| _|| _|| _|r|nt| _|| _	|| _
t| _|| _|
| _d | _|d ur<dd |D | _t|trX|| _|rWt sMtd| jj| jtkd nt||d| _| jt  t| j| j| j| _t| j| j| _d | _g | _d | _|	dkrttj  n|	dkrttj! n
|	dkrttj" |d ur|ng | _#d | _$|rt%| j| _$| j#&| j$j' d S d S )	Nc                 S   r   r;   r   )rS   r   r;   r;   r<   r     rV   z"Agent.__init__.<locals>.<dictcomp>z4Using the base tools requires torch to be installed.)r   )r   r   r   r
   )(r   r~   r   r=   
agent_namer   system_prompt_templater#   r   r   r   r   r   r   r   r   r   _toolboxr   ImportErrorr   ReactJsonAgentr   r   r   r   r   r   logsr   setLevelr   rL   rK   rJ   r   monitorr   appendupdate_metrics)r7   r   r   r   r   r   r   r   r   r   r   r   r   r   r;   r;   r<   r   e  sZ   


zAgent.__init__rP   c                 C   r   )z0Get the toolbox currently available to the agent)r   r   r;   r;   r<   r     r   zAgent.toolboxc                 C   s   d| _ t| j| j| j| _t| j| j| _t| dr*t	| jt
ttt| jB | _| j| jdg| _| jdd | jd| j | jd | j| j d S )Nr   r   )r   r   r-   z======== New task ========r.   zSystem prompt is as follows:)token_countr   r   r   r   r   r   r   hasattrr   r_   setr!   r   r   r   r   logdebugr   r;   r;   r<   initialize_for_run  s    
zAgent.initialize_for_runsummary_modec                 C   s  t j| jd d d}t jd| jd d  d}|r|g}n||g}t| jdd D ]\}}d|v rD|sDt j|d  d}|| d	|v rYt jd
|d	   d}|| d|v rp|spt jd|d   d}|| d|v r|rt jd| dt|d   d}|| d|v rt jd|d  d}|| d|v sd|v rd|v rd| dt|d  d }	nd|v rd| d|d  }	t j	|	d}
||
 q+|S )z
        Reads past llm_outputs, actions, and observations or errors from the logs into a series of messages
        that can be used as input to the LLM.
        r   r   roler   Task: r   r   N
llm_outputfactsz[FACTS LIST]:
planz[PLAN]:
r|   z[STEP z TOOL CALL]: z
New task:
errorobservationz[OUTPUT OF STEP z] -> Error:
z
Now let's retry: take care not to repeat previous errors! If you have retried several times, try a completely different approach.
z] -> Observation:
)
r   SYSTEMr   USER	enumerate	ASSISTANTrs   r   r   TOOL_RESPONSE)r7   r   prompt_messagetask_messagememoryistep_logthought_messagetool_call_messagemessage_contenttool_response_messager;   r;   r<   write_inner_memory_from_logs  sV   








z"Agent.write_inner_memory_from_logsc                 C   s   dd | j D S )Nc                 S   s   g | ]}d d |  D qS )c                 S   s   i | ]\}}|d kr||qS )agent_memoryr;   )rS   rz   valuer;   r;   r<   r         z6Agent.get_succinct_logs.<locals>.<listcomp>.<dictcomp>)r   )rS   r   r;   r;   r<   rU     r  z+Agent.get_succinct_logs.<locals>.<listcomp>)r   r   r;   r;   r<   get_succinct_logs  s   zAgent.get_succinct_logsr   split_tokenc                 C   sv   z| |}|d |d }}W n" ty2 } z| jj|dd td| d| d| dd	}~ww | | fS )
z
        Parse action from the LLM output

        Args:
            llm_output (`str`): Output of the LLM
            split_token (`str`): Separator for the action. Should match the example in the system prompt.
        rX   r   exc_infozError: No 'z.' token provided in your output.
Your output:
z0
. Be sure to include an action, prefaced with 'z'!N)r   rh   r   r   r   rs   )r7   r   r  r   	rationalerx   rl   r;   r;   r<   extract_action  s   

zAgent.extract_actionr   	argumentsc           	   
   C   sR  | j j}| jduri || j}||vr-d| dt|  d}| jj|dd t|zCt|t	r<|| |}|W S t|t
rg| D ]\}}t|t	rZ|| jv rZ| j| ||< qE|| di |}|W S tdt| d ty } z,|| j jv rtd| d	t||  || jv rtd
| d||  W Y d}~dS d}~ww )ap  
        Execute tool with the provided input and returns the result.
        This method replaces arguments with the actual values from the state if they refer to state variables.

        Args:
            tool_name (`str`): Name of the Tool to execute (should be one from self.toolbox).
            arguments (Dict[str, str]): Arguments passed to the Tool.
        NzError: unknown tool z, should be instead one of r   r   r  z;Arguments passed to tool should be a dict or string: got a zError in tool call execution: zn
You should only use this tool with a correct input.
As a reminder, this tool's description is the following:
zError in calling team member: z~
You should only ask this team member with a correct request.
As a reminder, this team member's description is the following:
r;   )r   r   r   r_   r   r   r   r   r   r   r   r   statetyperh   r%   )	r7   r   r  available_tools	error_msgr   rz   r  rl   r;   r;   r<   execute_tool_call  sJ   	




zAgent.execute_tool_callr  code_actionc              	   C   sn   | j d | j d| | j d t r(| j dt|tddtdd n| j d| | j d d S )	N=== Agent thoughts:r+   z&>>> Agent is executing the code below:F)ensurenlnord)stylez====)r   warningr   r   r'   r)   r(   )r7   r  r  r;   r;   r<   log_rationale_code_action?  s   zAgent.log_rationale_code_actionc                 K   s   t )z$To be implemented in the child class)NotImplementedError)r7   kwargsr;   r;   r<   runK  s   z	Agent.runr   )r=   r>   r?   r   r   r$   r   r   r   r   r   intr   r   r   r   r   r  r  r  r   r  r%  r(  r;   r;   r;   r<   r   d  sb    	


G$9+r   c                       s   e Zd ZdZ					ddee dee dee dee dee	eef  deee  f fd	d
Z
dedefddZddedefddZ  ZS )	CodeAgentz
    A class for an agent that solves the given task using a single block of code. It plans all its actions, then executes all in one shot.
    Nr   r   r   r   r   additional_authorized_importsc                    s   |d u rt  }|d u rt}|d u rt}t jd|||||d| t s+ttd t	| _
|r2|ng | _tttt| jB | _| jdt| j| _d S )Nr   r   r   r   r   zepygments isn't installed. Installing pygments will enable color syntax highlighting in the CodeAgent.r   r;   )r   r   r#   r   r   r   transformers_loggingwarning_oncer   r"   python_evaluatorr+  r_   r   r!   r   r   rb   r   )r7   r   r   r   r   r   r+  r'  r   r;   r<   r   U  s0   
	zCodeAgent.__init__resultrP   c                 C   s   t |S )zu
        Override this method if you want to change the way the code is
        cleaned in the `run` method.
        )rv   )r7   r0  r;   r;   r<   rv   z  s   zCodeAgent.parse_code_blobFr   return_generated_codec              
   K   s  || _ t|dkr|  j dt| d7  _ | | _|   tj| jd}tj	d| j  d}||g| _
| jd | j| j
 | jdurKd| jini }| j| j
fd	d
gi|}|r^|S z| j|dd\}}	W n  ty }
 z| jd|
  d|}}	W Y d}
~
nd}
~
ww z| |	}	W n" ty }
 zd|
 d}| jj|dd |W  Y d}
~
S d}
~
ww | ||	 z"i t | jj}| j|	|i | j| jd}| j| jd  |W S  ty }
 zd|
 d}| jj|dd |W  Y d}
~
S d}
~
ww )aK  
        Runs the agent for the given task.

        Args:
            task (`str`): The task to perform
            return_generated_code (`bool`, *optional*, defaults to `False`): Whether to return the generated code instead of running it
            kwargs (additional keyword arguments, *optional*):
                Any keyword argument to send to the agent when evaluating the code.

        Example:

        ```py
        from transformers.agents import CodeAgent

        agent = CodeAgent(tools=[])
        agent.run("What is the result of 2 power 3.7384?")
        ```
        r   6
You have been provided with these initial arguments: r   r   r   z"====Executing with this prompt====Nr   stop_sequences<end_action>Code:r   r  zSError in extracting action, trying to parse the whole output as code. Error trace: rw   Error in code parsing: z!. Be sure to provide correct coder   r  static_toolscustom_toolsr  r   print_outputszError in execution: z". Be sure to provide correct code.)r   lenr   copyr  r   r   r   r   r  r   r   infor   r   r  rh   r   rv   r   r%  r   r   r   r/  r   )r7   r   r1  r'  r  r  r   r   r  r  rl   r  r  outputr;   r;   r<   r(    sf   

zCodeAgent.runNNNNNr   )r=   r>   r?   r   r   r$   r   r   r   r   r   rv   r   r(  r   r;   r;   r   r<   r*  P  s,    
%r*  c                       s   e Zd ZdZeddd						d!dee dee dee	 d	ee	 d
ee
e	e	f  dee	 dee f fddZde	fddZedddd"de	dedefddZde	fddZde	fddZd#dedee fdd Z  ZS )$
ReactAgentaC  
    This agent that solves the given task step by step, using the ReAct framework:
    While the objective is not reached, the agent will perform a cycle of thinking and acting.
    The action will be parsed from the LLM output: it consists in calls to tools from the toolbox, with arguments chosen by the LLM engine.
    4.51.0zSwitch to smolagents instead, with the same functionalities and similar API (https://huggingface.co/docs/smolagents/index)versionr   Nr   r   r   r   r   	plan_typeplanning_intervalc           	         s~   |d u rt  }|d u rt}|d u rt}|d u rtd }n|tv s(J d| dt jd|||||d| || _|| _d S )Nr   z
plan type z is not supportedr,  r;   )r   r   r#   r   r   r   rG  rF  )	r7   r   r   r   r   r   rF  rG  r'  r   r;   r<   r     s(   

zReactAgent.__init__rP   c              
   C   s   t jddg| _|  j|  dd 7  _|  jt jd| dg7  _z| | jW S  tyC } zd| dW  Y d}~S d}~ww )zq
        This method provides a final answer to the task, based on the logs of the agent's interactions.
        zAn agent tried to answer an user query but it got stuck and failed to do so. You are tasked with providing an answer instead. Here is the agent's memory:r   r   NzLBased on the above, please provide an answer to the following user request:
z&Error in generating final llm output: r   )r   r   r   r  r  r   rh   )r7   r   rl   r;   r;   r<   provide_final_answer  s    zReactAgent.provide_final_answerFTr   streamrI   c                 K   sl   || _ t|dkr|  j dt| d7  _ | | _|r"|   n| jd|i |r1| |S | 	|S )a8  
        Runs the agent for the given task.

        Args:
            task (`str`): The task to perform

        Example:
        ```py
        from transformers.agents import ReactCodeAgent
        agent = ReactCodeAgent(tools=[])
        agent.run("What is the result of 2 power 3.7384?")
        ```
        r   r2  r   r   )
r   r<  r   r=  r  r   r   r   
stream_run
direct_run)r7   r   rI  rI   r'  r;   r;   r<   r(    s   



zReactAgent.runc              
   c   s   d}d}|du r|| j k rt }||d}zUz| | d|v r&|d }W n tyE } z| jj|dd ||d< W Y d}~nd}~ww W t }||d< || |d	< | j| | jD ]}|| q^|d7 }|V  n&t }||d< || |d	< | j| | jD ]}|| q|d7 }|V  w |du r|| j k s|du r|| j krd
}	dt	|	i}
| j|
 | jj|	dd | 
|}||
d< d|
d	< | jD ]}||
 q|
V  |V  dS )z
        Runs the agent in streaming mode, yielding steps as they are executed: should be launched only in the `run` method.
        Nr   	iteration
start_timefinal_answerr   r  r   step_end_timestep_durationReached max iterations.)r   timestepr   r   r   r   r   r   r   rH  r7   r   rO  rM  step_start_timestep_log_entryrl   rP  callbackerror_messagefinal_step_logr;   r;   r<   rJ  .  s\   









zReactAgent.stream_runc              
   C   s  d}d}|du r|| j k rt }||d}zhz%| jdur.|| j dkr.| j||dk|d | | d|v r;|d }W n tyZ } z| jj|dd ||d< W Y d}~nd}~ww W t }||d	< || |d
< | j	| | j
D ]}|| qs|d7 }n#t }||d	< || |d
< | j	| | j
D ]}|| q|d7 }w |du r|| j k s|du r|| j krd}	dt|	i}
| j	|
 | jj|	dd | |}||
d< d|
d
< | j
D ]}||
 q|S )z
        Runs the agent in direct mode, returning outputs only at the end: should be launched only in the `run` method.
        Nr   rL  )is_first_steprM  rO  r   r  r   rP  rQ  rR  )r   rS  rG  planning_steprT  r   r   r   r   r   r   r   rH  rU  r;   r;   r<   rK  V  sX   










zReactAgent.direct_runr[  rM  c                 C   s  |rvt jtd}t jd| dd}| ||g}t jt| j d d}t jt| j d j|| j	| j
| jdur>t| jnd|dd}| j||gd	gd
}	d|	 d}
d| d }| j|
|d | jdd | jd|
 dS | jdd}t jtd}t jtd}| |g| |g }t jt| j d j|dd}t jt| j d j|| j	| j
| jdurt| jnd|| j| dd}| j|g| |g d	gd
}tj||d}
d| d}| j|
|d | jdd | jd|
 dS )ax  
        Used periodically by the agent to plan the next steps to reach the objective.

        Args:
            task (`str`): The task to perform
            is_first_step (`bool`): If this step is not the first one, the plan should be an update over a previous plan.
            iteration (`int`): The number of the current step, used as an indication for the LLM.
        r   zHere is the task:
```
z
```
Now begin!systemuserNrw   )r   r   r   answer_factsz
<end_plan>)r3  zEHere is the plan of action that I will follow to solve the task:
```
z
```z+Here are the facts that I know so far:
```
)r   r   r0   z===== Initial plan =====r/   Fr   )r   )r   r   r   facts_updateremaining_steps)r   plan_updatez7Here is the updated list of the facts that I know:
```
z===== Updated plan =====)r   r   r   r  r   r   rF  r6   r   r   r   r   r   rs   r   r   r   r   r  r   r    r   r   r   )r7   r   r[  rM  message_prompt_factsmessage_prompt_taskr_  message_system_prompt_planmessage_user_prompt_plananswer_planfinal_plan_redactionfinal_facts_redactionr  facts_update_system_promptfacts_update_messagera  plan_update_messageplan_update_message_userrc  r;   r;   r<   r\  ~  s   		
zReactAgent.planning_stepNNNNNN)FT)FN)r=   r>   r?   r   r	   r   r$   r   r   r   r   r)  r   rH  r   r(  rJ  rK  r\  r   r;   r;   r   r<   rA    sH     ( (rA  c                       s|   e Zd ZdZ					ddee dee dee dee dee	eef  dee
 f fd	d
Zde	eef fddZ  ZS )r   a  
    This agent that solves the given task step by step, using the ReAct framework:
    While the objective is not reached, the agent will perform a cycle of thinking and acting.
    The tool calls will be formulated by the LLM in JSON format, then parsed and executed.
    Nr   r   r   r   r   rG  c              	      sJ   |d u rt  }|d u rt}|d u rt}t jd||||||d| d S )Nr   r   r   r   r   rG  r;   )r   r   r#   r   r   )r7   r   r   r   r   r   rG  r'  r   r;   r<   r     s    

zReactJsonAgent.__init__	log_entryc              
   C   sL  |   }|| _| jd | |d< | jd | j| jd  z| jdur-d| jini }| j| jfddd	gi|}W n tyR } zt	d
| dd}~ww | jd | j| ||d< | jd | j
|dd\}}z	| |\}}	W n ty } ztd| dd}~ww ||d< ||	d|d< | jd | jd| | jd| d|	  |dkrt|	trd|	v r|	d }
t|
tr|
| j v r| j|
 }
n|	}
n|	}
|
|d< |
S |	du ri }	| ||	}t|}|ttfv r|tkrd}n|tkrd}|| j|< d| d}nt| }| j| ||d< |S ) 
        Perform one step in the ReAct framework: the agent thinks, acts, and observes the result.
        The errors are raised here, they are caught and logged in the run() method.
        ===== New step =====r  z/===== Calling LLM with this last message: =====rX   Nr   r3  r4  r    Error in generating llm output: r   z&===== Output message of the LLM: =====r   z===== Extracting action =====r   r6  z"Could not parse the given action: r  r   tool_argumentsr|   r   r+   z>>> Calling tool: 'z' with arguments: rO  answerz	image.pngz	audio.mp3zStored 'z' in memory.r   )r  r   r   r   r=  r>  r   r   rh   r   r  r   r   r$  r   r   r   r   r  r   r  r  r   r   rs   )r7   rq  r  r   r   rl   r  rx   r   r  rw  r   observation_typeobservation_nameupdated_informationr;   r;   r<   rT    s~   





zReactJsonAgent.stepr@  r=   r>   r?   r   r   r$   r   r   r   r   r)  r   r   rT  r   r;   r;   r   r<   r     s*    	r   c                       s   e Zd ZdZ						ddee dee dee dee dee	eef  deee  d	ee
 f fd
dZde	eef fddZ  ZS )ReactCodeAgenta  
    This agent that solves the given task step by step, using the ReAct framework:
    While the objective is not reached, the agent will perform a cycle of thinking and acting.
    The tool calls will be formulated by the LLM in code format, then parsed and executed.
    Nr   r   r   r   r   r+  rG  c           	   	      s   |d u rt  }|d u rt}|d u rt}t jd||||||d| t s,ttd t	| _
|r3|ng | _tttt| jB | _| jdt| j| _i | _d S )Nrp  zjpygments isn't installed. Installing pygments will enable color syntax highlighting in the ReactCodeAgent.r   r;   )r   r   r#   r   r   r   r-  r.  r   r"   r/  r+  r_   r   r!   r   r   rb   r   r:  )	r7   r   r   r   r   r   r+  rG  r'  r   r;   r<   r   X  s4   

zReactCodeAgent.__init__rq  c              
   C   s  |   }| | _| jd | |d< | jd | j| jdd  z| jdur1d| jini }| j| jfddd	gi|}W n tyV } zt	d
| dd}~ww | jd | j| ||d< | jd z| j
|dd\}}W n  ty } z| jd|  ||}}W Y d}~nd}~ww zt|}W n ty } z
d| d}	t|	d}~ww ||d< d|d|d< | || z`i t | jj}
| jduri |
| j}
| j||
| j| j| jd}| jd | jd| jd  d| jd  }|dur"| jd | jdt| |dt|dd  7 }||d < W n# tyJ } zd!t| }	d"t|v rB|	d#7 }	t|	d}~ww |d$D ] }|dtd% d%kro| jd&d' | jd| ||d%< qP|S )(rr  rs  r  z1===== Calling LLM with these last messages: =====r  Nr   r3  r4  r   rt  r   z=== Output message of the LLM:r   z=== Extracting action ===r5  r6  zKError in extracting action, trying to parse the whole output. Error trace: r7  z#. Make sure to provide correct coder  zcode interpreterru  r|   r8  zPrint outputs:r,   r;  zPrint outputs:
zLast output from code snippet:zLast output from code snippet:
i r   z2Code execution failed due to the following error:
z%'dict' object has no attribute 'read'zd
You get this error because you passed a dict as input for one of the arguments instead of a string.r   rO  r-   zFinal answer:)r  r=  r   r   r   r>  r   r   rh   r   r  rv   r   r%  r   r   r   r   r/  r:  r  r   r$  r   r   r   r   r<  )r7   rq  r  r   r   rl   r  raw_code_actionr  r  r9  r0  r   liner;   r;   r<   rT    s   



zReactCodeAgent.stepro  r{  r;   r;   r   r<   r|  Q  s0    	
(r|  i  c                   @   s2   e Zd ZeddddddZdd	 Zd
d ZdS )ManagedAgentrB  rC  rD  NFc                 C   s"   || _ || _|| _|| _|| _d S r1   )r   r   r   additional_promptingprovide_run_summary)r7   r   r   r   r  r  r;   r;   r<   r     s
   
zManagedAgent.__init__c                 C   sD   d| j  d| d}| jr|d| j }|S |dd }|S )NzYou're a helpful agent named 'z@'.
You have been submitted this task by your manager.
---
Task:
a  
---
You're helping your manager solve a wider task: so make sure to not provide a one-line answer, but give as much information as possible so that they have a clear understanding of the answer.

Your final_answer WILL HAVE to contain these parts:
### 1. Task outcome (short version):
### 2. Task outcome (extremely detailed version):
### 3. Additional context (if relevant):

Put all these in your final_answer tool, everything that you do not pass as an argument to final_answer will be lost.
And even if your task resolution is not successful, please return as much context as possible, so that your manager can act upon this feedback.
<<additional_prompting>>z
<<additional_prompting>>rw   )r   r  rb   rs   )r7   r   	full_taskr;   r;   r<   write_full_task  s   
zManagedAgent.write_full_taskc                 K   s   |  |}| jj|fi |}| jrhd| j d}|t|7 }|d| j d7 }| jjddD ]-}|d }tt|tk sCdt|v rN|dt| d	 7 }q/|dt|d t  d
 7 }q/|d| j d7 }|S |S )Nz2Here is the final answer from your managed agent 'z':
zZ

For more detail, find below a summary of this agent's work:
SUMMARY OF WORK FROM AGENT 'Tr`  r   z[FACTS LIST]r   z
---z0
(...Step was truncated because too long)...
---z$
END OF SUMMARY OF WORK FROM AGENT 'r]   )	r  r   r(  r  r   r   r  r<  LENGTH_TRUNCATE_REPORTS)r7   requestr'  r  r?  rw  r   r   r;   r;   r<   __call__  s(   
zManagedAgent.__call__)NF)r=   r>   r?   r	   r   r  r  r;   r;   r;   r<   r    s    r  r1   )^rc   r   r`   rS  typingr   r   r   r   r   r   r   "huggingface_hub.utils._deprecationr	   rw   r   utilsr-  utils.import_utilsr   agent_typesr   r   default_toolsr   r   r   r   r   r   
monitoringr   promptsr   r   r   r   r   r   r   r   r   r    r   r!   r"   r   r#   r$   r%   r&   pygmentsr'   pygments.formattersr(   pygments.lexersr)   r5   r*   
get_loggerr=   r   	propagateStreamHandlerchsetFormatter
addHandlerr   rn   rv   r~   r   r   r   r   r   rh   r   r   r   r   r   r   r_   r   r   r   r   r*  rA  r   r|  r  r  r;   r;   r;   r<   <module>   sl   $0
!
"*0	g m~  o 