Skip to main content

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
The SDK uses Server-Sent Events (SSE) to deliver streaming responses.

Basic Streaming

Synchronous Streaming

Asynchronous Streaming

Stream Object

Streaming responses return a Stream (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

  • Always close streams properly using context managers or explicit .close() calls
  • Handle errors during streaming - connections can drop mid-stream
  • Don’t assume chunks arrive in a specific size or timing
  • Accumulate function call arguments before parsing as JSON
  • Use async streaming for high-concurrency workloads

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