# Practical and Useful Patterns for OpenAI Agent SDK
๐ Deliver your agent's responses in real time!
By leveraging different streaming event types, you can build everything from typewriter UIs to tool-progress notifications, dramatically improving user experience.
๐ Title: Streaming
๐ URL:
๐งฉ Overview
The OpenAI Agent SDK provides three streaming event types. RawResponsesStreamEvent delivers raw LLM tokens in real time. RunItemStreamEvent fires for coarser events like message creation and tool calls. AgentUpdatedStreamEvent detects agent handoffs. You can also cancel immediately or after the current turn completes.
๐ Usage
Define `Agent(name="assistant", instructions="Answer helpfully")` and start streaming with ` "What are the latest AI trends?")`. Iterate with `async for event in for `isinstance(event, RawResponsesStreamEvent)`, display tokens in real time via ` For `isinstance(event, RunItemStreamEvent)`, check `event.item.type` -- `"tool_called"` shows tool invocation with ` `"tool_output"` signals completion, and `"message_output_created"` indicates message generation start. For `isinstance(event, AgentUpdatedStreamEvent)`, display agent switches via ` Finally, `await retrieves the complete result.
For cancellation, after starting with ` "Run a long analysis")`, call `result.cancel()` inside the stream event loop for immediate abort, or `result.cancel(mode="after_turn")` to stop after the current turn completes. After canceling, consume the iterator with `async for _ in pass` to clean up resources.
๐ Practical Patterns
For chat UIs, the foundation is typewriter display using `output_text.delta` from `RawResponsesStreamEvent`. But since no tokens flow during tool calls, best practice is to show progress indicators like "Searching..." via `RunItemStreamEvent`'s `tool_called` event.
In multi-agent setups, `AgentUpdatedStreamEvent` lets you display transitions like "Switched from Researcher to Writer agent," helping users understand the processing flow.
Cancellation comes in two modes. `cancel()` aborts immediately, while `cancel(mode="after_turn")` waits for the current LLM turn to finish cleanly. In both cases, you must consume the stream iterator to completion after canceling to properly clean up resources.
๐ก Use Cases
โจ๏ธ Typewriter-style real-time display in chat applications
๐ง "Searching..." / "Calculating..." progress indicators during tool execution
๐ Real-time agent-switch notifications in multi-agent UIs
๐ Safe cancellation via user "Stop" button
โ ๏ธ Caveats
- Failing to consume the iterator after `cancel()` may cause resource leaks
- `RawResponsesStreamEvent` fires per-token at high frequency โ watch your UI re-render rate
- Errors during streaming arrive as events, so handle them appropriately
โจ Using the right streaming events for the right purpose lets you communicate "thinking," "searching," and "writing" to users โ building highly responsive agent UIs!
#
OpenAIAgentSDK# #
AIAgent#