@@ -404,10 +404,6 @@ def run_streamed(
404404 disabled = run_config .tracing_disabled ,
405405 )
406406 )
407- # Need to start the trace here, because the current trace contextvar is captured at
408- # asyncio.create_task time
409- if new_trace :
410- new_trace .start (mark_as_current = True )
411407
412408 output_schema = cls ._get_output_schema (starting_agent )
413409 context_wrapper : RunContextWrapper [TContext ] = RunContextWrapper (
@@ -426,7 +422,7 @@ def run_streamed(
426422 input_guardrail_results = [],
427423 output_guardrail_results = [],
428424 _current_agent_output_schema = output_schema ,
429- _trace = new_trace ,
425+ trace = new_trace ,
430426 )
431427
432428 # Kick off the actual agent loop in the background and return the streamed result object.
@@ -499,6 +495,9 @@ async def _run_streamed_impl(
499495 run_config : RunConfig ,
500496 previous_response_id : str | None ,
501497 ):
498+ if streamed_result .trace :
499+ streamed_result .trace .start (mark_as_current = True )
500+
502501 current_span : Span [AgentSpanData ] | None = None
503502 current_agent = starting_agent
504503 current_turn = 0
@@ -625,6 +624,8 @@ async def _run_streamed_impl(
625624 finally :
626625 if current_span :
627626 current_span .finish (reset_current = True )
627+ if streamed_result .trace :
628+ streamed_result .trace .finish (reset_current = True )
628629
629630 @classmethod
630631 async def _run_single_turn_streamed (
0 commit comments