---
type: email
from: Lucas Wang <notifications@github.com>
subject: [openai/openai-agents-python] fix: track request count when streaming

 fails mid-request (fixes #1973) (PR #1975)
received: 2026-03-06 08:13:33
date_header: Wed, 22 Oct 2025 08:51:15 -0700
priority: normal
status: awaiting_approval
uid: 33453
---

## Email Content

**From:** Lucas Wang <notifications@github.com>
**Subject:** [openai/openai-agents-python] fix: track request count when streaming

 fails mid-request (fixes #1973) (PR #1975)
**Date:** Wed, 22 Oct 2025 08:51:15 -0700

### Body (preview)

## 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 `ResponseCompletedEvent` arrives. If the model provider raises an exception before yielding `ResponseCompletedEvent`, the async for loop exits without ever updating usage.



### Why This Happens



In `src/agents/run.py` line 1254-1272, usage is only tracked when we receive `ResponseCompletedEvent`:



```python

if isinstance(event, ResponseCompletedEvent):

    usage = Usage(...)

    context_wrapper.usage.add(usage)

```



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:



```python

try:

    async for event in model.stream_response(...):

        # existing logic

except Exception:

    if final_response is None:

        context_wrapper.usage.add(Usage(requests=1))

    raise

```



This approach:

- ✅ Tracks that a request was made (important for monitoring and cost estimation)

- ✅ Doesn&#39;t introduce new dependencies (no tiktoken needed)

- ✅ Preserves existing behavior for successful streaming

- ✅ Accurately reflects unavailable data (token counts stay at 0)



While we cannot estimate token counts without introducing dependencies or making model-specific assumptions, tracking the request count provides valuable information for:

- Monitoring API call frequency

- Debugging failed requests  

- Cost estimation (users know a request was made)



## Changes



**src/agents/run.py**:

- Added try-except around streaming loop (lines 1237-1310)

- Tracks request count on exception if no response received

- Preserves existing

---

## Suggested Actions
- [ ] Reply
- [ ] Archive
- [ ] Escalate
