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

streaming.md

231 lines12.5 KB

1---
2title: Streaming Structured Output UIs
3id: structured-outputs-streaming
4order: 3
5description: "Build a UI that fills in field by field as the model streams structured JSON. chat({ outputSchema, stream: true }) on the server, useChat({ outputSchema }) on the client — progressive partial state plus a typed terminal object."
6keywords:
7 - tanstack ai
8 - structured outputs
9 - streaming
10 - useChat outputSchema
11 - partial
12 - final
13 - DeepPartial
14 - progressive ui
15---
16​
17You have an existing chat-style endpoint and you want the structured response to populate a UI _while_ the model is generating — a form filling in field by field, a card whose ingredients list grows as JSON streams in, a typewriter preview of a JSON-typed report. Blocking on `await chat({ outputSchema })` would leave the UI dark until the whole object is ready; this guide is the alternative.
18​
19By the end you'll have a server endpoint streaming structured JSON as Server-Sent Events, and a client that reads a typed `partial` (progressive object) and `final` (completed terminal object) from `useChat`.
20​
21For a full Start app that shows a table from `partial.rows`, open [Streaming Structured Table](../tutorials/streaming-structured-table).
22​
23> **Note:** This is the streaming counterpart of [One-Shot Extraction](./one-shot). If you don't need progressive UI updates, the one-shot path is simpler. If you want users to iterate on the object across multiple turns and keep history, see [Multi-Turn Chat](./multi-turn).
24​
25## Server endpoint
26​
27```typescript
28// app/api/extract-person/route.ts (or your framework's equivalent)
29import { chat, toServerSentEventsResponse } from "@tanstack/ai";
30import { openaiText } from "@tanstack/ai-openai";
31import { z } from "zod";
32​
33const PersonSchema = z.object({
34 name: z.string().meta({ description: "The person's full name" }),
35 age: z.number().meta({ description: "The person's age in years" }),
36 email: z.string().email(),
37});
38​
39export async function POST(request: Request) {
40 const { messages } = await request.json();
41​
42 const stream = chat({
43 adapter: openaiText("gpt-5.5"),
44 messages,
45 outputSchema: PersonSchema,
46 stream: true,
47 });
48​
49 return toServerSentEventsResponse(stream);
51```
52​
53That's the entire server side. `chat({ outputSchema, stream: true })` returns a `StructuredOutputStream<InferSchemaType<typeof PersonSchema>>` — an `AsyncIterable` of standard streaming events plus a terminal `structured-output.complete` event carrying the completed object. `toServerSentEventsResponse` knows what to do with it.
54​
55## Client with `useChat`
56​
57Pass the same schema to `useChat`. The hook gives you a progressively-parsed `partial` and a typed `final`:
58​
59```tsx
60import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
61import { z } from "zod";
62​
63const PersonSchema = z.object({
64 name: z.string(),
65 age: z.number(),
66 email: z.string().email(),
67});
68​
69function PersonExtractor() {
70 const { sendMessage, isLoading, partial, final } = useChat({
71 connection: fetchServerSentEvents("/api/extract-person"),
72 outputSchema: PersonSchema,
73 });
74​
75 return (
76 <form
77 onSubmit={(e) => {
78 e.preventDefault();
79 sendMessage("Extract: John Doe, 30, john@example.com");
80 }}
81 >
82 <button disabled={isLoading}>Extract</button>
83 {/* `partial` fills in field by field as JSON streams in. */}
84 <p>Name: {partial.name ?? "…"}</p>
85 <p>Age: {partial.age ?? "…"}</p>
86 <p>Email: {partial.email ?? "…"}</p>
87 {final && <pre>Completed: {JSON.stringify(final, null, 2)}</pre>}
88 </form>
89 );
91```
92​
93What the hook does for you:
94​
95- **`partial`** is `DeepPartial<z.infer<typeof PersonSchema>>` — every property optional, every nested array element optional. Updated from `TEXT_MESSAGE_CONTENT` deltas via the runtime's partial-JSON parser. The hook derives it from the latest assistant message's `structured-output` part (see [Multi-Turn Chat](./multi-turn) for why that distinction matters), so it reads `{}` between `sendMessage()` and the first chunk without any extra reset state.
96- **`final`** is `z.infer<typeof PersonSchema> | null` — the completed terminal payload from the `structured-output.complete` event. `null` until the run completes successfully.
97- **`outputSchema`** is used purely for client-side TypeScript inference. The streaming path does not run Standard Schema validation; validate the completed object in the consumer when required.
98- The same shape works for **non-streaming adapters too**. If an adapter (Anthropic, Gemini, Ollama) returns a single `structured-output.complete` event with no incremental deltas, `partial` stays `{}` and `final` populates when the event arrives. Same consumer code. Claude Code and Codex emit `structured-output.complete` from the harness event. OpenCode, Grok Build, and `acpCompatible` parse the last assistant text at the end. In both cases `partial` stays empty until `final` is set. See [Harness Agents](./harnesses).
99​
100`outputSchema` is optional: omit it and `useChat` returns its standard shape without `partial` / `final`.
101​
102## Rendering reasoning and tool calls
103​
104`partial` / `final` cover the structured payload. Reasoning tokens and tool calls land where they would in any other chat — on `messages[…].parts`:
105​
106| Chunk type | Where it lands on `messages[i].parts` |
107|---|---|
108| `REASONING_MESSAGE_CONTENT` | `ThinkingPart` on the assistant message |
109| `TOOL_CALL_START` / `_ARGS` / `_END` | `ToolCallPart` on the assistant message |
110| `TOOL_CALL_RESULT` | `ToolResultPart` on the tool message |
111| `TEXT_MESSAGE_CONTENT` (with `outputSchema` set) | `StructuredOutputPart` on the assistant message — the JSON deltas accumulate into `part.raw` and the progressive parse populates `part.partial` |
112| `TEXT_MESSAGE_CONTENT` (no `outputSchema`) | `TextPart` on the assistant message |
113​
114So render reasoning, tool calls, and the typed object from `messages[].parts`. `final` and `partial` are shortcuts for the latest `structured-output` part only.
115​
116```tsx ignore
117return (
118 <>
119 {messages.map((message) => (
120 <div key={message.id}>
121 {message.parts.map((part, i) => {
122 if (part.type === "thinking") {
123 return <ReasoningView key={i} text={part.content} />;
124 }
125 if (part.type === "tool-call") {
126 return <ToolCallView key={i} part={part} />;
127 }
128 if (part.type === "text") {
129 return <p key={i}>{part.content}</p>;
130 }
131 if (part.type === "structured-output") {
132 return (
133 <StructuredView key={i} data={part.data ?? part.partial} />
134 );
135 }
136 return null;
137 })}
138 </div>
139 ))}
140 </>
141);
142```
143​
144The `structured-output` part fields:
145​
146- `data`: the validated object after `structured-output.complete`
147- `partial`: a progressive parse of `raw` while JSON streams
148- `raw`: the source JSON string
149- `status`: `streaming`, `complete`, or `error`
150​
151`final` equals `data` on the latest assistant turn. Walk `parts` when you need history, tool calls, or reasoning.
152​
153> **Migration note:** Earlier versions of TanStack AI routed structured JSON deltas through a `TextPart` and required you to filter that part out of your renderer. That hack is gone — `TEXT_MESSAGE_CONTENT` on a structured-output run now routes into a dedicated `StructuredOutputPart` (with `raw`, `partial`, `data`, `status`, optional `errorMessage`). If your render loop still has an explicit `if (part.type === "text") return null;` line specifically for hiding structured JSON, you can remove it.
154​
155> **Going lower-level?** `useChat` still exposes `onChunk` if you want to observe individual chunks alongside the managed `partial` / `final` state (e.g. to drive a custom progress UI). Internal partial/final tracking runs first, then your `onChunk` callback fires with the same chunk — the two paths compose.
156​
157`useChat` (React, Vue, Solid) and `createChat` (Svelte) all accept the same `outputSchema` option and expose `partial` / `final` with the same semantics — only the reactivity primitive differs (React state, Vue `shallowRef`, Solid `Accessor`, Svelte reactive getter). See [Quick Start](../getting-started/quick-start) for the local idioms.
158​
159## What the stream contains
160​
161`chat({ outputSchema, stream: true })` returns a `StructuredOutputStream<T>`. The stream includes a `CUSTOM` event named `structured-output.complete` before `RUN_FINISHED`. The completion event carries the parsed object. A parsing failure emits `RUN_ERROR` instead of a successful `RUN_FINISHED`.
162​
163```typescript ignore
165 type: "CUSTOM",
166 name: "structured-output.complete",
167 value: {
168 object: T; // completed, parsed, typed
169 raw: string; // full accumulated JSON text
170 reasoning?: string; // present only for thinking/reasoning models
171 },
172 // ...standard event fields (timestamp, …)
173 // model lives in metadata.tanstack when present
175```
176​
177A `structured-output.start` event fires once at the beginning of the run carrying `{ messageId }`. Its job is to tell the client "the next batch of `TEXT_MESSAGE_CONTENT` deltas belongs to the assistant message with this id — route them into a `StructuredOutputPart` instead of building a free-form `TextPart`." The runtime also attaches the same `messageId` to the terminal `structured-output.complete` event's `value` so the client snaps the right assistant message's part on the way out — that extra field isn't on the public `StructuredOutputCompleteEvent<T>` shape (since consumer code typically doesn't need it; the start event already carries it), but you can read it off `value` at runtime if you need to.
178​
179## Adapter coverage
180​
181Streaming structured output works with **every adapter**, but only some support a true single-request streaming wire format:
182​
183| Adapter | Behavior with `outputSchema` + `stream: true` |
184|---|---|
185| `@tanstack/ai-openai` | Native single-request stream (Responses API, `text.format: json_schema`) |
186| `@tanstack/ai-openrouter` | Native single-request stream (`response_format: json_schema`) |
187| `@tanstack/ai-grok` | Native single-request stream (Chat Completions, `response_format: json_schema`) |
188| `@tanstack/ai-groq` | Native single-request stream (Chat Completions, `response_format: json_schema`) |
189| `@tanstack/ai-bedrock` | Native stream through Converse or an OpenAI-compatible API |
190| `@tanstack/ai-byteplus` | Native single-request stream on supported models; unsupported models emit `RUN_ERROR` |
191| `@tanstack/ai-llmgateway` | Native single-request stream (Chat Completions, `response_format: json_schema`) |
192| `@tanstack/ai-cloudflare` | Native single-request stream (Chat Completions, `response_format: json_schema`) |
193| `@tanstack/ai-lovable` | Native single-request stream (Responses or Chat Completions) |
194| Other adapters (anthropic, gemini, ollama, …) | Fallback: runs non-streaming `structuredOutput` and emits the final object as one `structured-output.complete` event |
195​
196The fallback path keeps the consumer code identical across providers — you always read the final object off `structured-output.complete` — but you won't see incremental deltas unless the adapter implements `structuredOutputStream` natively.
197​
198## Advanced: iterating the stream directly
199​
200When you don't need the SSE-over-HTTP boundary — Node scripts, CLIs, server endpoints that respond with a final JSON object instead of a stream, or tests — consume `chat({ outputSchema, stream: true })` as a plain async iterable:
201​
202```typescript ignore
203import { chat } from "@tanstack/ai";
204import { openaiText } from "@tanstack/ai-openai";
205import { z } from "zod";
206​
207const PersonSchema = z.object({
208 name: z.string(),
209 age: z.number(),
210 email: z.string().email(),
211});
212​
213const stream = chat({
214 adapter: openaiText("gpt-5.5"),
215 messages: [{ role: "user", content: "Extract: John Doe is 30, john@example.com" }],
216 outputSchema: PersonSchema,
217 stream: true,
218});
219​
220for await (const chunk of stream) {
221 if (chunk.type === "CUSTOM" && chunk.name === "structured-output.complete") {
222 // Typed against PersonSchema. Validate here when required.
223 console.log(chunk.value.object.name);
224 console.log(chunk.value.object.age);
225 }
227```
228​
229This is the same `StructuredOutputStream<T>` the server endpoint above hands to `toServerSentEventsResponse`. Pick this shape when you're a single process end-to-end; use the server-endpoint-plus-`useChat` shape when there's a network in the middle.
230​
231> **Combining with tools?** When `outputSchema`, `stream: true`, and `tools` are all set, the agent loop runs first and the structured stream emits its terminal event only after every tool completes. Tool-approval gates and client-tool invocations work the same as in a normal chat — see [With Tools](./with-tools) for the full pause/resume pattern.