Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

streaming.md

257 lines10.1 KB

1---
2title: Streaming Structured Output UIs
3id: structured-outputs-streaming
4order: 3
5description: "Fill a form or card field by field while the model streams JSON. Stream with chat({ outputSchema, stream: true }) on the server and read partial and final from useChat({ outputSchema })."
6keywords:
7 - tanstack ai
8 - structured outputs
9 - streaming
10 - useChat outputSchema
11 - partial
12 - final
13 - DeepPartial
14 - progressive ui
15---
16​
17A streaming structured output emits the object as the model writes it. The UI can render each finished field before the object is complete.
18​
19Stream the JSON instead. `useChat` parses it as it arrives and gives you a typed `partial` object that fills in field by field.
20​
21## Quick setup
22​
23This setup assumes chat already works in your app. For the schema file and the `zod` install, see the [overview](./overview#quick-setup).
24​
25### 1. Stream from the server
26​
27Pass `outputSchema` and `stream: true`:
28​
29```typescript
30// api/extract-person.ts
31import {
32 chat,
33 chatParamsFromRequest,
34 toServerSentEventsResponse,
35} from "@tanstack/ai";
36import { openaiText } from "@tanstack/ai-openai";
37import { PersonSchema } from "../schemas/person";
38​
39export async function POST(request: Request) {
40 const { messages, threadId, runId } = await chatParamsFromRequest(request);
41​
42 const stream = chat({
43 adapter: openaiText("gpt-6.1-sol"),
44 messages,
45 threadId,
46 runId,
47 outputSchema: PersonSchema,
48 stream: true,
49 });
50​
51 return toServerSentEventsResponse(stream);
53```
54​
55### 2. Render `partial` on the client
56​
57```tsx
58import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
59import { PersonSchema } from "./schemas/person";
60​
61export function PersonExtractor() {
62 const { sendMessage, isLoading, partial, final } = useChat({
63 connection: fetchServerSentEvents("/api/extract-person"),
64 threadId: "support-chat",
65 outputSchema: PersonSchema,
66 });
67​
68 return (
69 <form
70 onSubmit={(e) => {
71 e.preventDefault();
72 void sendMessage("Extract: John Doe, 30, john@example.com");
73 }}
74 >
75 <button disabled={isLoading}>Extract</button>
76 <p>Name: {partial.name ?? "..."}</p>
77 <p>Age: {partial.age ?? "..."}</p>
78 <p>Email: {partial.email ?? "..."}</p>
79 {final && <pre>{JSON.stringify(final, null, 2)}</pre>}
80 </form>
81 );
83```
84​
85Click Extract. The name, age, and email appear one after the other. When the run ends, the full object shows in the `<pre>` block.
86​
87For a full TanStack Start app that fills a table from `partial.rows`, open [Streaming Structured Table](../tutorials/streaming-structured-table).
88​
89## How it works
90​
91- `partial` is `DeepPartial<T>`. Every property and every array element is optional. The hook parses the JSON deltas as they arrive. It reads `{}` from `sendMessage()` until the first chunk.
92- `final` is `T | null`. It is `null` until the run completes. Then it holds the full object from the `structured-output.complete` event.
93- The schema on `useChat` gives you types. The streaming path does not validate the object with your schema. If you need validation, do it in your own code.
94​
95Some adapters cannot stream the JSON. Anthropic and Ollama send the object as one event. Harness agents also send it at the end (see [Harness Agents](./harnesses)). In these cases `partial` stays `{}` until `final` is set. Your client code does not change.
96​
97If you leave out `outputSchema`, `useChat` returns its normal shape with no `partial` or `final`.
98​
99Vue, Solid, Svelte, Angular, Preact, and Octane take the same `outputSchema` option and return `partial` and `final`. Only the reactive type changes. See [Quick Start](../getting-started/quick-start) for the code in each framework.
100​
101## Show reasoning and tool calls too
102​
103`partial` and `final` show only the object of the latest turn. Reasoning, tool calls, and the object of every turn are on `messages[].parts`:
104​
105```tsx
106import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
107import { z } from "zod";
108​
109// The same schema as schemas/person.ts. In your app, import it from that file.
110const PersonSchema = z.object({
111 name: z.string().meta({ description: "The full name of the person" }),
112 age: z.number().meta({ description: "The age in years" }),
113 email: z.string().email(),
114});
115​
116export function PersonRun() {
117 const { messages, sendMessage } = useChat({
118 connection: fetchServerSentEvents("/api/extract-person"),
119 threadId: "support-chat",
120 outputSchema: PersonSchema,
121 });
122​
123 return (
124 <div>
125 <button onClick={() => void sendMessage("Extract: John Doe, 30")}>
126 Extract
127 </button>
128 {messages.map((message) => (
129 <div key={message.id}>
130 {message.parts.map((part, i) => {
131 if (part.type === "thinking") {
132 return <em key={i}>{part.content}</em>;
133 }
134 if (part.type === "tool-call") {
135 return (
136 <p key={part.id}>
137 {part.name} ({part.state})
138 </p>
139 );
140 }
141 if (part.type === "text") {
142 return <p key={i}>{part.content}</p>;
143 }
144 if (part.type === "structured-output") {
145 const person = part.data ?? part.partial;
146 return <p key={i}>Name: {person?.name ?? "..."}</p>;
147 }
148 return null;
149 })}
150 </div>
151 ))}
152 </div>
153 );
155```
156​
157The `structured-output` part has these fields:
158​
159- `data`: the full object, after `structured-output.complete`.
160- `partial`: the progressive parse of `raw` while the JSON streams.
161- `raw`: the source JSON string.
162- `status`: `streaming`, `complete`, or `error`.
163- `errorMessage`: set when `status` is `error`.
164​
165`final` equals `data` on the latest assistant turn.
166​
167## Advanced
168​
169### Where each chunk lands
170​
171| Chunk type | Part on `messages[i].parts` |
172| --- | --- |
173| `REASONING_MESSAGE_CONTENT` | `ThinkingPart` on the assistant message |
174| `TOOL_CALL_START` / `_ARGS` / `_END` | `ToolCallPart` on the assistant message |
175| `TOOL_CALL_RESULT` | `ToolResultPart` on the tool message |
176| `TEXT_MESSAGE_CONTENT`, with `outputSchema` | `StructuredOutputPart` on the assistant message. The JSON deltas build `part.raw`, and the parse fills `part.partial`. |
177| `TEXT_MESSAGE_CONTENT`, no `outputSchema` | `TextPart` on the assistant message |
178​
179### What the stream contains
180​
181`chat({ outputSchema, stream: true })` returns a `StructuredOutputStream<T>`. It is an `AsyncIterable` of the normal stream events, plus two `CUSTOM` events:
182​
183- `structured-output.start` fires once, when the JSON begins. It carries `{ messageId }`. The client uses this id to send the next `TEXT_MESSAGE_CONTENT` deltas into a `StructuredOutputPart` on that message.
184- `structured-output.complete` fires before `RUN_FINISHED` and carries the parsed object.
185​
186```typescript ignore
188 type: "CUSTOM",
189 name: "structured-output.complete",
190 value: {
191 object: T; // full parsed object
192 raw: string; // full JSON text
193 reasoning?: string; // only for thinking or reasoning models
194 },
195 // standard event fields, such as timestamp
196 // the model id is in metadata.tanstack when present
198```
199​
200If the parse fails, the stream emits `RUN_ERROR` in place of `RUN_FINISHED`.
201​
202At runtime, `value` on the complete event also holds the same `messageId`. The client uses it to find the right message. This field is not on the public `StructuredOutputCompleteEvent<T>` type, but you can read it from `value` if you need it.
203​
204### Adapter coverage
205​
206Streaming structured output works with every adapter. Only some send the JSON as a true stream in one request:
207​
208| Adapter | Behavior with `outputSchema` and `stream: true` |
209| --- | --- |
210| `@tanstack/ai-openai` | Native stream in one request (Responses API, `text.format: json_schema`) |
211| `@tanstack/ai-openrouter` | Native stream in one request (`response_format: json_schema`) |
212| `@tanstack/ai-grok` | Native stream in one request (Chat Completions, `response_format: json_schema`) |
213| `@tanstack/ai-groq` | Native stream in one request (Chat Completions, `response_format: json_schema`) |
214| `@tanstack/ai-bedrock` | Native stream through Converse or an OpenAI-compatible API |
215| `@tanstack/ai-byteplus` | Native stream in one request on supported models. Other models emit `RUN_ERROR`. |
216| `@tanstack/ai-llmgateway` | Native stream in one request (Chat Completions, `response_format: json_schema`) |
217| `@tanstack/ai-cloudflare` | Native stream in one request (Chat Completions, `response_format: json_schema`) |
218| `@tanstack/ai-lovable` | Native stream in one request (Responses or Chat Completions) |
219| `@tanstack/ai-gemini` | Native stream in one request (`generateContentStream`, `responseSchema`) |
220| Other adapters (Anthropic, Ollama, and more) | Runs `structuredOutput` without streaming, then emits the object as one `structured-output.complete` event |
221​
222Your client code is the same on all adapters. You see deltas only when the adapter implements `structuredOutputStream`.
223​
224### Read the stream in a script
225​
226With no HTTP boundary (a Node script, a CLI, a test), iterate the stream directly:
227​
228```typescript
229import { chat } from "@tanstack/ai";
230import { openaiText } from "@tanstack/ai-openai";
231import { PersonSchema } from "./schemas/person";
232​
233const stream = chat({
234 adapter: openaiText("gpt-6.1-sol"),
235 messages: [{ role: "user", content: "Extract: John Doe is 30, john@example.com" }],
236 threadId: "thread-1",
237 outputSchema: PersonSchema,
238 stream: true,
239});
240​
241for await (const chunk of stream) {
242 if (chunk.type === "CUSTOM" && chunk.name === "structured-output.complete") {
243 // Typed from PersonSchema. Validate here if you need to.
244 console.log(chunk.value.object.name, chunk.value.object.age);
245 }
247```
248​
249This is the same `StructuredOutputStream<T>` that the server endpoint gives to `toServerSentEventsResponse`.
250​
251### Watch each chunk with `onChunk`
252​
253`useChat` also takes `onChunk`. The hook updates `partial` and `final` first. Then it calls your `onChunk` with the same chunk. Use it for a custom progress UI.
254​
255### With tools
256​
257When you set `outputSchema`, `stream: true`, and `tools`, the agent loop runs first. The structured stream emits its complete event only after every tool finishes. Tool approvals and client tools work the same as in a normal chat. See [With Tools](./with-tools).