Skip to content

fix: prevent ContextVar reset error in async streaming context. #516

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
wants to merge 1 commit into from

Conversation

JilinJL
Copy link

@JilinJL JilinJL commented Apr 15, 2025

Summary

This PR fixes a runtime error caused by an unexpected reset_current keyword argument passed to Trace.finish() within the RunResultStreaming.stream_events() method.

What was the issue?

Currently, stream_events() calls:
refer #515

Solution

Wrap the .finish(reset_current=True) call in a try/except block to fallback to a safe reset mode:

if self._trace:
    try:
        self._trace.finish(reset_current=True)
    except ValueError:
        logger.warning("ContextVar reset failed — switching to reset_current=False")
        self._trace.finish(reset_current=False)

🧪 Testing

Tested with a minimal FastAPI + StreamingResponse setup. After this patch:

  • The stream completes successfully.
  • No ValueError is raised.
  • Trace finalization still works.

📦 Affected file

openai-agents-python\src\agents\result.py

💬 Related Issue
This PR resolves the bug described in the issue: #515

JilinJL

This comment was marked as abuse.

@JilinJL JilinJL changed the title Fix: prevent ContextVar reset error in async streaming context. fix: prevent ContextVar reset error in async streaming context. Apr 16, 2025
@rm-openai
Copy link
Collaborator

IMO the loud exception is probably a good thing? Catches obvious errors. WDYT?

@JilinJL
Copy link
Author

JilinJL commented Apr 18, 2025

IMO the loud exception is probably a good thing? Catches obvious errors. WDYT?

I realize now that I don’t understand this area as well as I thought — my knowledge is still quite shallow.

I tried to be clever and submitted a PR, thinking I could grab a quick contribution, but clearly I misunderstood how it actually works.

Thanks a lot for the correction and your patience — I’ve learned from this.

@rm-openai rm-openai closed this Apr 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants