Open History to see the last commit
1---
2title: Stream Events
3id: stream-events
4order: 3
5description: "Read AG-UI stream chunks: event types, thread vs run ids, and tool input on the wire and in UIMessage parts."
6keywords:
7 - tanstack ai
8 - ag-ui
9 - stream events
10 - StreamChunk
11 - threadId
12 - runId
13 - TOOL_CALL
14 - TEXT_MESSAGE_CONTENT
15---
16
17You have a stream of chunks. You need to know which ones are tokens, which ones are tools, and when the run is done.
18
19Branch on `chunk.type`. Two ids frame every stream: `threadId` and `runId`.
20
21## Event types
22
23Public `StreamChunk` follows [AG-UI](https://docs.ag-ui.com/introduction). TanStack extras live under `metadata.tanstack`.
24
25Do now:
26
27- `RUN_STARTED`: `threadId`, `runId`
28- `TEXT_MESSAGE_START` / `CONTENT` / `END`: `messageId`, `delta`
29- `TOOL_CALL_START` / `ARGS` / `END`: `toolCallId`, `toolCallName`, args `delta`
30- `RUN_FINISHED` / `RUN_ERROR`: usage and finish reason. A rate-limited `RUN_ERROR` also says how long to wait. See [Rate limits](#rate-limits). For the provider's response ID, see [Read the provider response identity](#read-the-provider-response-identity)
31
32Later:
33
34- `REASONING_*` / `REASONING_ENCRYPTED_VALUE`: thinking content. See [Thinking and Reasoning](./thinking-content)
35- `TEXT_MESSAGE_CHUNK` / `TOOL_CALL_CHUNK` / `REASONING_MESSAGE_CHUNK`: other AG-UI servers can send one of these in place of START / CONTENT / END. A chunk with no id continues the open stream of the same kind. A chunk of a different kind closes that stream. The client builds the same message from both forms
36- `STEP_STARTED` / `STEP_FINISHED`: `stepName` only
37- `CUSTOM`: `name` and `value`. See [Custom Events](../protocol/custom-events)
38- `SUBAGENT_STARTED` / `SUBAGENT_FINISHED` / `SUBAGENT_ERROR`: a child agent. Attributed events carry `subagentRunId`. A child that waits for an interrupt ends with `SUBAGENT_FINISHED` and `outcome: { type: 'suspended' }`. In request messages, each child message carries `subagentRunId`. See [Subagents](./subagents)
39
40On `RUN_FINISHED`, in-process `chat()` still uses TanStack `TokenUsage` (`promptTokens`). The SSE and HTTP wires use the spec `usage` array (`inputTokens`). Read `finishReason` from `metadata.tanstack.finishReason`. Custom servers: see [Event metadata](../protocol/metadata).
41
42```typescript
43import { chat } from "@tanstack/ai";
44import { openaiText } from "@tanstack/ai-openai";
45
46const stream = chat({
47 adapter: openaiText("gpt-5.6"),
48 messages: [{ role: "user", content: "Hello!" }],
49});
50
51for await (const chunk of stream) {
52 if (chunk.type === "TEXT_MESSAGE_CONTENT") {
53 console.log(chunk.delta);
54 }
55 if (chunk.type === "RUN_FINISHED") {
56 console.log(chunk.usage);
57 console.log(chunk.metadata?.tanstack?.finishReason);
58 }
59}
60```
61
62## Token usage
63
64You want to know what a run cost. `RUN_FINISHED.usage.promptTokens` is the full input, cached tokens included. The cache parts are also on `promptTokensDetails`:
65
66- `cachedTokens`: tokens read from the cache.
67- `cacheWriteTokens`: tokens written to the cache.
68
69Need the uncached part? Subtract both:
70
71```typescript
72import type { TokenUsage } from "@tanstack/ai";
73
74function uncachedTokens(usage: TokenUsage) {
75 const read = usage.promptTokensDetails?.cachedTokens ?? 0;
76 const written = usage.promptTokensDetails?.cacheWriteTokens ?? 0;
77 return usage.promptTokens - read - written;
78}
79```
80
81Upgrading the Anthropic, Bedrock, or Claude Code adapter? Their `promptTokens` used to count only the uncached tokens. If your code adds `cachedTokens` to `promptTokens`, remove that addition. Otherwise you count the cache two times.
82
83## Rate limits
84
85You got a 429 and want to know how long to wait. If the provider sends a `retry-after-ms` or `retry-after` header, the `RUN_ERROR` has the wait in `metadata.tanstack.retryAfterMs`, in milliseconds.
86
87The Anthropic adapter and the adapters built on `@tanstack/openai-base` (for example OpenAI, Grok, and Groq) set it.
88
89The OpenRouter adapter also sets it for [an error in the stream](../adapters/openrouter#retry-an-error-in-the-stream). That value is the adapter's own backoff wait, not a wait from the provider.
90
91On the server:
92
93```typescript
94import { chat } from "@tanstack/ai";
95import { anthropicText } from "@tanstack/ai-anthropic";
96
97const stream = chat({
98 adapter: anthropicText("claude-sonnet-5-5"),
99 messages: [{ role: "user", content: "Hello!" }],
100});
101
102for await (const chunk of stream) {
103 if (chunk.type === "RUN_ERROR") {
104 const waitMs = chunk.metadata?.tanstack?.retryAfterMs;
105 console.log(waitMs === undefined ? "No wait sent" : `Retry in ${waitMs} ms`);
106 }
107}
108```
109
110The value also reaches the browser. On the client:
111
112```typescript
113import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
114
115const { messages } = useChat({
116 connection: fetchServerSentEvents("/api/chat"),
117 onChunk: (chunk) => {
118 if (chunk.type === "RUN_ERROR") {
119 console.log(chunk.metadata?.tanstack?.retryAfterMs);
120 }
121 },
122});
123```
124
125No `retryAfterMs`? The provider sent no wait header, so pick your own backoff. The provider SDKs also retry a 429 by themselves first. To handle every 429 yourself, set `maxRetries: 0` in the adapter config.
126
127### Let `chat()` retry for you
128
129You do not have to wait and retry in your own code. Pass `retry`, and `chat()` waits for the `retryAfterMs` time, then calls the model again:
130
131```typescript
132import { chat } from "@tanstack/ai";
133import { anthropicText } from "@tanstack/ai-anthropic";
134
135const stream = chat({
136 adapter: anthropicText("claude-sonnet-5-5"),
137 messages: [{ role: "user", content: "Hello!" }],
138 retry: { maxRetries: 3, maxWaitMs: 30_000 },
139});
140```
141
142When it retries:
143
144- Only when the `RUN_ERROR` has a wait time (`metadata.tanstack.retryAfterMs`). Only the adapters named above set it.
145- Only when the wait time is at most `maxWaitMs` (default 60 000). For a longer wait time, you get the `RUN_ERROR`.
146- Only when the call streamed no output, so no text repeats.
147
148Limits:
149
150- `maxRetries` is the limit for each model call, not for the full run.
151- The provider SDK retries a 429 first, then `chat()` retries. To count only the `chat()` retries, set `maxRetries: 0` in the adapter config.
152- With `outputSchema`, `chat()` does not retry the structured-output call.
153- An abort stops the wait immediately. You then get the `RUN_ERROR`.
154
155On a serverless route, a long wait keeps the request open. If your host has a short time limit, keep `maxWaitMs` low. Then retry the longer wait times from the client.
156
157## Read the provider response identity
158
159You want to find a reply in the provider's logs, or see which model really answered. Read `metadata.tanstack` on `RUN_FINISHED`:
160
161- `responseId`: the generation ID from the provider, when it sends one.
162- `model`: the model that the provider says it used. It can differ from the model that you asked for.
163- `source`: `{ provider, api, model }` for the call. Here `model` is the one that you asked for.
164
165On the server:
166
167```typescript
168import { chat } from "@tanstack/ai";
169import { anthropicText } from "@tanstack/ai-anthropic";
170
171const stream = chat({
172 adapter: anthropicText("claude-sonnet-5-5"),
173 messages: [{ role: "user", content: "Hello!" }],
174});
175
176for await (const chunk of stream) {
177 if (chunk.type === "RUN_FINISHED") {
178 const tanstack = chunk.metadata?.tanstack;
179 console.log(tanstack?.responseId, tanstack?.model, tanstack?.source);
180 }
181}
182```
183
184The same fields land on each assistant message. `StreamProcessor` merges the metadata of `RUN_FINISHED` and `RUN_ERROR` into the messages of that model call. A failed call also gets `stopReason: "error"`, and an aborted one gets `stopReason: "aborted"`.
185
186On the client:
187
188```typescript
189import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
190
191const { messages } = useChat({
192 connection: fetchServerSentEvents("/api/chat"),
193});
194
195for (const message of messages) {
196 const tanstack = message.metadata?.tanstack;
197 console.log(tanstack?.responseId, tanstack?.source, tanstack?.stopReason);
198}
199```
200
201No `responseId`? The provider sent no generation ID. The adapter never fills it with an HTTP request ID.
202
203## Threads and runs
204
205Two ids frame every stream. They come from the AG-UI protocol, not from a storage layer.
206
207- A **thread** (`threadId`) is the conversation. It stays the same across every exchange, reload, and device.
208- A **run** (`runId`) is one execution inside that thread. It spans `RUN_STARTED` to `RUN_FINISHED` (or `RUN_ERROR`). Every start mints a fresh run id. A thread collects many runs over its life.
209
210Tool calls and follow-up responses stream inside the same run. The whole [agentic cycle](./agentic-cycle) is one run, however many loops it takes.
211
212```mermaid
213flowchart LR
214 subgraph thread ["Thread (threadId, stable)"]
215 direction LR
216 subgraph r1 ["Run r1, finished"]
217 direction TB
218 e1["RUN_STARTED then text then tool call then tool result then final text then RUN_FINISHED"]
219 end
220 subgraph r2 ["Run r2, finished"]
221 direction TB
222 e2["RUN_STARTED then text then RUN_FINISHED"]
223 end
224 subgraph r3 ["Run r3, running"]
225 direction TB
226 e3["RUN_STARTED then text"]
227 end
228 r1 --> r2 --> r3
229 end
230```
231
232Because run ids are short-lived, anything long-lived anchors on the thread:
233
234- [Resumable streams](../resumable-streams/overview) log delivery per `runId`
235- [Server persistence](../persistence/chat-persistence#threads-runs-and-turns) stores the transcript per `threadId`
236
237The media generation hooks take a `threadId` too. There it names a slot, not a conversation. See [Id map](../persistence/id-map).
238
239## Tool input and output
240
241SSE and HTTP `TOOL_CALL_END` does not carry parsed `input`. `metadata.tanstack.args` carries the tool argument string as the provider sent it. In-process `chat()` still has `input`, parsed from that string. Tool input and output also live on `UIMessage` parts.
242
243On the server, feed chunks into `StreamProcessor`. On the client, read `useChat` `messages`.
244
245### Server
246
247```typescript
248import { chat, StreamProcessor, toolDefinition } from "@tanstack/ai";
249import { openaiText } from "@tanstack/ai-openai";
250import { z } from "zod";
251
252const weatherTool = toolDefinition({
253 name: "get_weather",
254 description: "Get weather for a location",
255 inputSchema: z.object({
256 location: z.string(),
257 unit: z.enum(["celsius", "fahrenheit"]).optional(),
258 }),
259});
260
261const stream = chat({
262 adapter: openaiText("gpt-5.6"),
263 messages: [{ role: "user", content: "What is the weather in Paris?" }],
264 tools: [weatherTool],
265});
266
267const processor = new StreamProcessor();
268for await (const chunk of stream) {
269 processor.processChunk(chunk);
270}
271processor.finalizeStream();
272
273for (const message of processor.getMessages()) {
274 for (const part of message.parts) {
275 if (part.type === "tool-call") {
276 console.log(part.name, part.input, part.output);
277 }
278 }
279}
280```
281
282### Type-safe tool call events
283
284Pass your `.client()` tools to `useChat`. A check on `part.name` narrows `part.input` and `part.output`:
285
286```typescript
287import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
288import { toolDefinition } from "@tanstack/ai";
289import { z } from "zod";
290
291const weatherTool = toolDefinition({
292 name: "get_weather",
293 description: "Get weather for a location",
294 inputSchema: z.object({
295 location: z.string(),
296 unit: z.enum(["celsius", "fahrenheit"]).optional(),
297 }),
298}).client(async (input) => {
299 return { location: input.location };
300});
301
302const { messages } = useChat({
303 connection: fetchServerSentEvents("/api/chat"),
304 tools: [weatherTool],
305});
306
307for (const message of messages) {
308 for (const part of message.parts) {
309 if (part.type === "tool-call" && part.name === "get_weather") {
310 console.log(part.input?.location);
311 }
312 }
313}
314```
315
316You now know which chunk is text, which is a tool, and which id is the conversation versus one run.