Skip to main content

Overview

Streaming allows you to receive tokens as they are generated, providing a better user experience for real-time applications like chatbots.

Basic Usage

Streaming Parameters

bool
required
Set to True to enable streaming. When enabled, the function returns a CustomStreamWrapper instead of a ModelResponse.
dict
Additional streaming options. Currently supports:
  • include_usage: If True, includes token usage in the final chunk

Response Format

Each chunk in the stream is a ModelResponseStream object:

Examples

Basic Streaming

Streaming with Usage Information

Building Complete Response from Stream

Handling Finish Reasons

Streaming with Different Providers

Streaming with Function Calls

Error Handling

Advanced Usage

Custom Stream Processing

Streaming with Token Counting

Cancelling a Stream

Best Practices

  1. Always handle empty content: Check if delta.content exists before using it
  2. Use flush=True: Ensure output appears immediately with print(..., flush=True)
  3. Monitor finish_reason: Check finish_reason to understand why streaming ended
  4. Handle errors gracefully: Wrap streaming in try-except blocks
  5. Close streams properly: The stream auto-closes when iteration completes or breaks

Performance Considerations

  • Latency: Streaming reduces time-to-first-token, improving perceived responsiveness
  • Memory: Streaming uses less memory than buffering the complete response
  • Connection: Keep connections alive during streaming - consider timeout settings
  • Rate limits: Streaming counts toward rate limits the same as non-streaming