Overview
Streaming allows you to receive chat completion responses incrementally as they are generated, rather than waiting for the entire response to complete. This is particularly useful for creating responsive user experiences.Basic Streaming
Setstream=True to enable streaming:
Stream Response Format
When streaming is enabled, the API returns a stream ofChatCompletionChunk objects instead of a single ChatCompletion object.
ChatCompletionChunk Structure
string
A unique identifier for the chat completion. Each chunk has the same ID.
string
The object type, which is always
chat.completion.chunk.integer
The Unix timestamp (in seconds) of when the chat completion was created. Each chunk has the same timestamp.
string
The model used to generate the completion.
array
A list of chat completion choices. Can contain more than one element if
n is greater than 1.Async Streaming
UseAsyncOpenAI for async streaming:
Stream Options
You can configure streaming behavior withstream_options:
Stream Options Parameters
boolean
default:"false"
If set to
true, the final chunk will include a usage field with token usage statistics for the entire request.Note: If the stream is interrupted or cancelled, you may not receive the final usage chunk.Streaming with Function Calling
When streaming with tool calls, the function information is sent incrementally:Accumulating Tool Call Data
Since tool calls are sent incrementally, you need to accumulate the chunks:Handling Finish Reasons
Thefinish_reason field is only present in the final chunk:
stop- Model reached a natural stopping pointlength- Maximum token limit reachedtool_calls- Model called a toolcontent_filter- Content was filteredfunction_call- (Deprecated) Model called a function
Error Handling
Handle errors during streaming:Streaming with Context Manager
Use a context manager to ensure proper cleanup:Complete Example: Streaming Chat UI
Here’s a complete example of building a streaming chat interface:Streaming Best Practices
1. Always Handle Incomplete Chunks
Not every chunk will contain content. Always check before accessing:2. Accumulate Complete Messages
For multi-turn conversations, accumulate the full response:3. Use Flush for Real-time Display
When printing to stdout, useflush=True for immediate display:
4. Handle Connection Issues
Always wrap streaming in try-except blocks:5. Request Usage Stats When Needed
If you need token counts, enableinclude_usage:
Comparison: Streaming vs Non-Streaming
- Non-Streaming
- Streaming
- Simpler to implement
- Full message available immediately
- Easier to handle errors
- Higher perceived latency
- No feedback until complete