
    ~h2             	           U d dl Z d dlZd dlZd dlZd dl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 d dlmZmZ d dlmZ d dlmZ d dlmZ d dlmZmZmZmZmZmZmZ d dlZd dl Z d d	l!m"Z"m#Z#m$Z$m%Z% d d
l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l0m1Z1 d dl2m3Z3 erd dl4Z5ddl6m7Z7m8Z8m9Z9 ddl:m;Z;m<Z< ddl=m>Z>m?Z?m@Z@mAZA ddlBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZM ddlNmOZOmPZPmQZQmRZRmSZSmTZTmUZUmVZV ddlWmXZXmYZYmZZZm[Z[ ddl\m]Z]m^Z^m_Z_ ddl`maZambZb ddlcmdZdmeZemfZfmgZgmhZhmiZimjZjmkZkmlZlmmZmmnZnmoZompZp  eeq      Zrdesdetes   fdZudesdevesef   desfdZwe G d  d!             Zxe G d" d#             Zy G d$ d%e      Zz G d& d'e      Z{ G d( d)e      Z| G d* d+e      Z} e}d, ezd,d,d,-       e{d,d,.       e|d,d,/      0      Z~e G d1 d2             ZeeQeRexeMeyeHeCeFf   Zeed3<    G d4 d5e	      Z G d6 d7e      Z G d8 d9e      Zy):    N)ABCabstractmethod)Callable	Generator)ThreadPoolExecutoras_completed)	dataclass)	getLogger)Path)TYPE_CHECKINGAnyLiteralType	TypeAlias	TypedDictUnion)create_repometadata_updatesnapshot_downloadupload_folder)StrictUndefinedTemplate)Group)Live)Markdown)Panel)Rule)Text   )
AgentAudio
AgentImagehandle_agent_output_types)TOOL_MAPPINGFinalAnswerTool)BASE_BUILTIN_MODULESLocalPythonExecutorPythonExecutorfix_final_answer_code)
ActionStepAgentMemoryCallbackRegistryFinalAnswerStep
MemoryStepPlanningStepSystemPromptStepTaskStepTiming
TokenUsageToolCall)CODEAGENT_RESPONSE_FORMATChatMessageChatMessageStreamDeltaChatMessageToolCallMessageRoleModelagglomerate_stream_deltasparse_json_if_needed)
YELLOW_HEXAgentLoggerLogLevelMonitor)DockerExecutorE2BExecutorWasmExecutor)Toolvalidate_tool_arguments)AGENT_GRADIO_APP_TEMPLATE
AgentErrorAgentExecutionErrorAgentGenerationErrorAgentMaxStepsErrorAgentParsingErrorAgentToolCallErrorAgentToolExecutionErrorextract_code_from_textis_valid_namemake_init_fileparse_code_blobstruncate_contenttemplatereturnc                     t        j                  d      }|j                  |      D ch c]!  }|j                  d      j	                         # c}S c c}w )Nz\{\{([^{}]+)\}\}r   )recompilefinditergroupstrip)selfrR   patternmatchs       M/opt/mcp/mcp-sentiment/venv/lib/python3.12/site-packages/smolagents/agents.pyget_variable_namesr^   f   sA    jj,-G070@0@0JKuEKKN  "KKKs   &A	variablesc                     t        | t              }	  |j                  di |S # t        $ r)}t        dt	        |      j
                   d|       d }~ww xY w)N)	undefinedz'Error during jinja template rendering: :  )r   r   render	Exceptiontype__name__)rR   r_   compiled_templatees       r]   populate_templaterj   k   se     _E[' ''4)44 [A$q'BRBRASSUVWUXYZZ[s   % 	A$AAc                   "    e Zd ZU eed<   eed<   y)ActionOutputoutputis_final_answerN)rg   
__module____qualname__r   __annotations__boolrc       r]   rl   rl   s   s    Krs   rl   c                   @    e Zd ZU eed<   eed<   eed<   eed<   eed<   y)
ToolOutputidrm   rn   observation	tool_callN)rg   ro   rp   strrq   r   rr   r3   rc   rs   r]   ru   ru   y   s    GKrs   ru   c                   0    e Zd ZU dZeed<   eed<   eed<   y)PlanningPromptTemplatez
    Prompt templates for the planning step.

    Args:
        plan (`str`): Initial plan prompt.
        update_plan_pre_messages (`str`): Update plan pre-messages prompt.
        update_plan_post_messages (`str`): Update plan post-messages prompt.
    initial_planupdate_plan_pre_messagesupdate_plan_post_messagesNrg   ro   rp   __doc__ry   rq   rc   rs   r]   r{   r{      s     !!""rs   r{   c                   &    e Zd ZU dZeed<   eed<   y)ManagedAgentPromptTemplatez
    Prompt templates for the managed agent.

    Args:
        task (`str`): Task prompt.
        report (`str`): Report prompt.
    taskreportNr   rc   rs   r]   r   r      s     IKrs   r   c                   &    e Zd ZU dZeed<   eed<   y)FinalAnswerPromptTemplatez
    Prompt templates for the final answer.

    Args:
        pre_messages (`str`): Pre-messages prompt.
        post_messages (`str`): Post-messages prompt.
    pre_messagespost_messagesNr   rc   rs   r]   r   r      s     rs   r   c                   :    e Zd ZU dZeed<   eed<   eed<   eed<   y)PromptTemplatesaq  
    Prompt templates for the agent.

    Args:
        system_prompt (`str`): System prompt.
        planning ([`~agents.PlanningPromptTemplate`]): Planning prompt templates.
        managed_agent ([`~agents.ManagedAgentPromptTemplate`]): Managed agent prompt templates.
        final_answer ([`~agents.FinalAnswerPromptTemplate`]): Final answer prompt templates.
    system_promptplanningmanaged_agentfinal_answerN)	rg   ro   rp   r   ry   rq   r{   r   r   rc   rs   r]   r   r      s!     $$--++rs   r    )r|   r}   r~   )r   r   )r   r   )r   r   r   r   c                   \    e Zd ZU dZedz  ed<   ed   ed<   ee   ed<   e	dz  ed<   e
ed<   y)		RunResulta  Holds extended information about an agent run.

    Attributes:
        output (Any | None): The final output of the agent run, if available.
        state (Literal["success", "max_steps_error"]): The final state of the agent after the run.
        messages (list[dict]): The agent's memory, as a list of messages.
        token_usage (TokenUsage | None): Count of tokens used during the run.
        timing (Timing): Timing details of the agent run: start time, end time, duration.
    Nrm   )successmax_steps_errorstatemessagestoken_usagetiming)rg   ro   rp   r   r   rq   r   listdictr2   r1   rc   rs   r]   r   r      s9     $J/004jd""Nrs   r   StreamEventc            $       $   e Zd ZdZddddej
                  ddddddddddfdee   dede	dz  de
dz  d	ed
ededee
e
f   dz  dedz  dee   eee   eee   z  f   z  dz  dedz  de
dz  de
dz  dedee   dz  dededz  f"dZede
fd       Zej*                  de
fd       Zde
dz  de
dz  fdZdOdedz  ddfdZd Zd Zd Z	 	 	 	 	 dPd e
d!ed"ed#ed$   dz  d%edz  d	edz  fd&Z	 dOd e
d	ed#ed$   dz  deeez  ez  e z     fd'Z!d(e"fd)Z#d*eez  fd+Z$d e
d#ed$   de"fd,Z%d-ed.edee ez     fd/Z&ed0        Z'e(de
fd1       Z)d2 Z*	 dQd3edee+   fd4Z,d*edee e-z  e.z  e/z     fd5Z0d*ede"fd6Z1d7e
d8e
de2e
e
f   fd9Z3dOd e
d#ed$   dz  de+fd:Z4d; Z5dQd<efd=Z6d e
fd>Z7dOd?e
e8z  d@e
dz  fdAZ9dee
e"f   fdBZ:e;dCee
e"f   dd fdD       Z<e;	 	 dRdEe
dFe
dz  dGefdH       Z=e;dIe
e8z  fdJ       Z>	 	 	 	 dSdEe
dKe
dLedz  dFee
z  dz  dMede
fdNZ?y)TMultiStepAgentar  
    Agent class 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 action (given by the LLM) and observation (obtained from the environment).

    Args:
        tools (`list[Tool]`): [`Tool`]s that the agent can use.
        model (`Callable[[list[dict[str, str]]], ChatMessage]`): Model that will generate the agent's actions.
        prompt_templates ([`~agents.PromptTemplates`], *optional*): Prompt templates.
        instructions (`str`, *optional*): Custom instructions for the agent, will be inserted in the system prompt.
        max_steps (`int`, default `20`): Maximum number of steps the agent can take to solve the task.
        add_base_tools (`bool`, default `False`): Whether to add the base tools to the agent's tools.
        verbosity_level (`LogLevel`, default `LogLevel.INFO`): Level of verbosity of the agent's logs.
        grammar (`dict[str, str]`, *optional*): Grammar used to parse the LLM output.
            <Deprecated version="1.17.0">
            Parameter `grammar` is deprecated and will be removed in version 1.20.
            </Deprecated>
        managed_agents (`list`, *optional*): Managed agents that the agent can call.
        step_callbacks (`list[Callable]` | `dict[Type[MemoryStep], Callable | list[Callable]]`, *optional*): Callbacks that will be called at each step.
        planning_interval (`int`, *optional*): Interval at which the agent will run a planning step.
        name (`str`, *optional*): Necessary for a managed agent only - the name by which this agent can be called.
        description (`str`, *optional*): Necessary for a managed agent only - the description of this agent.
        provide_run_summary (`bool`, *optional*): Whether to provide a run summary when called as a managed agent.
        final_answer_checks (`list[Callable]`, *optional*): List of validation functions to run before accepting a final answer.
            Each function should:
            - Take the final answer and the agent's memory as arguments.
            - Return a boolean indicating whether the final answer is valid.
    N   Ftoolsmodelprompt_templatesinstructions	max_stepsadd_base_toolsverbosity_levelgrammarmanaged_agentsstep_callbacksplanning_intervalnamedescriptionprovide_run_summaryfinal_answer_checksreturn_full_resultloggerc                 0   | j                   j                  | _        || _        |xs t        | _        |t        t        j                               t        |j                               z
  }|r
J d|        t        j                         D ]_  \  }}t        |t              s|j                         D ]6  }||j                         v r|||   j                         v r+J d| d|         a || _        d| _        |t        j                  dt               || _        || _        i | _        | j'                  |      | _        || _        || _        ||ng | _        || _        || _        | j5                  |	       | j7                  ||       | j9                  ||	       d | _        t=        | j>                        | _         |tC        |      | _"        n|| _"        tG        | j                  | jD                        | _$        | jK                  |
       d| _&        y )NzGSome prompt templates are missing from your custom `prompt_templates`: z under r   zFParameter 'grammar' is deprecated and will be removed in version 1.20.levelF)'	__class__rg   
agent_namer   EMPTY_PROMPT_TEMPLATESr   setkeysitems
isinstancer   r   step_numberwarningswarnFutureWarningr   r   r   _validate_namer   r   r   r   r   r   _setup_managed_agents_setup_tools"_validate_tools_and_managed_agentsr   r*   r   memoryr=   r   r?   monitor_setup_step_callbacksstream_outputs)rZ   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   missing_keyskeyvaluesubkeys                         r]   __init__zMultiStepAgent.__init__  s   ( ..11
 0 J4J'5::<=DTDYDYD[@\\L# YZfYgh# 5::< 
UeT*"'**, "&6&;&;&==6M]^aMbMgMgMiCi eflemmtuxtyzj #MMX !2%'
''-	&#6 :M:Y#6_a "4("">2%0//~F $	!$"4"45>%O<DK DKtzz4;;7"">2#rs   rS   c                 "    | j                         S N)initialize_system_promptrZ   s    r]   r   zMultiStepAgent.system_promptG  s    ,,..rs   r   c                     t        d      )Nz`The 'system_prompt' property is read-only. Use 'self.prompt_templates["system_prompt"]' instead.)AttributeError)rZ   r   s     r]   r   zMultiStepAgent.system_promptK  s    r
 	
rs   c                 >    |t        |      st        d| d      |S )NzAgent name 'z?' must be a valid Python identifier and not a reserved keyword.)rN   
ValueError)rZ   r   s     r]   r   zMultiStepAgent._validate_nameQ  s)    M$$7|D61pqrrrs   c                     i | _         |rpt        d |D              sJ d       |D ci c]  }|j                  | c}| _         | j                   j                         D ]  }ddddddd|_        d|_         y	y	c c}w )
z)Setup managed agents with proper logging.c              3   P   K   | ]  }|j                   xr |j                     y wr   )r   r   ).0agents     r]   	<genexpr>z7MultiStepAgent._setup_managed_agents.<locals>.<genexpr>Z  s"     TEuzz7e&7&77Ts   $&z6All managed agents need both a name and a description!stringz&Long detailed description of the task.)rf   r   objectz{Dictionary of extra inputs to pass to the managed agent, e.g. images, dataframes, or any other contextual data it may need.)r   additional_argsN)r   allr   valuesinputsoutput_type)rZ   r   r   s      r]   r   z$MultiStepAgent._setup_managed_agentsV  s     T^TT HT CQ"Q5::u#4"QD,,335 -%->fg ( (e(  %-!-  #Rs   A;c           	         t        d |D              sJ d       |D ci c]  }|j                  | c}| _        |rd| j                  j                  t	        j
                         D ci c]+  \  }}|dk7  s| j                  j                  dk(  r| |       - c}}       | j                  j                  dt                      y c c}w c c}}w )Nc              3   <   K   | ]  }t        |t                y wr   )r   rC   )r   tools     r]   r   z.MultiStepAgent._setup_tools.<locals>.<genexpr>j  s     <d:dD)<   z5All elements must be instance of Tool (or a subclass)python_interpreterToolCallingAgentr   )
r   r   r   updater#   r   r   rg   
setdefaultr$   )rZ   r   r   r   r   clss         r]   r   zMultiStepAgent._setup_toolsi  s    <e<<u>uu<278$diio8
JJ &2%7%7%9!c33t~~7N7NRd7d #%K 	

no.?@ 9s   C(0C

c           	         |D cg c]  }|j                    }}|||D cg c]  }|j                    c}z  }| j                   r|j                  | j                          t        |      t        t        |            k7  r1t	        d|D cg c]  }|j                  |      dkD  s| c}       y c c}w c c}w c c}w )NzXEach tool or managed_agent should have a unique name! You passed these duplicate names: r   )r   appendlenr   r   count)rZ   r   r   r   tool_and_managed_agent_namesr   r   s          r]   r   z1MultiStepAgent._validate_tools_and_managed_agentsv  s    >C'Dd		'D$'D%(^,TEUZZ,TT(99(//		:+,C8T4U0VVj%ArTEaEgEghlEmpqEqDrsu  W (E,T ss   B2B7
B<
$B<
c                    t               | _        |rt        |t              r(|D ]"  }| j                  j	                  t
        |       $ njt        |t              rO|j                         D ];  \  }}t        |t              s|g}|D ]  }| j                  j	                  ||         = nt        d      | j                  j	                  t
        | j                  j                         y )Nz'step_callbacks must be a list or a dict)r+   r   r   r   registerr)   r   r   r   r   update_metrics)rZ   r   callbackstep_cls	callbackss        r]   r   z$MultiStepAgent._setup_step_callbacks  s    .0.$/ . GH''00XFG ND1+9+?+?+A I'Hi%i6%.K	$- I++44XxHII !!JKK$$Z1L1LMrs   r   streamresetimageszPIL.Image.Imager   c           
      d   |xs | j                   }|| _        d| _        |=| j                  j	                  |       | xj                  dt        |       dz  c_        t        | j                        | j                  _        |r4| j                  j                          | j                  j                          | j                  j                  | j                  j                         t        | j                        j                    dt#        | j                  d      r| j                  j$                  nd t&        j(                  t#        | d	      r| j*                  nd
       | j                  j,                  j/                  t1        | j                  |             t3        | dd      rY| j4                  j7                  | j                         | j4                  j9                  i | j:                  | j<                         |r| j?                  | j                  ||      S tA        j@                         }tC        | j?                  | j                  ||            }tE        |d   tF              sJ |d   jH                  }	| jJ                  r d}
d}d}| j                  j,                  D ][  }tE        |tL        tN        f      s|jP                  d} n4|
|jP                  jR                  z  }
||jP                  jT                  z  }] |rtW        |
|      }nd}| j                  j,                  r5tE        t3        | j                  j,                  d   dd      tX              rd}nd}| j                  j[                         }t]        |	||t_        |tA        j@                               |      S |	S )a  
        Run the agent for the given task.

        Args:
            task (`str`): Task to perform.
            stream (`bool`): Whether to run in streaming mode.
                If `True`, returns a generator that yields each step as it is executed. You must iterate over this generator to process the individual steps (e.g., using a for loop or `next()`).
                If `False`, executes all steps internally and returns only the final answer after completion.
            reset (`bool`): Whether to reset the conversation or keep it going from previous run.
            images (`list[PIL.Image.Image]`, *optional*): Image(s) objects.
            additional_args (`dict`, *optional*): Any other variables that you want to pass to the agent run, for instance images or dataframes. Give them clear names!
            max_steps (`int`, *optional*): Maximum number of steps the agent can take to solve the task. if not provided, will use the agent's default value.

        Example:
        ```py
        from smolagents import CodeAgent
        agent = CodeAgent(tools=[])
        agent.run("What is the result of 2 power 3.7384?")
        ```
        FNz~
You have been provided with these additional arguments, that you can access using the keys as variables in your python code:
.)r   z - model_idr   r   )contentsubtitler   title)r   task_imagespython_executorr_   )r   r   r   r   Tinput_tokensoutput_tokenserrorr   r   
start_timeend_time)rm   r   r   r   r   )0r   r   interrupt_switchr   r   ry   r/   r   r   r   r   r   log_taskrY   rf   r   rg   hasattrr   r>   INFOr   stepsr   r0   getattrr   send_variables
send_toolsr   r   _run_streamtimer   r   r,   rm   r   r)   r.   r   r   r  r2   rI   get_full_stepsr   r1   )rZ   r   r   r   r   r   r   run_start_timer
  rm   total_input_tokenstotal_output_tokenscorrect_token_usagestepr   r   r   s                    r]   runzMultiStepAgent.run  s   : /		 %&JJo.II _ a I %54CUCU$V!KKLL IIOO%TZZ(112#gVZV`V`blNmtzz7J7Jsu5wx--&tV4$))$	 	 	
 	  tyyf!MN4*D1  //$**/E  ++,Qtzz,QT=P=P,QR##iPV#WW T%%499	RX%YZ%)_555r!!""!""#"&)) NdZ$>?''/.3+*d.>.>.K.KK*+t/?/?/M/MM+N #(6HXkl"{{  Z8I8I"8MwX\0]_q%r)!{{113H'!$))+N  rs   c              #     K   d| _         d}|s| j                   |k  r| j                  rt        d| j                        | j                  | j                   dk(  s| j                   dz
  | j                  z  dk(  rt        j
                         }d }| j                  |t        | j                  j                        dk(  | j                         D ]  }| |}
 t        |t              sJ t        j
                         }t        ||      |_        | j                  |       | j                  j                  j                  |       t        j
                         }	t!        | j                   t        |	      |      }
| j                  j#                  d	| j                    t$        j&                  
       	 | j)                  |
      D ]  }| t        |t*              s|j,                  s%|j.                  }| j                  j1                  t3        d| dt4               t$        j&                  
       | j6                  r| j9                  |       d}d|
_         	 | j                  |
       | j                  j                  j                  |
       |
 | xj                   dz  c_         |s| j                   |k  r|s(| j                   |dz   k(  r| j?                  ||      }
 tA        tC                     y # t:        $ r}|d }~wt        $ r}||
_        Y d }~d }~ww xY w# | j                  |
       | j                  j                  j                  |
       |
 | xj                   dz  c_         w xY ww)Nr   FzAgent interrupted.r   )is_first_stepr  r  )r  )r   r   observations_imageszStep r   zFinal answer: zbold styleT)"r   r  rF   r   r   r  _generate_planning_stepr   r   r
  r   r.   r1   r   _finalize_stepr   r)   log_ruler>   r	  _step_streamrl   rn   rm   logr   r<   r   _validate_final_answerrH   r  _handle_max_steps_reachedr,   r"   )rZ   r   r   r   returned_final_answerplanning_start_timeplanning_stepelementplanning_end_timeaction_step_start_timeaction_steprm   r   ri   s                 r]   r  zMultiStepAgent._run_stream  s       %'D,<,<	,I$$ !5t{{CC %%1  A%$*:*:Q*>$BXBX)X\])]&*iik# $#;;DKK,=,=(>!(C$JZJZ  <   ,G "M$+M	,
 "->>>$(IIK!'-2.($ ##M2!!((7 &*YY["$ ,,)?@$*K
 KK  5)9)9(:!;8== Q&"//< ;F L!&,7F<R<R'-}} >,!@%PZ|H\]"*-- ( 
  33 77E04-6:3;. ##K0!!((5!!  A% w (D,<,<	,Iz %)9)9Y])J99$GL7EFF (  &$%!!& ##K0!!((5!!  A% sd   F4N7(L  L -A4L !L0 "A NAN	L-LL-L(#L0 (L--L0 0ANNr   c                     | j                   D ]  }	  ||| j                        sJ  y # t        $ r+}t        d|j                   d| | j
                        d }~ww xY w)NzCheck z failed with error: )r   r   re   rF   rg   r   )rZ   r   check_functionri   s       r]   r!  z%MultiStepAgent._validate_final_answer@  sr    "66 	iNi%lDKK@@@	i  i 6.*A*A)BBVWXVY!Z\`\g\ghhis   )	A&AAmemory_stepc                     t        j                          |j                  _        | j                  j	                  ||        y )N)r   )r  r   r  r   r   rZ   r,  s     r]   r  zMultiStepAgent._finalize_stepG  s/    &*iik#$$[$=rs   c           	         t        j                          }| j                  ||      }t        | j                  t	        d| j
                        t        |t        j                                |j                        }|j                  |_	        | j                  |       | j                  j                  j                  |       |j                  S )NzReached max steps.r  )r   r  r   r   )r  provide_final_answerr)   r   rI   r   r1   r   r   action_outputr  r   r
  r   )rZ   r   r   r(  r   final_memory_steps         r]   r"  z(MultiStepAgent._handle_max_steps_reachedK  s    !%00v>&(($%94;;G%;diikR$00	
 +7*>*>'-.  !23###rs   r  r  c              #   	  K   t        j                          }|rt        t        j                  dt	        | j
                  d   d   || j                  | j                  d      dg      g}| j                  rt        | j                  d      rd	}| j                  j                  |d
g      }d\  }}	t        d	| j                  j                  d      5 }
|D ]v  }|j                  d||j                  z  }|
j!                  t#        |             |j$                  r/|	|j$                  j&                  z  }	|j$                  j(                  }| x 	 d d d        ng| j                  j+                  |d
g      }|j                  }|j$                  r,|j$                  j(                  |j$                  j&                  fnd\  }}	t-        j.                  d| d      }n-| j1                  d      }t        t        j2                  dt	        | j
                  d   d   d|i      dg      }t        t        j                  dt	        | j
                  d   d   || j                  | j                  | j4                  |z
  d      dg      }|g|z   |gz   }| j                  rt        | j                  d      rd	}d\  }}	t        d	| j                  j                  d      5 }
| j                  j                  |d
g      D ]v  }|j                  d||j                  z  }|
j!                  t#        |             |j$                  r/|	|j$                  j&                  z  }	|j$                  j(                  }| x 	 d d d        nb| j                  j+                  |d
g      }|j                  }|j$                  ,|j$                  j(                  |j$                  j&                  }	}t-        j.                  d| j6                   d| d      }|rdnd}| j                  j9                  t;        d| d      t=        |      t>        j@                         tC        ||t        t        jD                  |      tG        	       tI        |t        j                          !      "       y # 1 sw Y   xY w# 1 sw Y   xY ww)#Ntextr   r|   )r   r   r   r   rf   r4  roler   generate_streamr   z
<end_plan>)stop_sequences)r   r   visibleconsolevertical_overflow)NNz[Here are the facts I know and the plan of action that I will follow to solve the task:
```
z
```Tsummary_moder}   r   r~   )r   r   r   remaining_stepsz0I still need to solve the task I was given:
```
zY
```

Here are the facts I know and my new/updated plan of action to solve the task:
```
zInitial planzUpdated planz[bold]oranger  r   r   r  )model_input_messagesplanmodel_output_messager   r   )%r  r5   r8   USERrj   r   r   r   r   r  r   r8  r   r   r<  r   r   r   r   r  r   generatetextwrapdedentwrite_memory_to_messagesSYSTEMr   r   r   r   r   r>   r	  r.   	ASSISTANTr2   r1   )rZ   r   r  r  r  input_messagesplan_message_contentoutput_streamr   r  liveeventplan_messagerC  memory_messagesplan_update_preplan_update_postlog_headlines                     r]   r  z&MultiStepAgent._generate_planning_stepY  s     YY[
$)) %+$5 $ 5 5j A. Q37$**`d`s`s*t%N ""wtzz;L'M')$ $

 : :>[gZh : i.2+m"dkk&9&9YW $[_!. $ ==40EMMA0 KK1E(FG$00 -1B1B1P1P P/4/@/@/M/M#$$ $  $zz22>S_R`2a'3';';$ $// %00==$00>>
 & ,m ??q  sG  rH  HM  PD #;;;NO) '' !' 1 11*=>XYflnres!
O  + %% !' 1 11*=>YZ(,)-262E2E48NNT4I	'! " ..@DTCUUN""wtzz;L'M')$.2+m"dkk&9&9YW $[_!%!;!;&(4~ "< " 
$ !==40EMMA0 KK1E(FG$00 -1B1B1P1P P/4/@/@/M/M#
$$ $  $zz22>S_R`2a'3';';$++7$00==$00>> #0L ??Ftyyk  Rp  qE  pF  FK  ND *7~Nvl^4HEtDzYaYfYfg!/!,+2G2GQe!f"MZZ$))+F
 	
i$ $v$ $s:   CSA<R(FS!BR5:D.S(R2-S5R>:Sc                     t         j                  d       | j                  j                  g| j                  j                  z   S )NzdThe 'logs' attribute is deprecated and will soon be removed. Please use 'self.memory.steps' instead.)r   warningr   r   r
  r   s    r]   logszMultiStepAgent.logs  s5    r	
 ))*T[[->->>>rs   c                      y)z"To be implemented in child classesNrc   r   s    r]   r   z'MultiStepAgent.initialize_system_prompt  s     	rs   c                     d| _         y)zInterrupts the agent execution.TN)r  r   s    r]   	interruptzMultiStepAgent.interrupt  s
     $rs   r?  c                     | j                   j                  j                  |      }| j                   j                  D ]#  }|j	                  |j                  |             % |S )z
        Reads past llm_outputs, actions, and observations or errors from the memory into a series of messages
        that can be used as input to the LLM. Adds a number of keywords (such as PLAN, error, etc) to help
        the LLM.
        r>  )r   r   to_messagesr
  extend)rZ   r?  r   r,  s       r]   rI  z'MultiStepAgent.write_memory_to_messages  s[     ;;,,88l8S;;,, 	PKOOK333NO	Prs   c                     t        d      )  
        Perform one step in the ReAct framework: the agent thinks, acts, and observes the result.
        Yields ChatMessageStreamDelta during the run if streaming is enabled.
        At the end, yields either None if the step is not final, or the final answer.
        z2This method should be implemented in child classes)NotImplementedErrorr.  s     r]   r  zMultiStepAgent._step_stream  s     ""VWWrs   c                 <    t        | j                  |            d   S )z
        Perform one step in the ReAct framework: the agent thinks, acts, and observes the result.
        Returns either None if the step is not final, or the final answer.
        r   )r   r  r.  s     r]   r  zMultiStepAgent.step  s    
 D%%k23B77rs   model_outputsplit_tokenc           
          	 |j                  |      }|d   |d   }}|j	                         |j	                         fS # t        $ r! t        d| d| d| d| j                        w xY w)z
        Parse action from the LLM output

        Args:
            model_output (`str`): Output of the LLM
            split_token (`str`): Separator for the action. Should match the example in the system prompt.
        r   zNo 'z.' token provided in your output.
Your output:
z0
. Be sure to include an action, prefaced with 'z'!)splitre   rJ   r   rY   )rZ   rc  rd  rg  	rationaleactions         r]   extract_actionzMultiStepAgent.extract_action  s    
	 &&{3Eb	b	 I  &,,.00  	#{m#ST`Sa  bS  T_  S`  `b  c 	s	   = *A'c                 0   t        t        j                  d| j                  d   d   dg      g}|r)|d   xj                  |D cg c]  }d|d	 c}z  c_        || j                         d	d
 z  }|j                  t        t        j                  dt        | j                  d   d   d|i      dg             	 | j                  j                  |      }|S c c}w # t        $ r,}t        t        j                  dd| dg      cY d
}~S d
}~ww xY w)a+  
        Provide the final answer to the task, based on the logs of the agent's interactions.

        Args:
            task (`str`): Task to perform.
            images (`list[PIL.Image.Image]`, *optional*): Image(s) objects.

        Returns:
            `str`: Final answer to the task.
        r4  r   r   r5  r6  r   image)rf   rl  r   Nr   r   r   z&Error in generating final LLM output: )r5   r8   rJ  r   r   rI  r   rE  rj   r   rF  re   rK  )rZ   r   r   r   rl  chat_messageri   s          r]   r0  z#MultiStepAgent.provide_final_answer  s5     '' !' $ 5 5n En U

 QKSY#Z%Wu$E#ZZD113AB77 %% !' 1 11.A/R_egk^l!
	
	(,

(;(;H(EL# $[$  	 **"(4Z[\Z]2^_` 	s$   C>C   	D)!D
DDc                 :    | j                   j                  |        y)z;Creates a rich tree visualization of the agent's structure.N)r   visualize_agent_treer   s    r]   	visualizezMultiStepAgent.visualize?  s    ((.rs   detailedc                 R    | j                   j                  | j                  |       y)a  Prints a pretty replay of the agent's steps.

        Args:
            detailed (bool, optional): If True, also displays the memory at each step. Defaults to False.
                Careful: will increase log length exponentially. Use only for debugging.
        )rq  N)r   replayr   )rZ   rq  s     r]   rs  zMultiStepAgent.replayC  s     	4;;:rs   c                    t        | j                  d   d   t        | j                  |            } | j                  |fi |}t        |t              r|j                  }n|}t        | j                  d   d   t        | j                  |            }| j                  rJ|dz  }| j                  d	      D ]+  }|j                  }|d
t        t        |            z   dz   z  }- |dz  }|S )zAdds additional prompting for the managed agent, runs it, and wraps the output.
        This method is called only by a managed agent.
        r   r   )r   r   r   r   )r   r   zP

For more detail, find below a summary of this agent's work:
<summary_of_work>
Tr>  
z
---z
</summary_of_work>)rj   r   r   r   r  r   r   rm   r   rI  r   rQ   ry   )	rZ   r   kwargs	full_taskresultr   answermessager   s	            r]   __call__zMultiStepAgent.__call__L  s     &!!/26:		5
	 ).v.fi(]]FF"!!/28<RVR[R[jpHq
 ##llF88d8K J!//$!1#g,!??'IIJ ,,Frs   
output_dirrelative_pathc           	      T   t        |       | j                  rt        t        j                  j	                  |d             | j                  j                         D ]F  \  }}d| }|r|dz   |z   }|j                  t        j                  j	                  |d|      |       H | j                  j                  }| j                  j                         D ]g  }t        t        j                  j	                  |d             |j                  t        j                  j	                  |d      |j                  d       i t        j                  | j                  ddt        d	      dd
d      }t!        t        j                  j	                  |d      dd      5 }	|	j#                  |       ddd       | j%                         }
| j                  j                         D cg c]  }|j                   c}|
d<   | j                  j                         D ci c]#  }|j                  |j                  j                  % c}|
d<   t!        t        j                  j	                  |d      dd      5 }	t'        j(                  |
|	d       ddd       t!        t        j                  j	                  |d      dd      5 }	|	j+                  d |
d   D               ddd       t-        | dd      rd| j                   nd}||dz   nd}t.        }t1        j2                  t1        j4                         t0        j6                        }t8        |j:                  d<   d |j:                  d<   |j=                  |      }|j?                  |||
| j                  | j                  |d       }t!        t        j                  j	                  |d!      dd      5 }	|	j#                  |d"z          ddd       y# 1 sw Y   DxY wc c}w c c}w # 1 sw Y   xY w# 1 sw Y   <xY w# 1 sw Y   yxY w)#aR  
        Saves the relevant code files for your agent. This will copy the code of your agent in `output_dir` as well as autogenerate:

        - a `tools` folder containing the logic for each of the tools under `tools/{tool_name}.py`.
        - a `managed_agents` folder containing the logic for each of the managed agents.
        - an `agent.json` file containing a dictionary representing your agent.
        - a `prompt.yaml` file containing the prompt templates used by your agent.
        - an `app.py` file providing a UI for your agent when it is exported to a Space with `agent.push_to_hub()`
        - a `requirements.txt` containing the names of the modules used by your tool (as detected when inspecting its
          code)

        Args:
            output_dir (`str` or `Path`): The folder in which you want to save your agent.
        r   zmanaged_agents.r   )r}  r   F)tool_file_namemake_gradio_app|infT   )default_styledefault_flow_stylewidth	sort_keysallow_unicodeindentzprompts.yamlwzutf-8)encodingN
agent.json   )r  zrequirements.txtc              3   &   K   | ]	  }| d   yw)ru  Nrc   )r   rs     r]   r   z&MultiStepAgent.save.<locals>.<genexpr>  s     FaA3bFs   requirementsr   agent_r   r   )loaderra   reprc                 P    dj                  d | j                  d      D              S )Nr   c              3   <   K   | ]  }|j                           y wr   )
capitalize)r   words     r]   r   z8MultiStepAgent.save.<locals>.<lambda>.<locals>.<genexpr>  s     AqX\$//BSAqr   _)joinrg  )r   s    r]   <lambda>z%MultiStepAgent.save.<locals>.<lambda>  s"    "''Aq`e`k`klo`pAq:q rs   	camelcase)r   
class_name
agent_dictr   r   managed_agent_relative_pathzapp.pyru  ) rO   r   ospathr  r   saver   rg   r   r   r   yaml	safe_dumpr   floatopenwriteto_dictjsondump
writelinesr  rE   jinja2Environment
BaseLoaderr   r  filtersfrom_stringrd   )rZ   r|  r}  r   r   agent_suffixr  r   yaml_promptsfr  r  app_templatetemplate_envrR   app_texts                   r]   r  zMultiStepAgent.saved  s    	z" 277<<
4DEF%)%8%8%>%>%@ o!
E!0= #03#6#EL

277<<
4DjQam
n	o ^^,,
 JJ%%' 	jD277<<
G<=IIbggll:w7		chIi	j
 ~~!!$,
 "'',,z>:C'R 	"VWGGL!	" \\^
59ZZ5F5F5HITtyyI
7Z^ZmZmZtZtZv'wQV

EOO4L4L(L'w
#$"'',,z<8#P 	/TUIIj!A.	/ "'',,z+=>gV 	GZ[LLF:n+EFF	G .5T64-Hvdii[)g
=J=Vmc&9\^#0))1B1B1DPVPfPfg'+V$,q[)++L9 ??((("&"5"5/J	
 "'',,z84cGL 	%PQGGHtO$	% 	%G	" 	"
 J'w	/ 	/	G 	G0	% 	%s<   O-O:(O?.P;PP-O7PPP'c                    dD ]>  }t        | |d      s| j                  j                  d| dt        j                         @ | j
                  j                         D cg c]  }|j                          }}| j
                  j                         D ch c]  }|j                         d   D ]  }|  }}}| j                  j                         D ch c]  }|j                         d   D ]  }|  }}}||z  }t        | d      rD|j                  | j                  D 	ch c]  }	|	t        vs|	j                  d      d   ! c}	       | j                  j                  || j                   j                  j                  | j                   j                         d	| j                  j                         D cg c]  }|j                          c}| j"                  | j$                  t'        | j                  j(                        | j*                  | j,                  | j.                  | j0                  t3        |      d
}
|
S c c}w c c}}w c c}}w c c}	w c c}w )Convert the agent to a dictionary representation.

        Returns:
            `dict`: Dictionary representation of the agent.
        )r   r   NzThis agent has z&: they will be ignored by this method.r  authorized_importsr   r   )classdata)r  r   r   r   r   r   r   r   r   r   r   r  )r  r   r   r>   r	  r   r   r  r   r  r   r  r%   rg  r   rg   r   r   r   intr   r   r   r   r   sorted)rZ   attrr   
tool_dictsreqtool_requirementsr   managed_agents_requirementsr  packager  s              r]   r  zMultiStepAgent.to_dict  s    > 	oDtT4(/$7] ^`h`m`mn	o 261B1B1DEdllnE
E-1ZZ->->-@kTDLLN[iLjkSSkSkk%)%8%8%?%?%A'
!]MbMbMdesMt'
FIC'
'
# '
 )+FF4-.6:6M6Mu7QX`tQts#A&u
 ^^,,--66

**, MQL_L_LfLfLhi=}446i $ 5 5"4;;#4#45||!%!7!7II++"<0

" 9 Fk'
 v js$    I!I	!I%I3I<I
r  c                    |d   }t        t        j                  d      |d         }|j                  |d         }g }|d   D ])  }|j	                  t        j                  |d                + g }|d   j                         D ]J  \  }	}
t        t        j                  d      |
      }|j	                  |j                  |d   |	                L |||j                  d	      |j                  d
      |j                  d      |j                  d      |j                  d      |j                  d      |j                  d      d	}|j                         D ci c]  \  }}|	|| }}}|j                  |        | di |S c c}}w )a?  Create agent from a dictionary representation.

        Args:
            agent_dict (`dict[str, Any]`): Dictionary representation of the agent.
            **kwargs: Additional keyword arguments that will override agent_dict values.

        Returns:
            `MultiStepAgent`: Instance of the agent class.
        r   zsmolagents.modelsr  r  r   coder   smolagents.agentsr   r   r   r   r   r   r   )	r   r   r   r   r   r   r   r   r   rc   )
r  	importlibimport_module	from_dictr   rC   	from_coder   getr   )r   r  rv  
model_infomodel_classr   r   	tool_infor   managed_agent_namemanaged_agent_class_namemanaged_agent_class
agent_argskvs                  r]   r  zMultiStepAgent.from_dict  s     (
i556IJJW^L_`%%j&89#G, 	<ILL	&(9:;	< <FGW<X<^<^<` 	s8 8"))*A*ABU*VXp"q!!"5"?"?
K[@\]o@p"qr	s
  */A B#4)~~.?@!~~i0!+0C!DNN6*%>>-8


 (2'7'7'9Ktq!Q]adK
K&! Z  	 Ls   
F$Frepo_idtokentrust_remote_codec                     |st        d      |dddD ci c]  }||v r||j                  |       c}z  }t        t        dd|i|      } | j                  |fi |S c c}w )a  
        Loads an agent defined on the Hub.

        <Tip warning={true}>

        Loading a tool from the Hub means that you'll download the tool and execute it locally.
        ALWAYS inspect the tool you're downloading before loading it within your runtime, as you would do when
        installing a package using pip/npm/apt.

        </Tip>

        Args:
            repo_id (`str`):
                The name of the repo on the Hub where your tool is defined.
            token (`str`, *optional*):
                The token to identify you on hf.co. If unset, will use the token generated when running
                `huggingface-cli login` (stored in `~/.huggingface`).
            trust_remote_code(`bool`, *optional*, defaults to False):
                This flags marks that you understand the risk of running remote code and that you trust this tool.
                If not setting this to True, loading the tool from Hub will fail.
            kwargs (additional keyword arguments, *optional*):
                Additional keyword arguments that will be split in two: all arguments relevant to the Hub (such as
                `cache_dir`, `revision`, `subfolder`) will be used when downloading the files for your agent, and the
                others will be passed along to its init.
        znLoading an agent from Hub requires to acknowledge you trust its code: to do so, pass `trust_remote_code=True`.space)r  	repo_type)	cache_dirforce_downloadproxiesrevisionlocal_files_onlyr  rc   )r   popr   r   from_folder)r   r  r  r  rv  r   download_kwargsdownload_folders           r]   from_hubzMultiStepAgent.from_hub
  s    B ! A 
 %*@
D
 f} C 
D
 

 0TTOTUs9&99
D
s   A!folderc                    t        |      }t        j                  |dz  j                               }g }|d   j	                         D ]J  \  }}t        t        j                  d      |      }|j                  |j                  |dz  |z               L i |d<   g }|d   D ]/  }	|dz  |	 dz  j                         }
|j                  |	|
d       1 ||d<   |r||d<    | j                  |fi |S )zLoads an agent from a local folder.

        Args:
            folder (`str` or `Path`): The folder where the agent is saved.
            **kwargs: Additional keyword arguments that will be passed to the agent's init.
        r  r   r  r   z.py)r   r  )r   r  loads	read_textr   r  r  r  r   r  r  )r   r  rv  r  r   r  r  	agent_clsr   	tool_name	tool_codes              r]   r  zMultiStepAgent.from_folder@  s!    fZZ,!6 A A CD
 <FGW<X<^<^<` 	i8 8	 7 78K LNfgI!!)"7"7AQ8QTf8f"gh	i (*
#$ #G, 	AI')yk,==HHJILL)Y?@	A $
7 '5F#$s}}Z2622rs   commit_messageprivate	create_prc                 v   t        |||ddd      }|j                  }t        |dddgid|d       t        j                         5 }| j                  |       t        j                  d	| d
dj                  t        j                  |                    t        |||||d      cddd       S # 1 sw Y   yxY w)a   
        Upload the agent to the Hub.

        Parameters:
            repo_id (`str`):
                The name of the repository you want to push to. It should contain your organization name when
                pushing to a given organization.
            commit_message (`str`, *optional*, defaults to `"Upload agent"`):
                Message to commit while pushing.
            private (`bool`, *optional*, defaults to `None`):
                Whether to make the repo private. If `None`, the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.
            token (`bool` or `str`, *optional*):
                The token to use as HTTP bearer authorization for remote files. If unset, will use the token generated
                when running `huggingface-cli login` (stored in `~/.huggingface`).
            create_pr (`bool`, *optional*, defaults to `False`):
                Whether to create a PR with the uploaded files or directly commit.
        Tr  gradio)r  r  r  exist_okr  	space_sdktags
smolagentsr   )r  r  	overwritez!Uploading the following files to rb   ,)r  r  folder_pathr  r  r  N)r   r  r   tempfileTemporaryDirectoryr  r   infor  r  listdirr   )rZ   r  r  r  r  r  repo_urlwork_dirs           r]   push_to_hubzMultiStepAgent.push_to_hub`  s    2 
 ""lG,-	
 ((* 
	hIIhKK;G9BsxxPRPZPZ[cPdGeFfgh -$#!
	 
	 
	s   AB//B8r   )FTNNN)FNF)zUpload agentNNF)@rg   ro   rp   r   r>   r	  r   rC   r9   r   ry   r  rr   r   r   r   r-   r=   r   propertyr   setterr   r   r   r   r   r  r   r)   r.   r,   r6   r  r   r!  r  r"  r  rX  r   r   r[  r5   rI  r3   ru   rl   r  r  tuplerj  r0  rp  rs  r{  r   r  r  classmethodr  r  r  r  rc   rs   r]   r   r      s   @ 48#'$$,MM)-&*dh(,"&$)59#(%)%A$DzA$ A$ *D0	A$
 DjA$ A$ A$ "A$ c3h$&A$ tA$ Xd:.>4PX>@Y.Y)ZZ]aaA$ :A$ DjA$ 4ZA$ "A$  "(^d2!A$" !#A$$ d"%A$F /s / / 
3 
 

3: #* 
-D4K -4 -&A
N. 15'+ $aa a 	a
 &'$.a a :aH SWEGEG$'EG156G1H41OEG	:,>AWW	XEGNi3 i>*|*C >$c $4@Q;R $WZ $q
#'q
/2q
	)L8	9q
f ? ? #  % # 
k	X%X	)H4zALP	QX8
 8s 813 1S 1U3PS8_ 1*- -d;L6MPT6T -`k -^/;t ;S 0P%sTz P%#* P%d'c3h 'R (!4S> (!@P (! (!T  !"'	3:3: Tz3:  	3: 3:j 3t 3 3D -##'44 4 	4
 czD 4 4 
4rs   r   c                       e Zd ZdZ	 	 	 	 ddee   dededz  dedz  de	dedz  f fd	Z
ed
        ZdefdZdedeeez  ez  ez     fdZdededeeez     fdZdeeef   ez  deeef   ez  fdZdedeeef   ez  defdZ xZS )r   aU  
    This agent uses JSON-like tool calls, using method `model.get_tool_call` to leverage the LLM engine's tool calling capabilities.

    Args:
        tools (`list[Tool]`): [`Tool`]s that the agent can use.
        model (`Model`): Model that will generate the agent's actions.
        prompt_templates ([`~agents.PromptTemplates`], *optional*): Prompt templates.
        planning_interval (`int`, *optional*): Interval at which the agent will run a planning step.
        stream_outputs (`bool`, *optional*, default `False`): Whether to stream outputs during execution.
        max_tool_threads (`int`, *optional*): Maximum number of threads for parallel tool calls.
            Higher values increase concurrency but resource usage as well.
            Defaults to `ThreadPoolExecutor`'s default.
        **kwargs: Additional keyword arguments.
    Nr   r   r   r   r   max_tool_threadsc                 J   |xsO t        j                  t        j                  j	                  d      j                  d      j                               }t        |    d||||d| || _	        | j                  r!t        | j                  d      st        d      || _        y )Nsmolagents.promptsztoolcalling_agent.yaml)r   r   r   r   r8  \`stream_outputs` is set to True, but the model class implements no `generate_stream` method.rc   )r  	safe_loadr  	resourcesfilesjoinpathr  superr   r   r  r   r   r  )	rZ   r   r   r   r   r   r  rv  r   s	           r]   r   zToolCallingAgent.__init__  s     , 
t~~%%&:;DDE]^hhj0
 	 	
-/		

 	
 -wtzz;L'Mn  !1rs   c                     t        | j                  j                               t        | j                  j                               z   S )z4Returns a combined list of tools and managed agents.)r   r   r   r   r   s    r]   tools_and_managed_agentsz)ToolCallingAgent.tools_and_managed_agents  s5     DJJ%%'(40C0C0J0J0L+MMMrs   rS   c                 ~    t        | j                  d   | j                  | j                  | j                  d      }|S )Nr   )r   r   custom_instructionsr   )rj   r   r   r   r   rZ   r   s     r]   r   z)ToolCallingAgent.initialize_system_prompt  s@    )!!/2"&"5"5'+'8'8
 rs   r,  c           	   #     K   | j                         }|j                         }||_        	 | j                  rt	        | j
                  d      r| j
                  j                  |ddg| j                        }g }t        d| j                  j                  d      5 }|D ]H  }|j                  |       |j                  t        t        |      j                                      | J 	 ddd       t        |      }n| j
                  j!                  |ddg| j                        }|j"                  "|j$                  t'        |j$                        }	nt'        |j"                        xs d}	| j                  j)                  |	d	t*        j,                  
       ||_        |j"                  |_        |j2                  |_        |j8                  t;        |j8                        dk(  r	 | j
                  j=                  |      }n?|j8                  D ]0  }tA        |jB                  jD                        |jB                  _"        2 d\  }}| jG                  ||      D ]  }| tI        |tJ              s|jL                  s%|rtO        d| j                        |jP                  }d}tI        |t&              s\|| jR                  jU                         v sy| jR                  |   } tW        ||       y# 1 sw Y   xY w# t4        $ r}
t7        d|
 | j                        |
d}
~
ww xY w# t4        $ r}
t?        d|
 | j                        d}
~
ww xY ww)r`  r8  Observation:Calling tools:)r9  tools_to_call_fromr   r:  r;  NOutput message of the LLM:r   r   r   zError while generating output:
r   z1Error while parsing tool call from model output: r  zPYou returned multiple final answers. Please return only one single final answer!Trm   rn   ),rI  copyrB  r   r  r   r8  r  r   r   r<  r   r   r   r:   render_as_markdownrF  r   rawry   log_markdownr>   DEBUGrD  rc  r   re   rH   
tool_callsr   parse_tool_callsrJ   r;   function	argumentsprocess_tool_callsr   ru   rn   rL   rm   r   r   rl   )rZ   r,  rR  rL  rN  chat_message_stream_deltasrO  rP  rm  log_contentri   rx   r   got_final_answerrm   s                  r]   r  zToolCallingAgent._step_stream  s<     779(--/ ,:('	c""wtzz;L'M $

 : :"$24D#E'+'D'D !; ! LN*"dkk&9&9YW $[_!. $299%@$%>?Y%Z%m%m%op $$$  99ST,0JJ,?,?"$24D#E'+'D'D -@ -
  ''/L4D4D4P"%l&6&6"7K"%l&:&:";"ArK(('6".. )  0<K,'3';';K$&2&>&>K# ""*c,2I2I.Ja.On#zz::<H *44 b	/CIDVDVD`D`/a	"",b)4&&--lKH 	@FL&*-))'5n KK  $*==L'+$ ",4IZ9Z'+zz,'?	@ ,
 	
q$ $:  	c&)I!'Mt{{[abb	c  n'*[\][^(_aealalmmns   (MA0L AK5*CL $M)L- A.M3M 6M7M!M5K?:L 	L*L%%L**M-	M6MMMrm  c              #      K   i }|j                   J |j                   D ]U  }t        |j                  j                  |j                  j                  |j
                        }| |||j
                  <   W dt        dt        f fd}i }t        |      dk(  r8t        |j                               d   } ||      }|||j
                  <   | nt         j                        5 }	|j                         D cg c]  }|	j                  ||       }
}t        |
      D ]%  }|j                         }|||j
                  <   | ' 	 ddd       t        |j!                               D cg c]  }||   	 c}|_         |j"                  xs d|_        |j$                  xs d|_        t        |j!                               D cg c]  }||   	 c}D ]w  }d	|j
                   d
|j&                  j                   d|j&                  j                   d}|xj"                  |z  c_        |xj$                  |j(                  dz   z  c_        y |j"                  j+                  d      |_        |j$                  r!|j$                  j+                  d      |_        y|j$                  |_        yc c}w # 1 sw Y   kxY wc c}w c c}w w)a\  Process tool calls from the model output and update agent memory.

        Args:
            chat_message (`ChatMessage`): Chat message containing tool calls from the model.
            memory_step (`ActionStep)`: Memory ActionStep to update with results.

        Yields:
            `ToolCall | ToolOutput`: The tool call or tool output.
        Nr   r!  rv   rx   rS   c           
      ^   | j                   }| j                  xs i }j                  j                  t	        t        d| d|             t        j                         j                  ||      }t        |      }|t        t        fv r-|t        k(  rd}n|t        k(  rd}|j                  <   d| d}nt        |      j                         }j                  j                  d|j                  d	d
       t        j                         |dk(  }t!        | j"                  ||||       S )NzCalling tool: '' with arguments: r   z	image.pngz	audio.mp3zStored 'z' in memory.zObservations: [r  r   )rv   rm   rn   rw   rx   )r   r!  r   r   r   r   r>   r	  execute_tool_callrf   r!   r    r   ry   rY   replaceru   rv   )	rx   r  tool_argumentstool_call_resulttool_call_result_typeobservation_namerw   rn   rZ   s	           r]   process_single_tool_callzEToolCallingAgent.process_tool_calls.<locals>.process_single_tool_call?  s1   !I&006BNKKOOd_YK7I.IYZ[\mm    $55iP$()9$:!$Z(@@(J6'2$*j8'2$/?

+, ()9(:,G!"2399;KKOO !4!4S#!> ?@mm   (>9O<<' /'# rs   r   r   r   z
Tool call z: calling 'r)  ru  )r  r3   r   r   r!  rv   ru   r   r   r   r   r  submitr   rx  r  r   rc  observationsrx   rw   rstrip)rZ   rm  r,  parallel_callschat_tool_callrx   r1  outputstool_outputexecutorfuturesfuturer  rz  s   `             r]   r"  z#ToolCallingAgent.process_tool_calls)  s     /1&&222*55 	5N #,,11^=T=T=^=^cqctctI O+4N9<<(	5	 	Z 	D ~!#^2245a8I29=K&1GKNN# $D$9$9: &hZhZoZoZqMVHOO$<iH  +73 &F"(--/K.9GKNN+%%&	& >DNDWDWDY=Z![."3![#.#;#;#Ar #.#;#;#Ar 06w||~0FG1GAJG 	GK";>>"2+k>S>S>X>X=YYklw  mB  mB  mL  mL  lM  MO  PG$$/$$$(?(?$(FF$	G $/#;#;#B#B4#H 5@5M5MK$$++D1 	 S^SkSk 	 !& & "\ HsJ   C$K	'J2:J-5J2	#K	,J?8AK	KCK	-J22J<7K	r!  c           	          t        |t              rP|j                         D ci c]4  \  }}|t        |t              r| j                  j                  ||      n|6 c}}S |S c c}}w )zWReplace string values in arguments with their corresponding state values if they exist.)r   r   r   ry   r   r  )rZ   r!  r   r   s       r]   _substitute_state_variablesz,ToolCallingAgent._substitute_state_variables  sa    i& #,//"3C Zs5KTZZ^^E51QVV  	s   9A#r  c           
      r   i | j                   | j                  }||vr,t        d| ddj                  |       d| j                        ||   }| j                  |      }|| j                  v }t        ||      }|rt        || j                        	 t        |t              r|r |di |S  |di |ddiS |r ||      S  ||d      S # t        $ r_}|rd| d	t        |       d
| d}n+d| d	t        |       d
t        |      j                   d
| d	}t        || j                        |d}~ww xY w)ag  
        Execute a tool or managed agent with the provided arguments.

        The arguments are replaced with the actual values from the state if they refer to state variables.

        Args:
            tool_name (`str`): Name of the tool or managed agent to execute.
            arguments (dict[str, str] | str): Arguments passed to the tool call.
        zUnknown tool z, should be one of: z, r   sanitize_inputs_outputsT)r?  z(Error executing request to team member 'z' with arguments rb   z3
Please try again or request to another team memberzError executing tool 'z%
Please try again or use another toolNrc   )r   r   rL   r  r   r=  rD   rK   r   r   re   ry   rf   rg   )rZ   r  r!  available_toolsr   is_managed_agent	error_msgri   s           r]   r+  z"ToolCallingAgent.execute_tool_call  s    @TZZ?4+>+>?O+)	{*>tyy?Y>ZZ[\^b^i^i 
 y)44Y?	$(;(;;+D)<	$Y<<	I)T*,<t(i(q$BqBqlpBqq*:tImYhl@mm 	I>ykIZ[^_h[iZjjlmnlo pI I  -YK7HYHXXZ[_`a[b[k[kZllnopnq r; ;  *)T[[AqH	Is+   C .C :	C 	C 	D6AD11D6)NNFN)rg   ro   rp   r   r   rC   r9   r   r  rr   r   r  r  ry   r   r)   r   r6   r3   ru   rl   r  r5   r"  r   r   r=  r+  __classcell__r   s   @r]   r   r     s?   & 48(,$'+1Dz1 1 *D0	1
 :1 1 *1: N N	# 	S
%S
	)H4zALP	QS
jT
'T
6@T
	8j(	)T
lT#s(^c5I dSVX[S[n_bNb -I3 -I4S>C;O -ITW -Irs   r   c                   ^    e Zd ZdZ	 	 	 	 	 	 	 	 	 	 ddee   dededz  dee   dz  de	dz  de
d	   d
eeef   dz  de	dz  dededeeef   dz  deeeef   z  dz  f fdZd Zd Zd ZdefdZdefdZdedeeez  ez  ez     fdZdeeef   f fdZedeeef   dd f fd       Z xZ S )	CodeAgenta  
    In this agent, the tool calls will be formulated by the LLM in code format, then parsed and executed.

    Args:
        tools (`list[Tool]`): [`Tool`]s that the agent can use.
        model (`Model`): Model that will generate the agent's actions.
        prompt_templates ([`~agents.PromptTemplates`], *optional*): Prompt templates.
        additional_authorized_imports (`list[str]`, *optional*): Additional authorized imports for the agent.
        planning_interval (`int`, *optional*): Interval at which the agent will run a planning step.
        executor_type (`Literal["local", "e2b", "docker", "wasm"]`, default `"local"`): Type of code executor.
        executor_kwargs (`dict`, *optional*): Additional arguments to pass to initialize the executor.
        max_print_outputs_length (`int`, *optional*): Maximum length of the print outputs.
        stream_outputs (`bool`, *optional*, default `False`): Whether to stream outputs during execution.
        use_structured_outputs_internally (`bool`, default `False`): Whether to use structured generation at each action step: improves performance for many models.

            <Added version="1.17.0"/>
        grammar (`dict[str, str]`, *optional*): Grammar used to parse the LLM output.
            <Deprecated version="1.17.0">
            Parameter `grammar` is deprecated and will be removed in version 1.20.
            </Deprecated>
        code_block_tags (`tuple[str, str]` | `Literal["markdown"]`, *optional*): Opening and closing tags for code blocks (regex strings). Pass a custom tuple, or pass 'markdown' to use ("```(?:python|py)", "\n```"), leave empty to use ("<code>", "</code>").
        **kwargs: Additional keyword arguments.
    Nr   r   r   additional_authorized_importsr   executor_type)locale2bdockerwasmexecutor_kwargsmax_print_outputs_lengthr   !use_structured_outputs_internallyr   code_block_tagsc           	         |r|ng | _         t        t        t              t        | j                         z        | _        || _        |
| _        |
rT|xsO t        j                  t        j                  j                  d      j                  d      j                               }nS|xsO t        j                  t        j                  j                  d      j                  d      j                               }|r|
rt        d      t        |t               r|dk(  st        d      t        |t"              r|n|dk(  rdnd| _        t'        | P  d|||||d	| |	| _        | j*                  r!t-        | j.                  d
      st        d      d| j                   v r+| j0                  j3                  dt4        j6                         |dvrt        d|       || _        |xs i | _        | j=                         | _        y )Nr  zstructured_code_agent.yamlzcode_agent.yamlzRYou cannot use 'grammar' and 'use_structured_outputs_internally' at the same time.markdownzHOnly 'markdown' is supported for a string argument to `code_block_tags`.)z	```pythonz```)z<code>z</code>)r   r   r   r   r   r8  r  *zCaution: you set an authorization for all imports, meaning your agent can decide to import any package it deems necessary. This might raise issues if the package is not installed in your environment.r   >   rJ  rL  rI  rK  zUnsupported executor type: rc   ) rG  r  r   r%   r  rN  "_use_structured_outputs_internallyr  r  r  r	  r
  r  r  r   r   ry   r  rP  r  r   r   r  r   r   r   r>   r	  rH  rM  create_python_executorr   )rZ   r   r   r   rG  r   rH  rM  rN  r   rO  r   rP  rv  r   s                 r]   r   zCodeAgent.__init__  s     Ol-Jqs*"(-A)BSIkIkEl)l"m(@%2S/,/  4>>##))*>?HHIefppr4  0  4>>##))*>?HHIZ[eeg4 8qrros+Oz4Qghh /51  *, && 	 	 	
-/	
 	
 -wtzz;L'Mn  $444KKOO Zmm    BB:=/JKK*/>/D"#::<rs   c                     | S r   rc   r   s    r]   	__enter__zCodeAgent.__enter__  s    rs   c                 $    | j                          y r   )cleanup)rZ   exc_type	exc_value	tracebacks       r]   __exit__zCodeAgent.__exit__  s    rs   c                 f    t        | j                  d      r| j                  j                          yy)zIClean up resources used by the agent, such as the remote Python executor.rY  N)r  r   rY  r   s    r]   rY  zCodeAgent.cleanup  s)    4''3  ((* 4rs   rS   c                 :   | j                   dk(  r/t        | j                  fi d| j                  i| j                  z  S | j
                  rt        d      t        t        t        d} || j                      | j                  | j                  fi | j                  S )NrI  rN  z@Managed agents are not yet supported with remote code execution.)rJ  rK  rL  )rH  r&   rG  rN  rM  r   re   rA   r@   rB   r   )rZ   remote_executorss     r]   rU  z CodeAgent.create_python_executor  s    (&22-t/L/LMPTPdPdd 
 "" bcc"($ 
 8#D$6$6722DKKCGCWCW rs   c           
          t        | j                  d   | j                  | j                  d| j                  v rdnt        | j                        | j                  | j                  d   | j                  d   d      }|S )Nr   rS  z)You can import from any package you want.r   r   )r   r   r  r  code_block_opening_tagcode_block_closing_tagr   )rj   r   r   r   r  ry   r   rP  r  s     r]   r   z"CodeAgent.initialize_system_prompt/  s    )!!/2"&"5"5 d555 @T445'+'8'8*.*>*>q*A*.*>*>q*A
 rs   r,  c           	   #     K   | j                         }|j                         }||_        ddg}| j                  d   | j                  d   vr|j	                  | j                  d          	 i }| j
                  r| j
                  |d<   | j                  r	t        |d<   | j                  r | j                  j                  |fd|i|}g }t        d| j                  j                  d	
      5 }|D ]H  }	|j	                  |	       |j                  t        t!        |      j#                                      |	 J 	 ddd       t!        |      }
|
|_        |
j&                  }n^ | j                  j(                  |fd|i|}
|
|_        |
j&                  }| j                  j+                  |dt,        j.                         |rO|j1                         j3                  | j                  d         s#|| j                  d   z  }||j$                  _        |
j4                  |_        ||_        	 | j                  r3t=        j>                  |      d   }tA        || j                        xs |}ntC        || j                        }tE        |      }||_#        tK        d|dtM        | jN                  jP                               }| |g|_)        | j                  jU                  d|t,        jV                         	 | jY                  |      }g }tM        |jZ                        dkD  r%|t]        dd      t]        |jZ                        gz  }d|jZ                  z   }tm        tc        |jn                              }|d!|z   z  }||_2        |jp                  s|t]        d"|       gz  }| j                  jg                  ti        | t,        jV                         |jn                  |_9        tu        |jn                  |jp                  #       y# 1 sw Y   xY w# t8        $ r}t;        d| | j                        |d}~ww xY w# t8        $ r!}d| d}tI        || j                        d}~ww xY w# t8        $ r
}t_        | jX                  d      rd| jX                  j`                  v rtc        | jX                  j`                  d         }tM        |      dkD  rSt]        dd      t]        |      g}d|z   |_2        | j                  jg                  ti        | t,        jV                         tc        |      }d|v r/d|v r+| j                  jg                  d t,        jV                         tk        || j                        d}~ww xY ww)$r`  r  r  r   r   r   response_formatr9  r   r:  r;  Nr  r  z"Error in generating model output:
r  zError in code parsing:
z)
Make sure to provide correct code blobs.r   call_r'  zExecuting parsed code:)r   r   r   zExecution logs:boldr  zExecution logs:
r   _print_outputsr   z
Import of z is not allowedz[bold red]Warning to user: Code execution failed due to an unauthorized import - Consider passing said import under `additional_authorized_imports` when initializing your CodeAgent.zLast output from code snippet:
zOut: r  );rI  r  rB  rP  r   r   rT  r4   r   r   r8  r   r   r<  r   r   r:   r  rD  r   rF  r  r>   r  rY   endswithr   rc  re   rH   r  r  rM   rP   r(   code_actionrJ   r3   r   r   r
  r  log_coder	  r   rX  r   r  r   ry   r3  r   r   rG   rQ   rm   rn   r1  rl   )rZ   r,  rR  rL  r9  r   rN  r#  rO  rP  rm  output_textri   rj  rB  rx   code_outputexecution_outputs_consolerw   execution_logstruncated_outputs                        r]   r  zCodeAgent._step_streamA  s_     779(--/+9((*:;"$*>*>q*AA!!$"6"6q"9:.	f.0O||-1\\	*665N 12"" :

 : :"!#1! &!
 LN*"dkk&9&9YW $[_!. $299%@$%>?Y%Z%m%m%op $$$  99ST3?0*22,?DJJ,?,?"-#1- &-
 4@0*22(('6".. )  ;#4#4#6#?#?@T@TUV@W#Xt33A66;F008&2&>&>K#'2K$

	<66"jj5f=4[$BVBVWf[f.{D<P<PQ/<K&1K#
 %!s4;;,,-./
	
 "+ 	#;[X`XeXef	>..{;K(*%;##$q()*&9))*. ) .0@0@@K& ,C0B0B,CD9<LLL#. **%,-.* %
 	89O$/$6$6!+"4"4kFaFabbC$ $@  	f&)LQC'PRVR]R]^dee	f  	<21#5_`I#It{{;;	<.  	>t++W5:JdNbNbNhNh:h!$T%9%9%?%?@P%Q!R~&*.f=^,1- 0C^/SK,KKOOE+D$EX]]O[AIy(->)-K L"--    &i==!	>s   A(V+BP ,AP;C.P *A'Q  A&V8AQ- B1VPP 	P=P88P==V 	Q*	Q%%Q**V-
V7DU<<VVc                     t         |          }| j                  |d<   | j                  |d<   | j                  |d<   | j
                  |d<   |S )r  r  rH  rM  rN  )r  r  r  rH  rM  rN  )rZ   r  r   s     r]   r  zCodeAgent.to_dict  sZ     W_&
+/+B+B
'(&*&8&8
?#(,(<(<
$%151N1N
-.rs   r  c                 D   |j                  d      |j                  d      |j                  d      |j                  d      |j                  d      d}|j                         D ci c]  \  }}|	|| }}}|j                  |       t        |   |fi |S c c}}w )aB  Create CodeAgent from a dictionary representation.

        Args:
            agent_dict (`dict[str, Any]`): Dictionary representation of the agent.
            **kwargs: Additional keyword arguments that will override agent_dict values.

        Returns:
            `CodeAgent`: Instance of the CodeAgent class.
        r  rH  rM  rN  rP  )rG  rH  rM  rN  rP  )r  r   r   r  r  )r   r  rv  code_agent_kwargsr  r  r   s         r]   r  zCodeAgent.from_dict  s     .8^^<P-Q'^^O<)~~.?@(27Q(R)~~.?@
 /@.E.E.GYda1=QTYY  (w A/@AA	 Zs   (
B3B)
NNNrI  NNFFNN)!rg   ro   rp   r   r   rC   r9   r   ry   r  r   r   r   rr   r  r   rW  r]  rY  r'   rU  r   r)   r   r6   r3   ru   rl   r  r  r  r  rC  rD  s   @r]   rF  rF    s   8 48:>(,CJ15/3$27)-8<?=Dz?= ?= *D0	?=
 (,Cy4'7?= :?= ?@?= c3h$.?= #&*?= ?= ,0?= c3h$&?= uS#X.5?=B+
 $# $c%c	)H4zALP	QcBc3h  B4S> B B Brs   rF  )r  r  r  rU   r  rG  r  r   abcr   r   collections.abcr   r   concurrent.futuresr   r   dataclassesr	   loggingr
   pathlibr   typingr   r   r   r   r   r   r   r  r  huggingface_hubr   r   r   r   r   r   rich.consoler   	rich.liver   rich.markdownr   
rich.panelr   	rich.ruler   	rich.textr   	PIL.ImagePILagent_typesr    r!   r"   default_toolsr#   r$   local_python_executorr%   r&   r'   r(   r   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   modelsr4   r5   r6   r7   r8   r9   r:   r;   
monitoringr<   r=   r>   r?   r`  r@   rA   rB   r   rC   rD   utilsrE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rg   r   ry   r   r^   r   rj   rl   ru   r{   r   r   r   r   r   r   rq   r   r   rF  rc   rs   r]   <module>r     s  "   	 	     # / ? !   Q Q Q   Z Z ,   "     J J 8 s s   	 	 	  H G 0   " 
8	Ls Ls3x L
[ [S#X [3 [   
   #Y #
 

	 
,i ," )#!#"$
 -"R@*"M	    $ 	Y 	mS m`^I~ ^IB	oB oBrs   