|
| 1 | +--- |
| 2 | +title: 'Structured Output That Remembers Across Turns' |
| 3 | +published: 2026-05-19 |
| 4 | +excerpt: 'useChat({ outputSchema }) used to keep one slot for partial/final, so multi-turn structured chats lost prior turns the moment a new one streamed in. Every assistant turn now carries its own typed StructuredOutputPart on its UIMessage. History is preserved by default, and the schema generic threads all the way down to messages[i].parts[j].data.' |
| 5 | +library: ai |
| 6 | +authors: |
| 7 | + - Alem Tuzlak |
| 8 | +--- |
| 9 | + |
| 10 | + |
| 11 | + |
| 12 | +You ask the LLM for a recipe. It plates up _Spaghetti Pomodoro_ — title, cuisine, servings, ingredients, steps, all typed against your schema. Beautiful. You ask it to make the recipe vegan. A new recipe streams in. |
| 13 | + |
| 14 | +Then the first one vanishes. |
| 15 | + |
| 16 | +That used to be the deal with `useChat({ outputSchema })`: one hook-level `partial` / `final` slot. The instant a new turn started streaming, the previous turn's recipe was clobbered. Multi-turn anything (recipe refinement, ticket triage, iterative form filling) needed manual history plumbing — you'd intercept every chunk, snapshot `final` into your own state, juggle a `recipes[]` array yourself, and keep it in sync with `messages[]` to avoid drift. The schema's type safety also stopped at `partial` / `final`; once a structured payload landed in your local array, it was `unknown` again unless you cast. |
| 17 | + |
| 18 | +We just shipped a different shape. Every assistant turn now carries its own typed `structured-output` part on its `UIMessage`. History is preserved by default. The schema generic threads all the way down to `messages[i].parts.find(p => p.type === 'structured-output').data` — no casts, no manual tracking. Same `useChat` hook, same `outputSchema` option, less code in your component. If you missed the prior post on streaming a single typed object end-to-end, [start here](https://tanstack.com/blog/streaming-structured-output) — that piece is the antecedent to this one. |
| 19 | + |
| 20 | +This post walks through what changed, why it matters for any multi-turn UI, and how to build the recipe-builder pattern end-to-end in roughly 80 lines (split across a server route and a client component). |
| 21 | + |
| 22 | +## The old shape |
| 23 | + |
| 24 | +The previous `useChat({ outputSchema })` exposed two values that tracked the _current_ run: |
| 25 | + |
| 26 | +- `partial` — `DeepPartial<T>`, the progressively-parsed object as JSON streamed in |
| 27 | +- `final` — `T | null`, the validated object once `structured-output.complete` fired |
| 28 | + |
| 29 | +On a single-turn extractor (paste a paragraph → get a typed `Person`), this was perfect. Field-by-field reveal as the JSON streamed, validated payload on terminal event, one render to consume both. |
| 30 | + |
| 31 | +On a multi-turn chat it fell apart. `partial` and `final` were a _single slot_, scoped to whichever run was most recent. As soon as you called `sendMessage()` again, the previous turn's `final` was gone. The runtime had no place to keep it — the typed structured payload didn't live on the message itself, only in this transient hook state. |
| 32 | + |
| 33 | +The workaround we'd see in user code: |
| 34 | + |
| 35 | +```tsx |
| 36 | +const [recipes, setRecipes] = useState<Array<Recipe>>([]) |
| 37 | + |
| 38 | +const { sendMessage, final } = useChat({ |
| 39 | + outputSchema: RecipeSchema, |
| 40 | + connection: fetchServerSentEvents('/api/recipes'), |
| 41 | + onFinish: () => { |
| 42 | + if (final) setRecipes((prev) => [...prev, final]) |
| 43 | + }, |
| 44 | +}) |
| 45 | +``` |
| 46 | + |
| 47 | +Three problems with that: |
| 48 | + |
| 49 | +1. **The data lives in two places now.** `messages[]` has the assistant turns; `recipes[]` has the typed objects. Keeping them in sync (across reloads, retries, edits, server snapshots, replays) is your problem. |
| 50 | +2. **The model can't see the history.** Your `recipes[]` array is local to the component, the wire layer never sees it. When the user types "now make the vegan one cheaper," the LLM has no idea what "the vegan one" refers to; it only sees the raw text of each prior turn, with the structured response stripped to whatever it landed on the original `TextPart` as. Multi-turn refinement collapses. |
| 51 | +3. **You lose the schema's type safety.** `recipes` is typed, but the moment you try to round-trip a prior recipe back into the conversation, you're stringifying a typed object into the wire payload by hand. The library can't help you because it doesn't know `recipes` exists. |
| 52 | + |
| 53 | +The right place for this state is _on the message it came from_. That's what we shipped. |
| 54 | + |
| 55 | +## The new shape: typed parts on every assistant message |
| 56 | + |
| 57 | +Every `UIMessage` has a `parts: MessagePart[]` array. Before, the variants were `text`, `image`, `audio`, `video`, `document`, `tool-call`, `tool-result`, `thinking`. We added one: |
| 58 | + |
| 59 | +```ts |
| 60 | +type StructuredOutputPart<TData = unknown> = { |
| 61 | + type: 'structured-output' |
| 62 | + status: 'streaming' | 'complete' | 'error' |
| 63 | + /** Progressive parse — populated while streaming and after complete. */ |
| 64 | + partial?: DeepPartial<TData> |
| 65 | + /** Validated final object — set when status === 'complete'. */ |
| 66 | + data?: TData |
| 67 | + /** Accumulating JSON buffer — source of truth for the wire round-trip. */ |
| 68 | + raw: string |
| 69 | + reasoning?: string |
| 70 | + errorMessage?: string |
| 71 | +} |
| 72 | +``` |
| 73 | +
|
| 74 | +The runtime routes `TEXT_MESSAGE_CONTENT` deltas (the streaming JSON bytes) into this part instead of building a `TextPart`. On the terminal `structured-output.complete` event, `status` flips to `'complete'` and `data` is populated with the validated object. Every assistant turn produces a _new_ assistant message, which carries its _own_ `structured-output` part. The previous turn's part is untouched. |
| 75 | +
|
| 76 | +The hook-level `partial` and `final` still exist, they're derived from the _latest_ assistant message's part now, instead of being a sticky slot. That means they read `{}` and `null` between `sendMessage()` and the first chunk (because no new assistant message exists yet), and they snap to the freshest turn's payload as it streams. The migration is zero, the same code that read `partial` / `final` for a single-turn extractor reads identical values in the new shape. |
| 77 | +
|
| 78 | +What changed is everything _else_. Walking `messages[]` now exposes the full history of typed objects: |
| 79 | +
|
| 80 | +```tsx |
| 81 | +type RecipePart = StructuredOutputPart<Recipe> |
| 82 | + |
| 83 | +messages.map((m) => { |
| 84 | + if (m.role === 'assistant') { |
| 85 | + const part = m.parts.find( |
| 86 | + (p): p is RecipePart => p.type === 'structured-output', |
| 87 | + ) |
| 88 | + // part.data is Recipe (the schema-inferred type) — no cast. |
| 89 | + // part.partial is DeepPartial<Recipe>. |
| 90 | + if (part) return <RecipeCard part={part} /> |
| 91 | + } |
| 92 | + return null |
| 93 | +}) |
| 94 | +``` |
| 95 | +
|
| 96 | +The schema generic flows through `useChat<TTools, TSchema>` → `UIMessage<TTools, TData>` → `MessagePart<TTools, TData>` → `StructuredOutputPart<TData>`, so `part.data` resolves to `Recipe` with no cast. The `RecipePart` alias is for readability; you can inline `Extract<typeof p, { type: 'structured-output' }>` instead if you'd rather not name it. The same flow runs in Vue (`computed`), Solid (`createMemo`), and Svelte (`$derived.by`) — the parity work shipped in the same release. |
| 97 | +
|
| 98 | +## Building a recipe refinement loop |
| 99 | +
|
| 100 | +Here's the full recipe-builder pattern. Server endpoint first: |
| 101 | +
|
| 102 | +```ts |
| 103 | +// app/api/recipes/route.ts |
| 104 | +import { chat, toServerSentEventsResponse } from '@tanstack/ai' |
| 105 | +import { openaiText } from '@tanstack/ai-openai' |
| 106 | +import { z } from 'zod' |
| 107 | + |
| 108 | +export const RecipeSchema = z.object({ |
| 109 | + title: z.string(), |
| 110 | + cuisine: z.string(), |
| 111 | + servings: z.number(), |
| 112 | + estimatedCostUsd: z.number(), |
| 113 | + ingredients: z.array(z.object({ item: z.string(), amount: z.string() })), |
| 114 | + steps: z.array(z.string()), |
| 115 | + tips: z.array(z.string()), |
| 116 | +}) |
| 117 | + |
| 118 | +export type Recipe = z.infer<typeof RecipeSchema> |
| 119 | + |
| 120 | +const SYSTEM = `You are a chef. Reply with a single recipe matching the JSON schema. When the user asks for modifications, produce a new recipe in the same shape that reflects the change.` |
| 121 | + |
| 122 | +export async function POST(request: Request) { |
| 123 | + const { messages } = await request.json() |
| 124 | + const stream = chat({ |
| 125 | + adapter: openaiText('gpt-5.2'), |
| 126 | + messages, |
| 127 | + systemPrompts: [SYSTEM], |
| 128 | + outputSchema: RecipeSchema, |
| 129 | + stream: true, |
| 130 | + }) |
| 131 | + return toServerSentEventsResponse(stream) |
| 132 | +} |
| 133 | +``` |
| 134 | +
|
| 135 | +That's the whole server side. The only structured-output-specific lines are `outputSchema: RecipeSchema` and `stream: true`. The runtime takes care of converting the schema to JSON Schema, hitting the provider's native structured-output API, validating the response, and emitting `structured-output.start` + `structured-output.complete` events to the client. |
| 136 | +
|
| 137 | +Client: |
| 138 | +
|
| 139 | +```tsx |
| 140 | +import { useState } from 'react' |
| 141 | +import { useChat, fetchServerSentEvents } from '@tanstack/ai-react' |
| 142 | +import type { StructuredOutputPart } from '@tanstack/ai-client' |
| 143 | +import { RecipeSchema, type Recipe } from './api/recipes' |
| 144 | + |
| 145 | +type RecipePart = StructuredOutputPart<Recipe> |
| 146 | + |
| 147 | +export function RecipeBuilder() { |
| 148 | + const [input, setInput] = useState('') |
| 149 | + |
| 150 | + const { messages, sendMessage, isLoading } = useChat({ |
| 151 | + outputSchema: RecipeSchema, |
| 152 | + connection: fetchServerSentEvents('/api/recipes'), |
| 153 | + }) |
| 154 | + |
| 155 | + return ( |
| 156 | + <div> |
| 157 | + {messages.map((m) => { |
| 158 | + if (m.role === 'user') { |
| 159 | + const text = m.parts |
| 160 | + .filter((p) => p.type === 'text') |
| 161 | + .map((p) => p.content) |
| 162 | + .join('') |
| 163 | + return <UserPrompt key={m.id} text={text} /> |
| 164 | + } |
| 165 | + if (m.role === 'assistant') { |
| 166 | + const part = m.parts.find( |
| 167 | + (p): p is RecipePart => p.type === 'structured-output', |
| 168 | + ) |
| 169 | + if (!part) return null |
| 170 | + return <RecipeCard key={m.id} part={part} /> |
| 171 | + } |
| 172 | + return null |
| 173 | + })} |
| 174 | + |
| 175 | + <input value={input} onChange={(e) => setInput(e.target.value)} /> |
| 176 | + <button |
| 177 | + onClick={() => { |
| 178 | + sendMessage(input) |
| 179 | + setInput('') |
| 180 | + }} |
| 181 | + disabled={isLoading || !input.trim()} |
| 182 | + > |
| 183 | + {isLoading ? 'Cooking…' : 'Cook'} |
| 184 | + </button> |
| 185 | + </div> |
| 186 | + ) |
| 187 | +} |
| 188 | + |
| 189 | +function RecipeCard({ part }: { part: RecipePart }) { |
| 190 | + // `data` is Recipe (typed by the schema). `partial` is DeepPartial<Recipe>. |
| 191 | + // Both are typed — no cast, no `unknown`. |
| 192 | + const recipe = part.data ?? part.partial ?? {} |
| 193 | + return ( |
| 194 | + <article> |
| 195 | + <h3>{recipe.title ?? 'Plating up…'}</h3> |
| 196 | + {recipe.cuisine && <p>{recipe.cuisine}</p>} |
| 197 | + {recipe.ingredients?.map((ing, i) => ( |
| 198 | + <li key={i}> |
| 199 | + {ing?.amount} {ing?.item} |
| 200 | + </li> |
| 201 | + ))} |
| 202 | + </article> |
| 203 | + ) |
| 204 | +} |
| 205 | +``` |
| 206 | +
|
| 207 | +That's the entire client side. There's no separate `recipes[]` state, no `onFinish` callback, no manual history sync. Each `sendMessage()` triggers a new run, which produces a new assistant message, which carries its own typed structured-output part. The render loop walks `messages` and the new card just lands. |
| 208 | +
|
| 209 | +Try it: |
| 210 | +
|
| 211 | +> "Pasta dinner for two, under $15." → recipe lands. |
| 212 | +> |
| 213 | +> "Now make it vegan." → second recipe lands. The first is still on screen. |
| 214 | +> |
| 215 | +> "Add a salad and make it gluten-free." → third recipe lands. Both previous turns are still there. |
| 216 | +
|
| 217 | +## How the round-trip stays coherent |
| 218 | +
|
| 219 | +Multi-turn structured chats only work if the model sees its own prior responses on each follow-up turn. Otherwise turn N+1 has no idea what "make it vegan" refers to. |
| 220 | +
|
| 221 | +The wire layer handles this. When `useChat` sends turn N+1, it serializes the conversation back through `uiMessageToModelMessages`. For each assistant message with a completed `structured-output` part, the converter emits: |
| 222 | +
|
| 223 | +```ts |
| 224 | +{ role: 'assistant', content: part.raw } |
| 225 | +``` |
| 226 | +
|
| 227 | +`part.raw` is the original JSON the model produced, preserved byte-for-byte from the streaming bytes that built the part in the first place. The model sees its own prior recipe verbatim and can reason about modifications. There's a defensive fallback (`JSON.stringify(part.data)`) for terminal-only completes that arrived without streamed bytes, plus a "drop the turn if we can't serialize it" guard for unserializable `data` like `BigInt`s or circular refs. Streaming and errored parts are dropped from the round-trip; you don't want to feed an incomplete JSON fragment back to the LLM. |
| 228 | +
|
| 229 | +You don't see any of this. You called `sendMessage('now make it vegan')` and the model knew what it was modifying. |
| 230 | +
|
| 231 | +## The schema generic threads through every framework |
| 232 | +
|
| 233 | +The same release shipped parity across the framework hook packages: `@tanstack/ai-react`, `@tanstack/ai-vue`, `@tanstack/ai-solid`, and `@tanstack/ai-svelte` (which uses `createChat` instead of `useChat`). Each one threads the `TSchema` generic the same way: |
| 234 | +
|
| 235 | +- `useChat<TTools, TSchema>` (or `createChat<TTools, TSchema>` for Svelte) substitutes `TData = InferSchemaType<TSchema>` when a schema is supplied. |
| 236 | +- `messages` becomes `Array<UIMessage<TTools, TData>>`. |
| 237 | +- `MessagePart<TTools, TData>` substitutes `StructuredOutputPart<TData>` into the discriminated union. |
| 238 | +
|
| 239 | +Net effect: in any of the four frameworks, with `outputSchema: RecipeSchema`, `messages[i].parts.find(p => p.type === 'structured-output').data` resolves to `Recipe | undefined`. Default `TData = unknown` keeps every existing consumer that doesn't pass a schema source-compatible. |
| 240 | +
|
| 241 | +`@tanstack/ai-preact` doesn't support `outputSchema` yet; that's tracked separately. |
| 242 | +
|
| 243 | +## When to use this |
| 244 | +
|
| 245 | +The multi-turn pattern lights up any UI where: |
| 246 | +
|
| 247 | +- Users iterate on a structured object across turns (recipe builder, design spec refinement, ticket triage, A/B copy variants). |
| 248 | +- You want to render the history of typed objects, not just the latest. |
| 249 | +- You want the model to remember its own structured responses on follow-ups without you serializing them yourself. |
| 250 | +
|
| 251 | +For a single round-trip (one prompt, one typed object), use [`chat({ outputSchema })`](https://tanstack.com/ai/docs/structured-outputs/one-shot), the non-streaming activity is simpler. For a streaming UI that progressively fills in one object (the classic field-by-field form), use [`useChat({ outputSchema })`](https://tanstack.com/ai/docs/structured-outputs/streaming) and read `partial` / `final`, the new shape preserves that surface unchanged. Use [multi-turn](https://tanstack.com/ai/docs/structured-outputs/multi-turn) when history is a feature, not a chore. |
| 252 | +
|
| 253 | +## Try it |
| 254 | +
|
| 255 | +The full recipe-builder UI ships in the [`ts-react-chat` example](https://github.com/TanStack/ai/tree/main/examples/ts-react-chat) at `/generations/structured-chat`: cuisine-aware hero banners, streaming preview, multi-turn history, the lot. The docs walk through the pattern at [structured-outputs/multi-turn](https://tanstack.com/ai/docs/structured-outputs/multi-turn). |
| 256 | +
|
| 257 | +If you already use `useChat({ outputSchema })`, you don't need to change anything to get the new types — `partial` and `final` keep working. You opt into multi-turn the moment you walk `messages` instead of just reading the hook-level sugar. |
| 258 | +
|
| 259 | +[**Read the multi-turn docs →**](https://tanstack.com/ai/docs/structured-outputs/multi-turn) |
0 commit comments