Skip to main content

Streaming Chat Completions

Get real-time token-by-token responses for better user experience.

Overview

Streaming provides:
  • Lower perceived latency - Show progress immediately
  • Better UX - Users see responses as they’re generated
  • Progress indication - Know the AI is working
  • Cancellation - Stop generation mid-stream

Basic Streaming

Enable streaming with stream: true:

Stream Format

Streaming uses Server-Sent Events (SSE) format:

Initial Chunk (Role)

Content Chunks

Final Chunk

Advanced Patterns

Accumulate Full Response

Error Handling

Cancel Stream

Update UI in Real-Time

Retry on Failure

Performance Tips

1. Use Streaming for Long Responses

Streaming shows progress immediately, reducing perceived latency by 50-70%.

2. Buffer Chunks for Smoother UI

Accumulate 2-3 tokens before updating UI:

3. Handle Connection Issues

Implement exponential backoff for network failures:

Pricing

Streaming has the same cost as non-streaming:
  • $0.08 per 1,000 tokens
The only difference is how tokens are delivered (all at once vs. real-time).

Rate Limits

Streaming counts as a single request:

Best Practices

1. Always Use Streaming for Long Responses

If the expected response is >200 tokens, use streaming for better UX.

2. Handle Connection Drops

Implement retry logic for network failures:

3. Show Progress Indication

Display a spinner or “Generating…” message while waiting for first chunk.

4. Buffer Chunks for Smooth UI

Update UI every 2-3 tokens, not every single token.

5. Implement Cancellation

Allow users to stop generation mid-stream:

Common Issues

Issue: Stream Hangs Mid-Response

Solution: Implement timeout and retry logic:

Issue: Chunks Arrive Too Fast

Solution: Buffer chunks before updating UI:

Issue: Connection Drops Mid-Stream

Solution: Implement exponential backoff retry:

Next Steps

Create Completion

Learn about non-streaming completions

List Sessions

List chat sessions

Error Handling

Handle errors gracefully

Best Practices

Learn best practices