Overview
Streaming allows you to receive API responses incrementally as they’re generated, rather than waiting for the complete response. This provides:- Lower perceived latency - Display partial results immediately
- Better user experience - Show progress for long-running generations
- Real-time feedback - Process data as it arrives
Basic Streaming
Synchronous Streaming
Asynchronous Streaming
Stream Object
Streaming responses return aStream (sync) or AsyncStream (async) object:
Context Manager
Use a context manager to ensure proper cleanup:Stream Chunks
Each chunk in a stream contains:Accumulating Responses
Build the complete response from stream chunks:Function Calling with Streaming
Stream function calls as they’re generated:Error Handling
Handle errors during streaming:Streaming with Async Error Handling
Manual Stream Control
Manually control stream iteration:Responses API Streaming
Stream responses using the Responses API:Server-Sent Events Format
The SDK automatically handles SSE parsing. Each event contains:- event - Event type (if specified)
- data - JSON payload
- id - Event ID (if specified)
- retry - Retry timeout in milliseconds (if specified)
The stream automatically closes when it receives a
[DONE] message or when the response is complete.Best Practices
Performance Considerations
- Buffering - The SDK buffers SSE data automatically, no manual buffering needed
- Backpressure - Slow consumers may cause buffering in the underlying HTTP connection
- Connection pooling - Streaming requests hold connections longer, consider connection limits
- Timeouts - Streaming respects timeout settings, consider increasing for long streams
Related
- Async Operations - Asynchronous streaming
- Error Handling - Handling streaming errors
- Timeouts - Configuring streaming timeouts