sdk-python icon indicating copy to clipboard operation
sdk-python copied to clipboard

[python] OpenAIResponsesModel.stream does not close the response on early exit or error

Open tyx022898 opened this issue 3 weeks ago • 2 comments

Package: strands-agents (Python) 1.64.0, strands/models/openai_responses.py

What happens

OpenAIResponsesModel.stream does response = await client.responses.create(**request) and then iterates response, but never enters the stream's context. When the caller stops early (closes the model.stream(...) generator after the first text delta, as an agent cancel or a consumer break does) or an exception is raised mid-stream, the HTTP response body is not closed deterministically; it is left to garbage collection. Under concurrent streams we saw nested async generators finalized from the GC on another task.

Repro (offline)

Serve two SSE events through httpx.MockTransport with an AsyncByteStream whose aclose sets a flag, consume model.stream([...]) inside contextlib.aclosing and break on the first contentBlockDelta. After the async with, response.is_closed and the body's closed flag are False.

Fix

async with await client.responses.create(**request) as response:
    ...  # the existing event loop, unchanged, indented one level

so completion, exceptions and early generator closure all release the response. We run this as a local patch on 1.64.0 (checked against main on 2026-11-09, which still iterates without the context manager). It pairs with an openai-python fix for the same cleanup path (closing the SSE iterators before the response). Happy to open a PR.

tyx022898 avatar Nov 10 '26 01:11 tyx022898

I can take this. I will close the OpenAI Responses stream with an async context manager so early exit and errors release the response, and add a test.

Ayush701-code-zm avatar Nov 10 '26 04:11 Ayush701-code-zm

Hey @Ayush701-code-zm thanks for filing an issue!

We have a bug report template that we ask you to use for filing bugs, which contains fields like Actual behaviour and Expected behaviour. Consequence of this report is not clear, as such we can't triage the issue.

Once you file a new issue, we will triage it and let you know if it's ready for contribution!

opieter-aws avatar Nov 12 '26 21:11 opieter-aws