Skip to content

Streaming is blocking and cannot be cancelled #2222

Description

@varunursekar

Describe the bug

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

from agents import Agent, Runner, function_tool
import asyncio
import datetime


@function_tool
async def get_secret_key():
    await asyncio.sleep(120)
    return "secret_key"


async def main():
    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())

    while True:
        try:
            event = await asyncio.wait_for(anext(event_iter), timeout=5)
            print(datetime.datetime.now(), event)
        except StopAsyncIteration:
            break
        except asyncio.TimeoutError:
            print("Timed out waiting for next event")
            break  # or continue if you want to keep waiting

if __name__ == "__main__":
    asyncio.run(main())

Expected behavior

The iterator should respond as expected to asyncio cancellations. The loop above should time out.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions