o
    h                     @  s  d dl mZ d dlZd dlZd dl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mZ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 d d	lm Z  d d
l!m"Z"m#Z# d dl$m%Z%m&Z&m'Z'm(Z(m)Z) d dl*m+Z+ ddl,m-Z-m.Z. ddl/m0Z0 ddl1m2Z2m3Z3 ddl4m5Z5m6Z6m7Z7m8Z8m9Z9 ddl:m;Z;m<Z<m=Z=m>Z> ddl?m@Z@mAZA ddlBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZO ddlPmQZQ ddlRmRZR ddlSmTZT ddlUmVZV ddlWmXZXmYZY ddlZm[Z[m\Z\ ddl]m^Z^m_Z_m`Z`maZambZbmcZcmdZdmeZemfZf ddlgmhZh ddlimjZjmkZkmlZlmmZm ddlnmoZompZpmqZqmrZrmsZsmtZtmuZu ddlvmwZwmxZx e
r?dd lymzZz G d!d" d"Z{e{ Z|e.d#dd$Z}eG d%d& d&Z~eG d'd( d(ZeG d)d* d*ZeG d+d, d,ZeG d-d. d.ZeG d/d0 d0ZeG d1d2 d2ZeG d3d4 d4ZeG d5d6 d6ZeG d7d8 d8ZeG d9d: d:ZdOd@dAZG dBdC dCZG dDdE dEZG dFdG dGZG dHdI dIZdPdMdNZdS )Q    )annotationsN)	Awaitable)	dataclassfield)TYPE_CHECKINGAnycast)ResponseComputerToolCallResponseFileSearchToolCallResponseFunctionToolCallResponseFunctionWebSearchResponseOutputMessage)ResponseCodeInterpreterToolCall)	ActionClickActionDoubleClick
ActionDragActionKeypress
ActionMoveActionScreenshotActionScroll
ActionType
ActionWait))ComputerCallOutputAcknowledgedSafetyCheck)ComputerCallOutputMcpApprovalResponse)ImageGenerationCallLocalShellCallMcpApprovalRequestMcpCallMcpListTools)ResponseReasoningItem   )AgentToolsToFinalOutputResult)AgentOutputSchemaBase)AsyncComputerComputer)AgentsExceptionModelBehaviorError#ToolInputGuardrailTripwireTriggered$ToolOutputGuardrailTripwireTriggered	UserError)InputGuardrailInputGuardrailResultOutputGuardrailOutputGuardrailResult)HandoffHandoffInputData)HandoffCallItemHandoffOutputItemItemHelpersMCPApprovalRequestItemMCPApprovalResponseItemMCPListToolsItemMessageOutputItemModelResponseReasoningItemRunItemToolCallItemToolCallOutputItemTResponseInputItem)RunHooks)logger)ModelSettings)ModelTracing)RunContextWrapperTContext)RunItemStreamEventStreamEvent)	ComputerToolComputerToolSafetyCheckDataFunctionToolFunctionToolResultHostedMCPToolLocalShellCommandRequestLocalShellToolMCPToolApprovalRequestTool)ToolContext)ToolInputGuardrailDataToolInputGuardrailResultToolOutputGuardrailDataToolOutputGuardrailResult)	SpanErrorTracefunction_spanget_current_traceguardrail_spanhandoff_spantrace)_coro_error_tracing)	RunConfigc                   @     e Zd ZdS )QueueCompleteSentinelN__name__
__module____qualname__ re   re   Q/var/www/html/openai_agents/venv/lib/python3.10/site-packages/agents/_run_impl.pyr`   n   s    r`   Fis_final_outputfinal_outputc                   @  s6   e Zd ZU eedZded< 	 dd
dZdddZdS )AgentToolUseTracker)default_factoryzlist[tuple[Agent, list[str]]]agent_to_toolsagent
Agent[Any]
tool_names	list[str]returnNonec                   sD   t  fdd| jD d }|r|d | d S | j |f d S )Nc                 3       | ]}|d   kr|V  qdS r   Nre   .0itemrm   re   rf   	<genexpr>}       z3AgentToolUseTracker.add_tool_use.<locals>.<genexpr>r!   )nextrl   extendappend)selfrm   ro   existing_datare   rx   rf   add_tool_use|   s   z AgentToolUseTracker.add_tool_useboolc                   s2   t  fdd| jD d }|d uot|d dkS )Nc                 3  rs   rt   re   ru   rx   re   rf   ry      rz   z5AgentToolUseTracker.has_used_tools.<locals>.<genexpr>r!   r   )r{   rl   len)r~   rm   r   re   rx   rf   has_used_tools   s   z"AgentToolUseTracker.has_used_toolsN)rm   rn   ro   rp   rq   rr   )rm   rn   rq   r   )	rb   rc   rd   r   listrl   __annotations__r   r   re   re   re   rf   rj   w   s
   
 
rj   c                   @     e Zd ZU ded< ded< dS )ToolRunHandoffr0   handoffr   	tool_callNrb   rc   rd   r   re   re   re   rf   r         
 r   c                   @  r   )ToolRunFunctionr   r   rI   function_toolNr   re   re   re   rf   r      r   r   c                   @  r   )ToolRunComputerActionr	   r   rG   computer_toolNr   re   re   re   rf   r      r   r   c                   @  r   )ToolRunMCPApprovalRequestr   request_itemrK   mcp_toolNr   re   re   re   rf   r      r   r   c                   @  r   )ToolRunLocalShellCallr   r   rM   local_shell_toolNr   re   re   re   rf   r      r   r   c                   @  sP   e Zd ZU ded< ded< ded< ded< d	ed
< ded< ded< dddZdS )ProcessedResponselist[RunItem]	new_itemslist[ToolRunHandoff]handoffslist[ToolRunFunction]	functionslist[ToolRunComputerAction]computer_actionslist[ToolRunLocalShellCall]local_shell_callsrp   
tools_usedlist[ToolRunMCPApprovalRequest]mcp_approval_requestsrq   r   c                 C  s   t | j| j| j| j| jgS N)anyr   r   r   r   r   r~   re   re   rf   has_tools_or_approvals_to_run   s   z/ProcessedResponse.has_tools_or_approvals_to_runN)rq   r   )rb   rc   rd   r   r   re   re   re   rf   r      s   
 r   c                   @     e Zd ZU ded< dS )NextStepHandoffrn   	new_agentNr   re   re   re   rf   r         
 r   c                   @  r   )NextStepFinalOutputr   outputNr   re   re   re   rf   r      r   r   c                   @  r_   )NextStepRunAgainNra   re   re   re   rf   r      s    r   c                   @  sb   e Zd ZU ded< 	 ded< 	 ded< 	 ded< 	 ded	< 	 d
ed< 	 ded< 	 edddZdS )SingleStepResultstr | list[TResponseInputItem]original_inputr9   model_responser   pre_step_itemsnew_step_itemsz8NextStepHandoff | NextStepFinalOutput | NextStepRunAgain	next_steplist[ToolInputGuardrailResult]tool_input_guardrail_resultslist[ToolOutputGuardrailResult]tool_output_guardrail_resultsrq   c                 C  s   | j | j S )z`Items generated during the agent run (i.e. everything generated after
        `original_input`).)r   r   r   re   re   rf   generated_items   s   z SingleStepResult.generated_itemsN)rq   r   )rb   rc   rd   r   propertyr   re   re   re   rf   r      s"   
 r   tracing_disabledr   trace_include_sensitive_datarq   rB   c                 C  s   | rt jS |r
t jS t jS r   )rB   DISABLEDENABLEDENABLED_WITHOUT_DATA)r   r   re   re   rf   get_model_tracing_impl   s
   r   c                   @  s  e Zd ZedmddZednddZedod#d$Zedpd,d-Zedqd2d3Zedrd6d7Z	edsd<d=Z
edtd@dAZedudDdEZedvdIdJZedwdMdNZedxdPdQZedydRdSZedzdYdZZed{d^d_Zed|dbdcZed}dedfZed~djdkZdlS )RunImplrm   Agent[TContext]r   r   r   r   new_responser9   processed_responser   output_schemaAgentOutputSchemaBase | NonehooksRunHooks[TContext]context_wrapperRunContextWrapper[TContext]
run_configr^   rq   r   c       	           s  t |}g }
|
|j t| j||j|||	d| j||j|||	dI d H \\}}}}|
dd |D  |
| |j	rP| j
||j	|dI d H }|
| |j }rf| j||||
|||||	d	I d H S | j||||	dI d H }|jr|jr}|jtu rt|j|_|jd u rtd | j|||||
|j||||d	
I d H S d
d |
D }|rt|d jnd }| s|r| s|r||}| j|||||
|||||d	
I d H S |r| r| j|||||
|pd||||d	
I d H S t||||
t ||dS )N)rm   	tool_runsr   r   config)rm   actionsr   r   r   c                 S  s   g | ]}|j qS re   )run_item)rv   resultre   re   rf   
<listcomp>"  s    z:RunImpl.execute_tools_and_side_effects.<locals>.<listcomp>)rm   approval_requestsr   )	rm   r   r   r   r   run_handoffsr   r   r   )rm   tool_resultsr   r   zhModel returned a final output of None. Not raising an error because we assumeyou know what you're doing.)
rm   r   r   r   r   ri   r   r   r   r   c                 S  s   g | ]	}t |tr|qS re   )
isinstancer8   ru   re   re   rf   r   ]  s     r   r   r   r   r   r   r   )r   r|   r   asynciogatherexecute_function_tool_callsr   execute_computer_actionsr   r   execute_mcp_approval_requestsr   execute_handoffs"_check_for_final_output_from_toolsrh   output_typestrri   r@   errorexecute_final_outputr4   extract_last_textraw_itemr   is_plain_textvalidate_jsonr   r   )clsrm   r   r   r   r   r   r   r   r   r   function_resultsr   r   computer_resultsapproval_resultsr   check_tool_usemessage_itemspotential_final_output_textri   re   re   rf   execute_tools_and_side_effects   s   




z&RunImpl.execute_tools_and_side_effectsrn   tool_use_trackerrj   model_settingsrA   c                 C  s&   |j du r||rtj|ddS |S )znResets tool choice to None if the agent has used tools and the agent's reset_tool_choice
        flag is True.TN)tool_choice)reset_tool_choicer   dataclassesreplace)r   rm   r   r   re   re   rf   maybe_reset_tool_choice  s   zRunImpl.maybe_reset_tool_choice	all_tools
list[Tool]responser   list[Handoff]c             	   C  s"  g }g }g }g }	g }
g }g }dd |D }dd |D }t dd |D d }t dd |D d }dd |D }|jD ]}t|trM|t||d n8t|trb|t||d |d	 n#t|trw|t||d |d
 nt|t	r|t
||d nt|tr|t||d |d |sttdi d td|	t||d nt|tr|t||d |j|vrttdd|jid td|j d||j }|jr|t||d ntd|j d nt|tr|t||d n~t|tr|t||d |d nit|tr1|t||d |d nTt|trF|t||d |d n?t|trt|t||d |d |sjttdi d td|
t||d nt|tstdt |  q:t|tsq:||j! |j!|v r|t"||d t#|||j! d}|| q:|j!|vr|d ur|j!d kr|t||d |t$|t%|d! q:ttd"d#|j!id d$|j! d%|j! }t||t||d |t$|||j! d! q:t&||||	|
||d&S )'Nc                 S  s   i | ]}|j |qS re   )	tool_namerv   r   re   re   rf   
<dictcomp>      z2RunImpl.process_model_response.<locals>.<dictcomp>c                 S  s   i | ]}t |tr|j|qS re   )r   rI   namerv   toolre   re   rf   r     s    c                 s      | ]
}t |tr|V  qd S r   )r   rG   r   re   re   rf   ry         z1RunImpl.process_model_response.<locals>.<genexpr>c                 s  r  r   )r   rM   r   re   re   rf   ry     r  c                 S  s"   i | ]}t |tr|jd  |qS )server_label)r   rK   tool_configr   re   re   rf   r     s    
r   rm   file_search
web_searchcomputer_usezComputer tool not foundmessagedataz7Model produced computer action without a computer tool.)r   r   zMCP server label not foundr  zMCP server label z
 not found)r   r   zMCP server z  has no on_approval_request hookmcpimage_generationcode_interpreterlocal_shellzLocal shell tool not foundz;Model produced local shell call without a local shell tool.)r   r   z"Unexpected output type, ignoring: )r   r   json_tool_call)r   r   zTool not foundr   zTool z not found in agent )r   r   r   r   r   r   r   )'r{   r   r   r   r}   r8   r
   r<   r   r    r:   r	   r]   attach_error_to_current_spanrU   r(   r   r   r5   r  on_approval_requestr   r@   warningr   r7   r   r   r   r   r   r   typer   r2   r   r   _build_litellm_json_tool_callr   )r   rm   r   r   r   r   itemsr   r   r   r   r   r   handoff_mapfunction_mapr   r   hosted_mcp_server_mapr   serverr   r   re   re   rf   process_model_response  s  












	zRunImpl.process_model_response	func_toolrI   tool_contextToolContext[TContext]r   r   
str | Nonec                  s   |j sdS |j D ]:}|t||dI dH }|t||d |jd dkr-t||d|jd dkr;|jd   S |jd dkrCq	q	dS )	a  Execute input guardrails for a tool.

        Args:
            func_tool: The function tool being executed.
            tool_context: The tool execution context.
            agent: The agent executing the tool.
            tool_input_guardrail_results: List to append guardrail results to.

        Returns:
            None if tool execution should proceed, or a message string if execution should be
            skipped.

        Raises:
            ToolInputGuardrailTripwireTriggered: If a guardrail triggers an exception.
        N)contextrm   	guardrailr   r  raise_exceptionreject_contentr  allow)tool_input_guardrailsrunrQ   r}   rR   behaviorr)   )r   r  r  rm   r   r#  gr_outre   re   rf   _execute_input_guardrailsC  s0   

z!RunImpl._execute_input_guardrailsreal_resultr   r   r   c          	        s   |j s|S |}|j D ]<}|t|||dI dH }|t||d |jd dkr0t||d|jd dkr?|jd } |S |jd dkrGqq|S )	a7  Execute output guardrails for a tool.

        Args:
            func_tool: The function tool being executed.
            tool_context: The tool execution context.
            agent: The agent executing the tool.
            real_result: The actual result from the tool execution.
            tool_output_guardrail_results: List to append guardrail results to.

        Returns:
            The final result after guardrail processing (may be modified).

        Raises:
            ToolOutputGuardrailTripwireTriggered: If a guardrail triggers an exception.
        )r!  rm   r   Nr"  r  r$  r%  r  r&  )tool_output_guardrailsr(  rS   r}   rT   r)  r*   )	r   r  r  rm   r,  r   final_resultoutput_guardrailr*  re   re   rf   _execute_output_guardrailsz  s<   

	
z"RunImpl._execute_output_guardrailsr   r   c                  sL   t |||||jr|j|||nt I dH  |||jI dH S )a  Execute the core tool function with before/after hooks.

        Args:
            func_tool: The function tool being executed.
            tool_context: The tool execution context.
            agent: The agent executing the tool.
            hooks: The run hooks to execute.
            tool_call: The tool call details.

        Returns:
            The result from the tool execution.
        N)r   r   on_tool_startr   r\   noop_coroutineon_invoke_tool	arguments)r   r  r  rm   r   r   re   re   rf   _execute_tool_with_hooks  s   
	z RunImpl._execute_tool_with_hooksr   r   r   `tuple[list[FunctionToolResult], list[ToolInputGuardrailResult], list[ToolOutputGuardrailResult]]c                  s|   g g d fdd}g }|D ]}|j }	|||	|j qtj| I d H }
 fd	d
t||
D }|fS )Nr  rI   r   r   rq   r   c           	        sl  t | j}tj|j|d}jr|j|j_zNj	| | dI d H }|d ur,|}n7j
| | |dI d H }j| | |dI d H }t| | | jr[ j| | |nt I d H  |}W n. ty } z"ttd| jt|dd t|tr|td| j d	| |d }~ww jr||j_W d    |S W d    |S 1 sw   Y  |S )
N)r   )r  r  rm   r   )r  r  rm   r   r   )r  r  rm   r,  r   zError running tool)r   r   r
  zError running tool z: )rW   r   rP   from_agent_contextcall_idr   r4  	span_datainputr+  r5  r0  r   r   on_tool_endr   r\   r2  	Exceptionr]   r  rU   r   r   r'   r+   r   )	r  r   span_fnr  rejected_messager.  r,  r   erm   r   r   r   r   r   r   re   rf   run_single_tool  s|   
		




@
@@z<RunImpl.execute_function_tool_calls.<locals>.run_single_toolc                   s8   g | ]\}}t |j|t|t|jt| d dqS )r   r   rm   )r  r   r   )rJ   r   r=   r4   tool_call_output_itemr   r   )rv   tool_runr   rx   re   rf   r   4  s    
z7RunImpl.execute_function_tool_calls.<locals>.<listcomp>)r  rI   r   r   rq   r   )r   r}   r   r   r   zip)r   rm   r   r   r   r   rA  tasksrD  r   resultsfunction_tool_resultsre   r@  rf   r     s   E


z#RunImpl.execute_function_tool_callscallsr   c             
     s4   g }|D ]}| tj|||||dI d H  q|S )N)rm   callr   r   r   )r}   LocalShellActionexecute)r   rm   rI  r   r   r   rG  rJ  re   re   rf   execute_local_shell_callsC  s   

	z!RunImpl.execute_local_shell_callsr   r   c                  s   g }|D ]T}d }|j jrH|jjrHg }|j jD ]0}	t|||j |	d}
|j|
}t|r2|I d H n|}|rD|t|	j	|	j
|	jd qtd|tj||||||dI d H  q|S )N)ctx_wrapperrm   r   safety_check)idcoder  z/Computer tool safety check was not acknowledged)rm   actionr   r   r   acknowledged_safety_checks)r   pending_safety_checksr   on_safety_checkrH   inspectisawaitabler}   r   rP  rQ  r  r+   ComputerActionrL  )r   rm   r   r   r   r   rG  rR  acknowledgedcheckr  maybeackre   re   rf   r   [  sF   

z RunImpl.execute_computer_actionsr   r   r   c       	           s,  t |dk}
|
rd| fdd|dd  D  |d }t jd}|j}|||jjI d H }|j|j_	|
rNdd |D }|
tdd	|id
 |t t|j|| |d t|j| |d jrv jj|| dnt I d H  |jp|	r|	jnd }|rtd tt|trt|n|t|t||d}t|st !|tdddid
 t"d| ||}t#$|r|I d H }t|tst !|tdddid
 t"d| t|j%t&r|j%nt|j%}t|j'}t|j(}W d    n	1 sw   Y  t)||||t*|g g dS )Nr!   z.Multiple handoffs detected, ignoring this one.c                   s$   g | ]}t t|j d qS )rB  )r=   r4   rC  r   r   rm   output_messagere   rf   r     s    z,RunImpl.execute_handoffs.<locals>.<listcomp>r   )
from_agentc                 S  s   g | ]}|j jqS re   )r   
agent_namer   re   re   rf   r     r   zMultiple handoffs requestedrequested_agentsr
  )rm   r   source_agenttarget_agent)r!  r_  to_agent)rm   sourcezFiltering inputs for handoff)input_historypre_handoff_itemsr   run_contextzInvalid input filterdetailsznot callable()zInvalid input filter: zInvalid input filter resultznot a HandoffInputDatazInvalid input filter result: r   )+r   r|   rZ   r   r   on_invoke_handoffr   r4  r9  rd  	set_errorrU   r}   r3   r4   rC  get_transfer_messager   r   
on_handoffr   r\   r2  input_filterhandoff_input_filterr@   debugr1   r   r   tuplecallabler]   attach_error_to_spanr+   rV  rW  rf  r   rg  r   r   r   )r   rm   r   r   r   r   r   r   r   r   multiple_handoffsactual_handoffspan_handoffr   r   ra  rn  handoff_input_datafilteredre   r]  rf   r     s   












\zRunImpl.execute_handoffsr   r   c                  s4   d	 fddfdd|D }t j| I d H S )
Napproval_requestr   rq   r;   c                   s   | j j}|d usJ d|t| j}t|r |I d H }n|}|dd }| jj|d dd}|d s<|r<||d< t| dS )Nz.Callback is required for MCP approval requestsreasonapprovemcp_approval_response)approval_request_idr{  r  r  )	r   r  rN   r   rV  rW  getrP  r6   )ry  callbackmaybe_awaitable_resultr   rz  r   )rm   r   re   rf   run_single_approval  s(   

zBRunImpl.execute_mcp_approval_requests.<locals>.run_single_approvalc                   s   g | ]} |qS re   re   )rv   ry  )r  re   rf   r   1  r   z9RunImpl.execute_mcp_approval_requests.<locals>.<listcomp>)ry  r   rq   r;   )r   r   )r   rm   r   r   rF  re   )rm   r   r  rf   r     s   z%RunImpl.execute_mcp_approval_requestsri   c       
      	     s2   |  ||||I d H  t||||t||	|
dS )Nr   )run_final_output_hooksr   r   )r   rm   r   r   r   r   ri   r   r   r   r   re   re   rf   r   4  s   zRunImpl.execute_final_outputc                   s<   t |||||jr|j|||nt I d H  d S r   )r   r   on_agent_endr   on_endr\   r2  )r   rm   r   r   ri   re   re   rf   r  P  s   zRunImpl.run_final_output_hooksr#  InputGuardrail[TContext]r:  r!  r-   c                   sV   t | }||||I d H }|jj|j_|W  d    S 1 s$w   Y  d S r   rY   get_namer(  r   tripwire_triggeredr9  	triggered)r   rm   r#  r:  r!  span_guardrailr   re   re   rf   run_single_input_guardrail_  s   $z"RunImpl.run_single_input_guardrailOutputGuardrail[TContext]agent_outputr/   c                   sX   t | }|j|||dI d H }|jj|j_|W  d    S 1 s%w   Y  d S )N)rm   r  r!  r  )r   r#  rm   r  r!  r  r   re   re   rf   run_single_output_guardraill  s   $z#RunImpl.run_single_output_guardrailqueue2asyncio.Queue[StreamEvent | QueueCompleteSentinel]c                 C  s   |D ]u}t |trt|dd}n`t |trt|dd}nTt |tr(t|dd}nHt |tr4t|dd}n<t |tr@t|dd}n0t |trLt|dd}n$t |trXt|dd}nt |t	rdt|d	d}nt
d
t|  d }|rw|| qd S )Nmessage_output_created)rw   r   handoff_requestedhandoff_occuredtool_calledtool_outputreasoning_item_createdmcp_approval_requestedmcp_list_toolszUnexpected item type: )r   r8   rE   r2   r3   r<   r=   r:   r5   r7   r@   r  r  
put_nowait)r   r   r  rw   eventre   re   rf   stream_step_items_to_queuey  s.   








z"RunImpl.stream_step_items_to_queuestep_resultc                 C  s   |  |j| d S r   )r  r   )r   r  r  re   re   rf   stream_step_result_to_queue  s   z#RunImpl.stream_step_result_to_queuer   list[FunctionToolResult]r#   c                  s   |st S |jdkrt S |jdkrtd|d jdS t|jtrA|jdg }|D ]}|jj|v r:td|jd  S q)tdddS t	|jrct
|jrZttt |||I dH S tt|||S td	|j  td	|j )
zDetermine if tool results should produce a final output.
        Returns:
            ToolsToFinalOutputResult: Indicates whether final output is ready, and the output value.
        run_llm_againstop_on_first_toolTr   rg   stop_at_tool_namesFNzInvalid tool_use_behavior: )_NOT_FINAL_OUTPUTtool_use_behaviorr#   r   r   dictr~  r  r   rr  rV  iscoroutinefunctionr   r   r@   r   r+   )r   rm   r   r   r   namestool_resultre   re   rf   r     s:   






z*RunImpl._check_for_final_output_from_toolsN)rm   r   r   r   r   r   r   r9   r   r   r   r   r   r   r   r   r   r^   rq   r   )rm   rn   r   rj   r   rA   rq   rA   )rm   rn   r   r   r   r9   r   r   r   r   rq   r   )
r  rI   r  r  rm   r   r   r   rq   r   )r  rI   r  r  rm   r   r,  r   r   r   rq   r   )r  rI   r  r  rm   r   r   r   r   r   rq   r   )rm   r   r   r   r   r   r   r   r   r^   rq   r6  )rm   r   rI  r   r   r   r   r   r   r^   rq   r   )rm   r   r   r   r   r   r   r   r   r^   rq   r   )rm   r   r   r   r   r   r   r   r   r9   r   r   r   r   r   r   r   r^   rq   r   )rm   r   r   r   r   r   rq   r   )rm   r   r   r   r   r9   r   r   r   r   ri   r   r   r   r   r   r   r   r   r   rq   r   )rm   r   r   r   r   r   ri   r   )
rm   rn   r#  r  r:  r   r!  r   rq   r-   )
r#  r  rm   rn   r  r   r!  r   rq   r/   )r   r   r  r  )r  r   r  r  )
rm   r   r   r  r   r   r   r^   rq   r#   )rb   rc   rd   classmethodr   r   r  r+  r0  r5  r   rM  r   r   r   r   r  r  r  r  r  r   re   re   re   rf   r      sP      *6< j0 !r   c                   @  s,   e Zd ZdZdddZdddZdd ZdS )TraceCtxManagerzSCreates a trace only if there is no current trace, and manages the trace lifecycle.workflow_namer   trace_idr   group_idmetadatadict[str, Any] | Nonedisabledr   c                 C  s(   d | _ || _|| _|| _|| _|| _d S r   )r[   r  r  r  r  r  )r~   r  r  r  r  r  re   re   rf   __init__  s   
zTraceCtxManager.__init__rq   c                 C  s:   t  }|st| j| j| j| j| jd| _| jjdd | S )N)r  r  r  r  r  T)mark_as_current)rX   r[   r  r  r  r  r  start)r~   current_tracere   re   rf   	__enter__  s   zTraceCtxManager.__enter__c                 C  s   | j r| j jdd d S d S )NT)reset_current)r[   finish)r~   exc_typeexc_valexc_tbre   re   rf   __exit__  s   zTraceCtxManager.__exit__N)
r  r   r  r   r  r   r  r  r  r   )rq   r  )rb   rc   rd   __doc__r  r  r  re   re   re   rf   r    s
    

r  c                   @  s<   e Zd ZedddddZedddZedddZdS ) rX  N)rS  rm   r   rR  r   r   r   r   r   r   r^   rS  6list[ComputerCallOutputAcknowledgedSafetyCheck] | Nonerq   r;   c             	     s   t |jjtr| |jj|jn| |jj|j}t|	|||j|j
r/|j
	|||jnt |I d H \}}}	t||||j|	|j
rR|j
|||j|	nt I d H  d|	 }
t||
t|jjd|
dd|ddS )Nzdata:image/png;base64,computer_screenshot)r  	image_urlcomputer_call_output)r8  r   r  rS  rm   r   r   )r   r   computerr%   _get_screenshot_asyncr   _get_screenshot_syncr   r   r1  r   r\   r2  r;  r=   r   r8  )r   rm   rR  r   r   r   rS  output_func_r   r  re   re   rf   rL    s>   



zComputerAction.executer  r&   r   r	   r   c                   s4  |j }t|tr||j|j|j | S t|tr(||j|j | S t|t	r<|
dd |jD  | S t|trK||j | S t|tr\||j|j | S t|tri|  | S t|tr~||j|j|j|j | S t|tr||j | S t|tr|  | S )Nc                 S     g | ]}|j |jfqS re   xyrv   pre   re   rf   r   3      z7ComputerAction._get_screenshot_sync.<locals>.<listcomp>rR  r   r   clickr  r  buttonr   double_clickr   dragpathr   keypresskeysr   mover   
screenshotr   scrollscroll_xscroll_yr   r  textr   waitr   r  r   rR  re   re   rf   r  '  s:   









z#ComputerAction._get_screenshot_syncr%   c                   s@  |j }t|tr||j|j|jI d H  nt|tr(||j|jI d H  nqt|t	r<|
dd |jD I d H  n]t|trK||jI d H  nNt|tr\||j|jI d H  n=t|tri| I d H  n0t|tr~||j|j|j|jI d H  nt|tr||jI d H  nt|tr| I d H  | I d H S )Nc                 S  r  re   r  r  re   re   rf   r   O  r  z8ComputerAction._get_screenshot_async.<locals>.<listcomp>r  r  re   re   rf   r  C  s*   






 

z$ComputerAction._get_screenshot_async)rm   r   rR  r   r   r   r   r   r   r^   rS  r  rq   r;   )r  r&   r   r	   rq   r   )r  r%   r   r	   rq   r   )rb   rc   rd   r  rL  r  r  re   re   re   rf   rX    s    	3rX  c                   @  s   e Zd ZedddZdS )rK  rm   r   rJ  r   r   r   r   r   r   r^   rq   r;   c          	   	     s   t ||||j|jr|j|||jnt I d H  t||jd}|j	|}t
|r6|I d H }n|}t ||||j||jrO|j|||j|nt I d H  t||d|jj|ddS )N)rN  r  local_shell_call_output)r  rP  r   r  )r   r   r1  r   r   r\   r2  rL   r   executorrV  rW  r;  r=   r8  )	r   rm   rJ  r   r   r   requestr   r   re   re   rf   rL  a  s:   

	

	zLocalShellAction.executeN)rm   r   rJ  r   r   r   r   r   r   r^   rq   r;   )rb   rc   rd   r  rL  re   re   re   rf   rK  `  s    rK  r   r   rI   c                 C  s"   d
dd}t | j| ji |ddd	S )N_ctxToolContext[Any]valuer   rq   c                   s"   t |trdd l}||S |S )Nr   )r   r   jsonloads)r  r  r  re   re   rf   r3    s
   

z5_build_litellm_json_tool_call.<locals>.on_invoke_toolT)r   descriptionparams_json_schemar3  strict_json_schema
is_enabled)r  r  r  r   rq   r   )rI   r   )r   r3  re   re   rf   r    s   
r  )r   r   r   r   rq   rB   )r   r   rq   rI   )
__future__r   r   r   rV  collections.abcr   r   r   typingr   r   r   openai.types.responsesr	   r
   r   r   r   :openai.types.responses.response_code_interpreter_tool_callr   2openai.types.responses.response_computer_tool_callr   r   r   r   r   r   r   r   r   0openai.types.responses.response_input_item_paramr   +openai.types.responses.response_input_paramr   r   +openai.types.responses.response_output_itemr   r   r   r   r   .openai.types.responses.response_reasoning_itemr    rm   r"   r#   r  r$   r  r%   r&   
exceptionsr'   r(   r)   r*   r+   r#  r,   r-   r.   r/   r   r0   r1   r  r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   	lifecycler?   r@   r   rA   models.interfacerB   rh  rC   rD   stream_eventsrE   rF   r  rG   rH   rI   rJ   rK   rL   rM   rN   rO   r  rP   tool_guardrailsrQ   rR   rS   rT   tracingrU   rV   rW   rX   rY   rZ   r[   utilr\   r]   r(  r^   r`   QUEUE_COMPLETE_SENTINELr  rj   r   r   r   r   r   r   r   r   r   r   r   r   r  rX  rK  r  re   re   re   rf   <module>   s    ,<,$	
       ]%n3