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

multi-turn.md

232 lines8.2 KB

1---
2title: Multi-Turn Structured Chat
3id: structured-outputs-multi-turn
4order: 4
5description: "Let users change a typed object over many turns and keep every version on screen. Each run adds an assistant message with its own structured-output part, 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​
17Each turn of a structured chat returns the same schema. Earlier objects stay in the thread so the user can compare them.
18​
19Each structured run adds a new assistant message with its own typed `structured-output` part. Walk `messages` and render one card per part.
20​
21## Quick setup
22​
23This setup assumes chat already works in your app and `zod` is installed.
24​
25### 1. Define the schema
26​
27```typescript
28// schemas/recipe.ts
29import { z } from "zod";
30​
31export const RecipeSchema = z.object({
32 title: z.string(),
33 cuisine: z.string(),
34 servings: z.number(),
35 estimatedCostUsd: z.number(),
36 ingredients: z.array(z.object({ item: z.string(), amount: z.string() })),
37 steps: z.array(z.string()),
38 tips: z.array(z.string()),
39});
40```
41​
42### 2. Add the server endpoint
43​
44The server sees the full history on each request and returns one structured run:
45​
46```typescript
47// api/structured-chat.ts
48import {
49 chat,
50 chatParamsFromRequest,
51 toServerSentEventsResponse,
52} from "@tanstack/ai";
53import { openaiText } from "@tanstack/ai-openai";
54import { RecipeSchema } from "../schemas/recipe";
55​
56const SYSTEM_PROMPT =
57 "You are a chef assistant. Always respond with one recipe that matches the JSON schema. When the user asks for a change, return a new recipe in the same shape.";
58​
59export async function POST(request: Request) {
60 const { messages, threadId, runId } = await chatParamsFromRequest(request);
61​
62 const stream = chat({
63 adapter: openaiText("gpt-6.1-sol"),
64 messages,
65 threadId,
66 runId,
67 systemPrompts: [SYSTEM_PROMPT],
68 outputSchema: RecipeSchema,
69 stream: true,
70 });
71​
72 return toServerSentEventsResponse(stream);
74```
75​
76### 3. Render one card per turn
77​
78```tsx
79import { useState } from "react";
80import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
81import { z } from "zod";
82​
83// The same schema as schemas/recipe.ts. In your app, import it from that file.
84const RecipeSchema = z.object({
85 title: z.string(),
86 cuisine: z.string(),
87 servings: z.number(),
88 estimatedCostUsd: z.number(),
89 ingredients: z.array(z.object({ item: z.string(), amount: z.string() })),
90 steps: z.array(z.string()),
91 tips: z.array(z.string()),
92});
93​
94export function RecipeChat() {
95 const [input, setInput] = useState("");
96 const { messages, sendMessage, isLoading } = useChat({
97 connection: fetchServerSentEvents("/api/structured-chat"),
98 threadId: "support-chat",
99 outputSchema: RecipeSchema,
100 });
101​
102 return (
103 <div>
104 {messages.map((m) => {
105 if (m.role === "user") {
106 const text = m.parts
107 .map((p) => (p.type === "text" ? p.content : ""))
108 .join("");
109 return <p key={m.id}>You: {text}</p>;
110 }
111​
112 const part = m.parts.find(
113 (p): p is Extract<typeof p, { type: "structured-output" }> =>
114 p.type === "structured-output",
115 );
116 if (!part) return null;
117​
118 // `data` is the full Recipe. `partial` fills in while the JSON streams.
119 const recipe = part.status === "complete" ? part.data : part.partial;
120​
121 return (
122 <article key={m.id}>
123 <h3>{recipe?.title ?? "Cooking..."}</h3>
124 <ul>
125 {recipe?.ingredients?.map((ing, i) => (
126 <li key={i}>
127 {ing?.amount} {ing?.item}
128 </li>
129 ))}
130 </ul>
131 {part.status === "error" && <p>Failed: {part.errorMessage}</p>}
132 </article>
133 );
134 })}
135​
136 <input
137 value={input}
138 onChange={(e) => setInput(e.target.value)}
139 disabled={isLoading}
140 />
141 <button
142 disabled={isLoading}
143 onClick={() => {
144 void sendMessage(input);
145 setInput("");
146 }}
147 >
148 Send
149 </button>
150 </div>
151 );
153```
154​
155Ask for a pasta recipe, then send "make it vegan". A second card appears under the first. The first card does not change.
156​
157## How it works
158​
159- Each successful structured run adds a new assistant message with its own `structured-output` part. Old parts stay as they are.
160- `part.data` has the type that your schema infers (`Recipe` here). The schema type flows from `useChat({ outputSchema })` into `messages`.
161- On the next turn, the client sends the `raw` JSON of each complete part back as assistant content. The model sees its earlier recipes and can change them.
162- The hook-level `partial` and `final` still work. They show only the latest turn. Use them for a small "latest recipe" widget, and walk `messages` for the history.
163​
164A run can also hold assistant messages with no structured-output part, for example a plain-text message before the JSON. Always find the part by its type.
165​
166The example app has a full version of this UI at `examples/ts-react-chat/src/routes/generations.structured-chat.tsx`. For React Native, the Expo example streams the same recipe pattern into native cards. See [Quick Start: React Native](../getting-started/quick-start-react-native).
167​
168## Advanced
169​
170### The part type
171​
172```typescript
173import type { DeepPartial } from "@tanstack/ai";
174​
175type StructuredOutputPart<TData> = {
176 type: "structured-output";
177 status: "streaming" | "complete" | "error";
178 /** Progressive parse of `raw`. Set while streaming and after complete. */
179 partial?: DeepPartial<TData>;
180 /** The full object. Set when `status === "complete"`. */
181 data?: TData;
182 /** The JSON text. This is what the next turn sends to the model. */
183 raw: string;
184 /** Reasoning tokens from thinking models, when present. */
185 reasoning?: string;
186 /** Set when `status === "error"`. */
187 errorMessage?: string;
188};
189```
190​
191When `status` is `"complete"`, TypeScript knows that `data` is set.
192​
193### How the schema type reaches `messages`
194​
195`TData` flows from `useChat({ outputSchema })` through `UIMessage<TTools, TData>` and `MessagePart<TTools, TData>` in `@tanstack/ai-client`. The framework hooks use these types. So `messages[i].parts.find(...)` returns `StructuredOutputPart<Recipe>`, with no cast.
196​
197You can also import the named type and use it in a predicate:
198​
199```tsx ignore
200import type { StructuredOutputPart } from "@tanstack/ai-client";
201import type { z } from "zod";
202import type { RecipeSchema } from "./schemas/recipe";
203​
204type RecipePart = StructuredOutputPart<z.infer<typeof RecipeSchema>>;
205​
206const part = message.parts.find(
207 (p): p is RecipePart => p.type === "structured-output",
208);
209```
210​
211The core `@tanstack/ai` package also has `MessagePart<TData>` and `UIMessage<TData>`, with one generic and no `TTools`. You need these only at the adapter layer. For UI code, use the types from your framework package or from `@tanstack/ai-client`.
212​
213### Part states
214​
215A part usually goes from `streaming` to `complete`, or from `streaming` to `error`. A `complete` event can also arrive with no streaming deltas before it.
216​
217- While the JSON streams, only `partial` and `raw` are set.
218- `data` is set only on `complete`.
219- Render `part.data ?? part.partial` to fill the card field by field, then show the full object at the end.
220​
221Between `sendMessage()` and the first chunk, the latest turn has no structured-output part. The hook-level `partial` is `{}` and `final` is `null` in that time. To show a placeholder, check `isLoading` and whether the last message is from the user.
222​
223### What the next turn sends
224​
225- Complete parts stay on their UI messages. The client copies `part.raw` into the assistant content that goes to the model.
226- The server conversion keeps the structured-output marker. The adapters read the content for the provider.
227- Parts that are still streaming, or that failed, stay in the UI but do not go to the model.
228- If a complete part has an empty `raw` and the runtime cannot serialize `data`, the part stays in the UI but does not go to the model. This rule stops a blank assistant turn from reaching the model.
229​
230### With tools
231​
232Each turn can run tools first, then return a structured message. Tool approvals and client tools work the same way. See [With Tools](./with-tools).