stream() function enables real-time streaming of model responses, providing a better user experience for long-form content.
Basic Usage
Stream a chat completion with async iteration:Stream event types
Thestream() function returns a ChatStream — an async iterable that also exposes .result and .events:
Handling Different Event Types
Process different event types for rich streaming experiences:Getting the complete response
Access the aggregated result via.result, and the full event list via .events:
Streaming starts immediately when you create the handle.
.result resolves
when the stream completes, .events resolves with the observed history even
on abort or failure, and the handle is replayable for late iterators.Streaming with configuration
Apply the same configuration options asgenerate():
UI Integration Examples
- React
- Node.js HTTP
- Express
Streaming with Tools
Handle tool calls during streaming:Abort Streaming
Cancel streaming with AbortController:Error Handling
Handle errors during streaming:Best Practices
Streams are replayable
Streams are replayable
ChatStream buffers events internally. You can iterate multiple times, and .result resolves independently of event consumption:Buffer text for display
Buffer text for display
Accumulate text deltas for complete content:
Handle reasoning separately
Handle reasoning separately
Distinguish between reasoning and response text:
Next Steps
Chat Completion
Learn about non-streaming responses
Tool Calling
Stream tool calls and responses
Structured Outputs
Stream structured JSON objects
Multi-Modal
Stream responses with images