Overview
Streaming allows you to receive LLM responses incrementally as they’re generated, rather than waiting for the complete response. This significantly improves perceived latency and enables real-time user interfaces like ChatGPT. The Gateway supports streaming for all compatible providers with automatic format transformation to OpenAI’s Server-Sent Events (SSE) format.How It Works
When streaming is enabled:- Request is sent to the provider with
stream: true - Provider begins generating the response
- Gateway receives chunks as they’re generated
- Chunks are transformed to OpenAI format (if needed)
- Transformed chunks are streamed to your application
- Final chunk signals completion
The Gateway handles different streaming formats (SSE, JSON lines, AWS event streams) and normalizes them to OpenAI’s format, making it easy to switch providers.
Configuration
Basic Streaming
Simply setstream: true in your request:
Streaming with Configs
Combine streaming with other features:Retries and fallbacks work seamlessly with streaming. If a stream fails mid-way, the Gateway can retry or fallback automatically.
Usage Examples
Stream Format
OpenAI Format (Default)
The Gateway outputs streams in OpenAI’s SSE format:Chunk Structure
Provider Support
Streaming Providers
All major providers support streaming:The Gateway automatically transforms all streaming formats to OpenAI-compatible SSE, so you can switch providers without changing client code.
Implementation Details
Stream Processing
Fromsrc/handlers/streamHandler.ts:
Provider-Specific Handling
AWS Bedrock Event Streams
Bedrock uses binary event streams that require special parsing:Advanced Streaming Patterns
Function Calling with Streaming
Streaming with Metadata
Multi-Provider Streaming with Fallback
Error Handling
Handling Stream Errors
Mid-Stream Failures
The Gateway handles mid-stream failures:- Gateway attempts retry with same provider
- Falls back to next provider if retry fails
- New stream starts from beginning
Performance Optimization
Latency Optimization
Chunk Buffering
For better UI rendering, buffer small chunks:Best Practices
Handle Stream Completion
Handle Stream Completion
Always check for
finish_reason to detect stream completion:Set Appropriate Timeouts
Set Appropriate Timeouts
Streaming responses take longer. Set higher timeouts:
Implement Retry Logic
Implement Retry Logic
Streams can fail mid-way. Implement client-side retry:
Buffer for UI Rendering
Buffer for UI Rendering
Buffer small chunks before updating UI to reduce render overhead and improve perceived performance.
Monitor Stream Performance
Monitor Stream Performance
Track metrics like time-to-first-chunk and total stream duration to optimize user experience.
Related Features
Realtime APIs
WebSocket-based realtime APIs
Timeouts
Configure streaming timeouts
Fallbacks
Fallback on stream failures
Retries
Retry failed streams