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: IfTrue, includes token usage in the final chunk
Response Format
Each chunk in the stream is aModelResponseStream 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
- Always handle empty content: Check if
delta.contentexists before using it - Use
flush=True: Ensure output appears immediately withprint(..., flush=True) - Monitor finish_reason: Check
finish_reasonto understand why streaming ended - Handle errors gracefully: Wrap streaming in try-except blocks
- 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