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 request2
Receive Chunks
Get response tokens incrementally via SSE
3
Process Events
Parse
data: events containing JSON chunks4
Handle Completion
Watch for
[DONE] signal to know when completeEndpoints
Streaming works with both API formats:stream: true parameter.
Request Format
OpenAI Format
Anthropic Format
Response Format
Event Stream Structure
Responses are sent as Server-Sent Events:Stream Lifecycle
- Initial chunk - Contains role:
- Content chunks - Incremental text:
- Final chunk - Includes finish_reason:
- Stream end:
Implementation Examples
- Python
- JavaScript
- Browser
- React
- cURL
Advanced Features
Function Calling with Streaming
Progress Tracking
Buffering for Performance
Error Handling
Best Practices
- Buffer for UI updates - Don’t update DOM for every chunk (batching improves performance)
- Show loading indicators - Display typing indicators during streaming
- Implement timeouts - Set reasonable timeouts for connections
- Handle interruptions - Use retry logic with exponential backoff
- Clean up resources - Always close streams properly
- Test error scenarios - Ensure your app handles network failures gracefully
Performance Tips
- Use
flush=Truein 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
Related
- Chat Completions API - OpenAI-compatible streaming API
- Messages API - Anthropic-compatible streaming API
- Function Calling - Using functions with streaming
- Authentication - API authentication methods

