Skip to main content

Overview

Streaming allows you to receive response tokens as they’re generated, rather than waiting for the complete response. This is perfect for:
  • Chatbots - Display responses as they’re typed
  • Live assistants - Show progress in real-time
  • Long responses - Start displaying content immediately
  • Better UX - Reduce perceived latency

How It Works

1

Enable Streaming

Set stream: true in your request
2

Receive Chunks

Get response tokens incrementally via SSE
3

Process Events

Parse data: events containing JSON chunks
4

Handle Completion

Watch for [DONE] signal to know when complete

Endpoints

Streaming works with both API formats:
Both endpoints support the stream: true parameter.

Request Format

OpenAI Format

Anthropic Format

Response Format

Event Stream Structure

Responses are sent as Server-Sent Events:

Stream Lifecycle

  1. Initial chunk - Contains role:
  1. Content chunks - Incremental text:
  1. Final chunk - Includes finish_reason:
  1. Stream end:

Implementation Examples

Async Python

Advanced Features

Function Calling with Streaming

Progress Tracking

Buffering for Performance

Error Handling

Streaming connections can fail mid-stream. Always implement retry logic.

Best Practices

  1. Buffer for UI updates - Don’t update DOM for every chunk (batching improves performance)
  2. Show loading indicators - Display typing indicators during streaming
  3. Implement timeouts - Set reasonable timeouts for connections
  4. Handle interruptions - Use retry logic with exponential backoff
  5. Clean up resources - Always close streams properly
  6. Test error scenarios - Ensure your app handles network failures gracefully

Performance Tips

Buffer small chunks together before updating the UI to avoid excessive DOM updates.
  • Use flush=True in Python’s print for immediate output
  • Implement debouncing for frequent UI updates
  • Consider virtualization for long responses
  • Use Web Workers for parsing in browsers
  • Monitor memory usage for long streams