fix: track request count when streaming fails mid-request (fixes #1973) #1975
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
This PR fixes issue #1973 where usage tracking was completely lost when streaming fails mid-request.
Problem
When streaming fails (API errors, connection drops, context window exceeded, etc.), usage tracking was completely lost. The issue occurs because usage is only accumulated when
ResponseCompletedEventarrives. If the model provider raises an exception before yieldingResponseCompletedEvent, the async for loop exits without ever updating usage.Why This Happens
In
src/agents/run.pyline 1254-1272, usage is only tracked when we receiveResponseCompletedEvent:If an error occurs before this event (e.g., connection drops, rate limits, context window exceeded), the loop exits and no usage is recorded at all.
Solution
Wrap the streaming loop in try-except to ensure at least the request count is tracked when streaming fails:
This approach:
While we cannot estimate token counts without introducing dependencies or making model-specific assumptions, tracking the request count provides valuable information for:
Changes
src/agents/run.py:
tests/test_usage_tracking_on_error.py (new file):
Testing
All tests pass:
Fixes #1973