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