Skip to main content

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

Set stream=True to enable streaming:

Stream Response Format

When streaming is enabled, the API returns a stream of ChatCompletionChunk 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

Use AsyncOpenAI for async streaming:

Stream Options

You can configure streaming behavior with stream_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

The finish_reason field is only present in the final chunk:
Possible finish reasons:
  • stop - Model reached a natural stopping point
  • length - Maximum token limit reached
  • tool_calls - Model called a tool
  • content_filter - Content was filtered
  • function_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, use flush=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, enable include_usage:

Comparison: Streaming vs Non-Streaming

Pros:
  • Simpler to implement
  • Full message available immediately
  • Easier to handle errors
Cons:
  • Higher perceived latency
  • No feedback until complete