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

multi-turn.md

229 lines11.8 KB

1---
2title: Multi-Turn Structured Chat
3id: structured-outputs-multi-turn
4order: 4
5description: "Build a chat where users iterate on a typed object across multiple turns — each successfully completed structured-output run adds a typed response to message history, and messages[i].parts.find(p => p.type === 'structured-output') is typed by your schema."
6keywords:
7 - tanstack ai
8 - structured outputs
9 - multi-turn
10 - structured chat
11 - StructuredOutputPart
12 - typed message parts
13 - UIMessage
14 - recipe builder
15---
16​
17You want users to iterate on a structured object across turns. "Give me a pasta recipe under $15" → recipe card lands. "Now make it vegan" → a new recipe card lands; the old one stays visible in history. "Add a salad and make it gluten-free" → third card lands; the first two are still there to compare against.
18​
19This is the shape of a structured-output chat: each successfully completed structured-output run adds a structured-output assistant message, every old response stays renderable, and the type of `messages[i].parts.find(p => p.type === 'structured-output').data` is your schema's inferred type — not `unknown`.
20​
21By the end of this guide you'll have a chat UI that walks `messages` directly, renders one typed card per successfully completed structured-output run, and keeps history across `sendMessage()` calls.
22​
23> **Note:** If you only need a single round-trip (one prompt → one object), use [One-Shot Extraction](./one-shot). If you have one turn that streams progressively but no history, use [Streaming UIs](./streaming) — its `partial` / `final` sugar is the right surface. This page is for the case where history matters.
24​
25> **React Native recipe app:** The Expo example streams this same multi-turn
26> recipe pattern into native cards with an XHR transport selector. See
27> [Quick Start: React Native](../getting-started/quick-start-react-native) to
28> run it on Expo Go.
29​
30## How it lands on the message
31​
32When `useChat({ outputSchema })` receives the server's `structured-output.complete` event, the runtime attaches a typed `structured-output` `MessagePart` to the assistant `UIMessage` carrying the structured response. The part looks like this:
33​
34```typescript
35import type { DeepPartial } from "@tanstack/ai";
36​
37type StructuredOutputPart<TData> = {
38 type: "structured-output";
39 status: "streaming" | "complete" | "error";
40 /** Progressive parse of `raw` — populated while streaming and after complete. */
41 partial?: DeepPartial<TData>;
42 /** Completed typed object — set when `status === "complete"`. */
43 data?: TData;
44 /** Accumulating JSON text. Round-trip source of truth for the next turn. */
45 raw: string;
46 /** Optional reasoning tokens surfaced by thinking models. */
47 reasoning?: string;
48 /** Set when `status === "error"`. */
49 errorMessage?: string;
50};
51```
52​
53`TData` flows from `useChat({ outputSchema })` through the framework-package message types (`UIMessage<TTools, TData>` and `MessagePart<TTools, TData>` in `@tanstack/ai-client`, which the React / Vue / Solid / Svelte hooks re-export) down to the structured-output variant. The result: when you call `useChat({ outputSchema: RecipeSchema })`, `messages[i].parts.find(p => p.type === "structured-output")` returns `StructuredOutputPart<Recipe>` — `data` is typed as `Recipe`, `partial` as `DeepPartial<Recipe>`. No manual cast.
54​
55> **Note:** The core `@tanstack/ai` package defines `MessagePart<TData>` and `UIMessage<TData>` with a single generic (no `TTools`) — the tools generic lives in `@tanstack/ai-client` and the framework hook packages. If you're building UI, you almost always want to import from your framework package (`@tanstack/ai-react` / `-vue` / `-solid` / `-svelte`) or from `@tanstack/ai-client` — those carry both generics. The core types come into play only if you're working at the adapter layer below the client.
56​
57Each new structured response lands on a **new** assistant message with its **own** structured-output part. Earlier responses stay untouched. That's what makes "show history" trivial.
58​
59A run may also contain assistant messages without a structured-output part. Native-combined output keeps the structured JSON and its part on one assistant message. On the separate-finalization path, a plain-text assistant message can precede the structured-output assistant message. Find the part by type instead of assuming that every assistant message contains one.
60​
61## Server endpoint
62​
63The server side is the same as a single-turn streaming endpoint. `chat({ outputSchema, stream: true })` happens to be multi-turn safe out of the box because the server sees the full conversation history on every request and emits one structured-output run per request.
64​
65```typescript
66// app/api/structured-chat/route.ts
67import { chat, toServerSentEventsResponse } from "@tanstack/ai";
68import { openaiText } from "@tanstack/ai-openai";
69import { z } from "zod";
70​
71export const RecipeSchema = z.object({
72 title: z.string(),
73 cuisine: z.string(),
74 servings: z.number(),
75 estimatedCostUsd: z.number(),
76 ingredients: z.array(
77 z.object({ item: z.string(), amount: z.string() }),
78 ),
79 steps: z.array(z.string()),
80 tips: z.array(z.string()),
81});
82​
83export type Recipe = z.infer<typeof RecipeSchema>;
84​
85const SYSTEM_PROMPT = `You are a chef assistant. Always respond 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.`;
86​
87export async function POST(request: Request) {
88 const { messages } = await request.json();
89 const stream = chat({
90 adapter: openaiText("gpt-5.5"),
91 messages,
92 systemPrompts: [SYSTEM_PROMPT],
93 outputSchema: RecipeSchema,
94 stream: true,
95 });
96 return toServerSentEventsResponse(stream);
98```
99​
100Behind the scenes, when the client sends turn N, prior `UIMessage.parts` remain intact in the request. The client also mirrors each completed structured-output part's `raw` JSON into assistant content. Server conversion preserves the structured-output marker while adapters consume the provider-facing content. Multi-turn coherence is preserved without you doing anything special.
101​
102## Client: walk the messages
103​
104Here's the shape you want. `useChat` exposes `messages` (typed, schema-aware), `sendMessage`, and the hook-level `partial` / `final` sugar for the latest turn. To render history, walk `messages` directly:
105​
106```tsx ignore
107import { useState } from "react";
108import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
109import type { StructuredOutputPart } from "@tanstack/ai-client";
110import { RecipeSchema, type Recipe } from "./api/structured-chat";
111import { UserBubble } from "./components";
112​
113// The schema-typed structured-output part. Pulled out so the find()
114// predicate below stays readable.
115type RecipePart = StructuredOutputPart<Recipe>;
116​
117function StructuredChatPage() {
118 const [input, setInput] = useState("");
119​
120 const { messages, sendMessage, isLoading } = useChat({
121 outputSchema: RecipeSchema,
122 connection: fetchServerSentEvents("/api/structured-chat"),
123 });
124​
125 return (
126 <div>
127 {messages.map((m) => {
128 if (m.role === "user") {
129 const text = m.parts
130 .filter((p) => p.type === "text")
131 .map((p) => p.content)
132 .join("");
133 return <UserBubble key={m.id} text={text} />;
134 }
135 if (m.role === "assistant") {
136 // `data` is typed as `Recipe` because the schema generic flows
137 // all the way from useChat through messages[i].parts.
138 const recipePart = m.parts.find(
139 (p): p is RecipePart => p.type === "structured-output",
140 );
141 if (!recipePart) return null;
142 return <RecipeCard key={m.id} part={recipePart} />;
143 }
144 return null;
145 })}
146​
147 <input
148 value={input}
149 onChange={(e) => setInput(e.target.value)}
150 disabled={isLoading}
151 />
152 <button
153 onClick={() => {
154 sendMessage(input);
155 setInput("");
156 }}
157 disabled={isLoading}
158 >
159 Send
160 </button>
161 </div>
162 );
164​
165function RecipeCard({ part }: { part: RecipePart }) {
166 // `data` is `Recipe` once status === 'complete'. `partial` is
167 // DeepPartial<Recipe> while the model is still streaming the JSON.
168 // Read whichever is freshest — they converge on complete.
169 const recipe = part.data ?? part.partial;
170​
171 return (
172 <article>
173 <h3>{recipe?.title ?? "Plating up…"}</h3>
174 {recipe?.cuisine && <p>{recipe?.cuisine}</p>}
175 {recipe?.ingredients?.map((ing, i) => (
176 <li key={i}>
177 {ing?.amount} {ing?.item}
178 </li>
179 ))}
180 {part.status === "error" && (
181 <p>Failed: {part.errorMessage ?? "Stream failed"}</p>
182 )}
183 </article>
184 );
186```
187​
188That's it. The render loop above produces a card per structured response. When the user sends a follow-up, a new structured-output assistant message arrives — the old card stays exactly as it was.
189​
190> **See the full pattern in code:** the example app at `examples/ts-react-chat/src/routes/generations.structured-chat.tsx` ships a polished version of this exact recipe-builder UI — empty state, streaming placeholder, cuisine-aware hero banner, ingredients grid, numbered method, chef's tips block. Use it as a reference for visual layout; the data wiring matches what's shown above.
191​
192## Streaming the latest turn
193​
194A `structured-output` part normally goes `streaming` → `complete` (or `streaming` → `error`). A terminal-only `complete` event can also arrive with no prior streaming deltas. The `data` field only populates on `complete`. While the model is still emitting JSON, only `partial` and `raw` are filled in. Render against `part.data ?? part.partial` and the UI fills in field by field as bytes arrive, then snaps to the completed typed object on the terminal event.
195​
196The hook-level `partial` and `final` are still available. They're derived from the most recent structured-output part after the latest user message — the same part the render loop above already finds. `partial` returns `{}` between `sendMessage()` and the first chunk (because no structured-output part exists yet to derive from), and `final` returns `null` until the latest turn lands its `complete` event. Use them for sticky-summary widgets ("Latest recipe title: …"); use the `messages` walk for the full history view.
197​
198## Type-safe access without a named alias
199​
200The example above pulls `type RecipePart = StructuredOutputPart<Recipe>` out for readability. If you'd rather not name it, you can narrow inline with `Extract`:
201​
202```tsx ignore
203import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
204import { RecipeSchema, type Recipe } from "./api/structured-chat";
205​
206const { messages } = useChat({
207 outputSchema: RecipeSchema,
208 connection: fetchServerSentEvents("/api/structured-chat"),
209});
210​
211for (const m of messages) {
212 const recipePart = m.parts.find(
213 (p): p is Extract<typeof p, { type: "structured-output" }> =>
214 p.type === "structured-output",
215 );
216 // `recipePart` is `StructuredOutputPart<Recipe> | undefined`.
217 // `recipePart.data` is `Recipe | undefined`.
219```
220​
221Both forms produce the same typed result. Pick whichever you find more readable.
222​
223## What about the round-trip?
224​
225When turn N+1 fires, completed structured-output parts remain on their UI messages and are mirrored into provider-facing assistant content using `part.raw`. Streaming and errored parts remain UI state but are excluded from model input.
226​
227If `raw` is empty (rare — a terminal-only complete event arrived before any deltas, then the runtime couldn't serialize the `data` either), the part remains in UI state but is excluded from provider-facing content. This avoids sending a blank assistant turn to the model.
228​
229> **Combining with tools?** Multi-turn structured chats compose with the agent loop the same way single-turn streams do — each turn runs tools first, then produces a structured-output message. See [With Tools](./with-tools) for tool-approval gating and client-tool invocations inside a structured-chat run.