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
31
32Later:
33
34- `REASONING_*` / `REASONING_ENCRYPTED_VALUE`: thinking content. See [Thinking and Reasoning](./thinking-content)
35- `STEP_STARTED` / `STEP_FINISHED`: `stepName` only
36- `CUSTOM`: `name` and `value`. See [Custom Events](../protocol/custom-events)
37- `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)
38
39On `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).
40
41```typescript
42import { chat } from "@tanstack/ai";
43import { openaiText } from "@tanstack/ai-openai";
44
45const stream = chat({
46 adapter: openaiText("gpt-5.6"),
47 messages: [{ role: "user", content: "Hello!" }],
48});
49
50for await (const chunk of stream) {
51 if (chunk.type === "TEXT_MESSAGE_CONTENT") {
52 console.log(chunk.delta);
53 }
54 if (chunk.type === "RUN_FINISHED") {
55 console.log(chunk.usage);
56 console.log(chunk.metadata?.tanstack?.finishReason);
57 }
58}
59```
60
61## Threads and runs
62
63Two ids frame every stream. They come from the AG-UI protocol, not from a storage layer.
64
65- A **thread** (`threadId`) is the conversation. It stays the same across every exchange, reload, and device.
66- 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.
67
68Tool calls and follow-up responses stream inside the same run. The whole [agentic cycle](./agentic-cycle) is one run, however many loops it takes.
69
70```mermaid
71flowchart LR
72 subgraph thread ["Thread (threadId, stable)"]
73 direction LR
74 subgraph r1 ["Run r1, finished"]
75 direction TB
76 e1["RUN_STARTED then text then tool call then tool result then final text then RUN_FINISHED"]
77 end
78 subgraph r2 ["Run r2, finished"]
79 direction TB
80 e2["RUN_STARTED then text then RUN_FINISHED"]
81 end
82 subgraph r3 ["Run r3, running"]
83 direction TB
84 e3["RUN_STARTED then text"]
85 end
86 r1 --> r2 --> r3
87 end
88```
89
90Because run ids are short-lived, anything long-lived anchors on the thread:
91
92- [Resumable streams](../resumable-streams/overview) log delivery per `runId`
93- [Server persistence](../persistence/chat-persistence#threads-runs-and-turns) stores the transcript per `threadId`
94
95The media generation hooks take a `threadId` too. There it names a slot, not a conversation. See [Id map](../persistence/id-map).
96
97## Tool input and output
98
99SSE and HTTP `TOOL_CALL_END` does not carry parsed `input`. In-process `chat()` still has `input`. Tool input and output also live on `UIMessage` parts.
100
101On the server, feed chunks into `StreamProcessor`. On the client, read `useChat` `messages`.
102
103### Server
104
105```typescript
106import { chat, StreamProcessor, toolDefinition } from "@tanstack/ai";
107import { openaiText } from "@tanstack/ai-openai";
108import { z } from "zod";
109
110const weatherTool = toolDefinition({
111 name: "get_weather",
112 description: "Get weather for a location",
113 inputSchema: z.object({
114 location: z.string(),
115 unit: z.enum(["celsius", "fahrenheit"]).optional(),
116 }),
117});
118
119const stream = chat({
120 adapter: openaiText("gpt-5.6"),
121 messages: [{ role: "user", content: "What is the weather in Paris?" }],
122 tools: [weatherTool],
123});
124
125const processor = new StreamProcessor();
126for await (const chunk of stream) {
127 processor.processChunk(chunk);
128}
129processor.finalizeStream();
130
131for (const message of processor.getMessages()) {
132 for (const part of message.parts) {
133 if (part.type === "tool-call") {
134 console.log(part.name, part.input, part.output);
135 }
136 }
137}
138```
139
140### Type-safe tool call events
141
142Pass your `.client()` tools to `useChat`. A check on `part.name` narrows `part.input` and `part.output`:
143
144```typescript
145import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
146import { toolDefinition } from "@tanstack/ai";
147import { z } from "zod";
148
149const weatherTool = toolDefinition({
150 name: "get_weather",
151 description: "Get weather for a location",
152 inputSchema: z.object({
153 location: z.string(),
154 unit: z.enum(["celsius", "fahrenheit"]).optional(),
155 }),
156}).client(async (input) => {
157 return { location: input.location };
158});
159
160const { messages } = useChat({
161 connection: fetchServerSentEvents("/api/chat"),
162 tools: [weatherTool],
163});
164
165for (const message of messages) {
166 for (const part of message.parts) {
167 if (part.type === "tool-call" && part.name === "get_weather") {
168 console.log(part.input?.location);
169 }
170 }
171}
172```
173
174You now know which chunk is text, which is a tool, and which id is the conversation versus one run.