You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Streaming is blocking and cannot be cancelled #2222
RunResultStreamed.stream_events() cannot be cancelled using asyncio primitives. In the script below, we'd like to time out if a streaming event takes longer than 5 seconds to arrive. However, using asyncio.wait_for's cancellation event is not propagated to the stream_events iterator.
Debug information
Agents SDK version: (e.g. v0.0.3)
Python version (e.g. Python 3.10)
Repro steps
fromagentsimportAgent, Runner, function_toolimportasyncioimportdatetime@function_toolasyncdefget_secret_key():
awaitasyncio.sleep(120)
return"secret_key"asyncdefmain():
agent=Agent(
name="secret_key_agent",
model="gpt-4.1-mini",
tools=[get_secret_key],
)
result=Runner.run_streamed(agent, input="What is the secret key?")
event_iter=aiter(result.stream_events())
whileTrue:
try:
event=awaitasyncio.wait_for(anext(event_iter), timeout=5)
print(datetime.datetime.now(), event)
exceptStopAsyncIteration:
breakexceptasyncio.TimeoutError:
print("Timed out waiting for next event")
break# or continue if you want to keep waitingif__name__=="__main__":
asyncio.run(main())
Expected behavior
The iterator should respond as expected to asyncio cancellations. The loop above should time out.
@varunursekar I’m not sure whether this is a bug or expected behavior, but currently if the caller times out, the SDK won’t cancel streaming immediately. It “safely” waits for any background task to finish (see _await_task_safely function).
If you need streaming timeouts today, the best approach seems to be implementing your own timer and call result.cancel() directly. It supports "immediate" and "after_turn". See: #1896 and #1895
This use case was not supported by design, but enabling to use the timeout this way may be useful for other developers too. My pull request #2226 may resolve it. Feedback is welcome!
Activity
ihower commentedon Dec 23, 2025
@varunursekar I’m not sure whether this is a bug or expected behavior, but currently if the caller times out, the SDK won’t cancel streaming immediately. It “safely” waits for any background task to finish (see
_await_task_safelyfunction).If you need streaming timeouts today, the best approach seems to be implementing your own timer and call
result.cancel()directly. It supports "immediate" and "after_turn". See: #1896 and #1895fix: #2222 Streaming is blocking and cannot be cancelled
seratch commentedon Dec 23, 2025
This use case was not supported by design, but enabling to use the timeout this way may be useful for other developers too. My pull request #2226 may resolve it. Feedback is welcome!
fix: openai#2222 Streaming is blocking and cannot be cancelled (opena…