Agent Streaming
Stream agent responses token-by-token
Overview
The chatStream method returns an async iterable that yields StreamChunk objects as the agent generates its response. This enables real-time display of agent output in CLIs, web UIs, and other interfaces.
Basic usage (Node.js)
Stream chunk types
Each chunk has a type field indicating what kind of data it contains:
Continue a conversation
Pass conversation_id to maintain context across streamed messages:
Collecting the full response
If you want to stream to the UI but also capture the full text:
Error handling
Errors during streaming can come from either the initial connection or within the stream itself.
Connection errors
If the initial request fails (auth error, agent not found, etc.), chatStream throws before yielding any chunks:
In-stream errors
If something goes wrong during generation, you will receive a chunk with type: 'error':
Web / React example
React Native warning
chatStream() does not work in React Native or Expo. React Native’s fetch implementation does not support ReadableStream, which is required for SSE parsing.
See the React Native guide for a complete workaround using raw fetch and manual SSE parsing.
React Native workaround (summary)
In React Native, you must use raw fetch with react-native-sse or manual line parsing. Here is the essential pattern:
See the full React Native guide at React Native for a complete React component example.
How it works
Under the hood, chatStream makes a POST request to /agents/{id}/chat/stream and parses the Server-Sent Events (SSE) response. Each SSE data: line is parsed as JSON into a StreamChunk.
The SSE format looks like:
The SDK’s parseSSE utility handles buffering, line splitting, and JSON parsing. You can import it directly if you need it for custom streaming: