Skip to content

ValueError when finishing trace in Runner.run_streamed(): “token was created in a different Context” #538

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
sarattha opened this issue Apr 17, 2025 · 0 comments · Fixed by #540
Labels
bug Something isn't working

Comments

@sarattha
Copy link

When using Runner.run_streamed() in async streaming mode, at the end of the stream the SDK crashes with:

    ValueError: <Token var=<ContextVar name='current_trace' default=None at 0x…> at 0x…> was created in a different Context

This comes from the tracing code’s Scope.reset_current_trace(token) call in Trace.finish(), because the token was set in the parent
task’s context but is being reset in the spawned Task’s context.

To Reproduce

    1. Call `Runner.run_streamed(...)` (e.g. from a FastAPI endpoint) on an agent that emits a streaming response.
    2. Consume it all, letting the stream reach completion.
    3. Observe the exception in the server logs.

Expected behavior
The trace should clean up without raising a ValueError, or tracing should be disabled automatically for streaming if it can’t safely reset in the child Task.

Traceback

    File ".../agents/tracing/scope.py", line 49, in reset_current_trace
        _current_trace.reset(token)
    ValueError: <Token var=<ContextVar name='current_trace' default=None at 0x…> at 0x…> was created in a different Context

Environment

    * openai‑agents‑python version: 0.0.11
    * Python: 3.13.2 on macOS (aarch64)
    * starlette / fastapi / uvicorn versions: 0.34.1

Additional context
run_streamed() does:

    1. `new_trace = trace(...); new_trace.start(mark_as_current=True)`
    2. `asyncio.create_task(_run_streamed_impl(...))`
    3. When the child task ends, `stream_events()` calls `trace.finish(reset_current=True)`, using the token created in the parent
context. Python’s ContextVar API refuses to reset with a token from another context.

Suggested fix
Either:

    * Don’t call `reset_current_trace()` in the worker Task (or catch/reset appropriately),
    * Or capture and re‐apply the correct ContextVar in the spawned Task,
    * Or disable tracing by default in `run_streamed()` if it can’t guarantee same context.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant