@@ -204,49 +204,28 @@ async def _execute_handoffs(
204204 return result
205205
206206
207- def _patch_agent_run () -> None :
207+ async def _execute_final_output (
208+ original_execute_final_output : "Callable[..., SingleStepResult]" ,
209+ * args : "Any" ,
210+ ** kwargs : "Any" ,
211+ ) -> "SingleStepResult" :
208212 """
209- Patches AgentRunner methods to create agent invocation spans.
210- This directly patches the execution flow to track when agents start and stop.
213+ Patched execute_final_output that
214+ - ends the agent invocation span.
215+ - ends the workflow span if the response is streamed.
211216 """
212217
213- # Store original methods
214- original_execute_final_output = agents ._run_impl .RunImpl .execute_final_output
218+ agent = kwargs .get ("agent" )
219+ context_wrapper = kwargs .get ("context_wrapper" )
220+ final_output = kwargs .get ("final_output" )
215221
216- @wraps (
217- original_execute_final_output .__func__
218- if hasattr (original_execute_final_output , "__func__" )
219- else original_execute_final_output
220- )
221- async def patched_execute_final_output (
222- cls : "agents.Runner" , * args : "Any" , ** kwargs : "Any"
223- ) -> "Any" :
224- """
225- Patched execute_final_output that
226- - ends the agent invocation span.
227- - ends the workflow span if the response is streamed.
228- """
229-
230- agent = kwargs .get ("agent" )
231- context_wrapper = kwargs .get ("context_wrapper" )
232- final_output = kwargs .get ("final_output" )
233-
234- try :
235- result = await original_execute_final_output (* args , ** kwargs )
236- finally :
237- with capture_internal_exceptions ():
238- if (
239- agent
240- and context_wrapper
241- and _has_active_agent_span (context_wrapper )
242- ):
243- end_invoke_agent_span (context_wrapper , agent , final_output )
244- # For streaming, close the workflow span (non-streaming uses context manager in _create_run_wrapper)
245- _close_streaming_workflow_span (agent )
246-
247- return result
248-
249- # Apply patches
250- agents ._run_impl .RunImpl .execute_final_output = classmethod (
251- patched_execute_final_output
252- )
222+ try :
223+ result = await original_execute_final_output (* args , ** kwargs )
224+ finally :
225+ with capture_internal_exceptions ():
226+ if agent and context_wrapper and _has_active_agent_span (context_wrapper ):
227+ end_invoke_agent_span (context_wrapper , agent , final_output )
228+ # For streaming, close the workflow span (non-streaming uses context manager in _create_run_wrapper)
229+ _close_streaming_workflow_span (agent )
230+
231+ return result
0 commit comments