Open History to see the last commit
1---
2title: Structured Outputs With Tools
3id: structured-outputs-with-tools
4order: 5
5description: "Let the model call tools first, then return a typed object. Pass tools and outputSchema to the same chat() call, and handle tool approvals and client tools inside the run."
6keywords:
7 - tanstack ai
8 - structured outputs
9 - tools
10 - agent loop
11 - tool approval
12 - client tools
13 - outputSchema tools
14---
15
16The model can call tools, then return an object that matches `outputSchema`. The tool result is available before the object is filled.
17
18Pass `tools` and `outputSchema` to the same `chat()` call.
19
20New to tools? Read [Server Tools](../tools/server-tools) first.
21
22## Quick setup
23
24### 1. Define the tool and the schema
25
26```typescript group=with-tools
27// recommend.ts
28import { chat, toolDefinition } from "@tanstack/ai";
29import { openaiText } from "@tanstack/ai-openai";
30import { z } from "zod";
31
32const getProductPrice = toolDefinition({
33 name: "get_product_price",
34 description: "Get the current price of a product",
35 inputSchema: z.object({ productId: z.string() }),
36}).server(async ({ productId }) => {
37 console.log(`Looking up ${productId}`);
38 return { price: 29.99, currency: "USD" };
39});
40
41const RecommendationSchema = z.object({
42 productName: z.string(),
43 currentPrice: z.number(),
44 reason: z.string(),
45});
46```
47
48### 2. Pass both to `chat()`
49
50Add this to the same file:
51
52```typescript group=with-tools
53const recommendation = await chat({
54 adapter: openaiText("gpt-6.1-sol"),
55 messages: [{ role: "user", content: "Recommend a product for a developer" }],
56 threadId: "thread-1",
57 tools: [getProductPrice],
58 outputSchema: RecommendationSchema,
59});
60
61console.log(recommendation.productName, recommendation.currentPrice);
62```
63
64Run the file. You see `Looking up ...` first. Then the typed recommendation prints, with the price from the tool.
65
66## How it works
67
681. The agent loop runs. The model calls `get_product_price`, and the engine runs it.
692. The loop continues until every tool has a result.
703. The model returns JSON that matches your schema.
714. The engine validates the object, and the promise resolves.
72
73With `stream: true`, the client sees the events in this order:
74
751. `RUN_STARTED`
762. Tool events (`TOOL_CALL_START`, `TOOL_CALL_ARGS`, `TOOL_CALL_END`, `TOOL_CALL_RESULT`). These can repeat for many calls.
773. `structured-output.start`, when the JSON begins
784. `TEXT_MESSAGE_CONTENT` deltas with the JSON
795. `structured-output.complete` with the full object
806. `RUN_FINISHED`
81
82In `useChat`, `partial` stays `{}` and `final` stays `null` during step 2. `partial` starts to fill at step 3, and `final` is set at step 5. Tool-call parts land on the assistant message, the same as in a normal chat.
83
84## Gate a tool behind an approval
85
86A tool with `needsApproval: true` does not run until the user says yes. The run pauses, and the structured JSON starts only after the user answers.
87
88Put the tool definition in a shared file:
89
90```typescript
91// tools/definitions.ts
92import { toolDefinition } from "@tanstack/ai";
93import { z } from "zod";
94
95export const sendEmailDef = toolDefinition({
96 name: "send_email",
97 description: "Send an email to a recipient",
98 inputSchema: z.object({ to: z.string(), subject: z.string() }),
99 outputSchema: z.object({ sent: z.boolean() }),
100 needsApproval: true,
101});
102
103export const ReportSchema = z.object({
104 summary: z.string(),
105 emailSent: z.boolean(),
106});
107```
108
109On the server, forward `parentRunId` and `resume`. The answer of the user arrives in a second request, and `chat()` uses these fields to continue the paused run:
110
111```typescript
112// api/report.ts
113import {
114 chat,
115 chatParamsFromRequest,
116 toServerSentEventsResponse,
117 toolDefinition,
118} from "@tanstack/ai";
119import { openaiText } from "@tanstack/ai-openai";
120import { z } from "zod";
121
122// The same definitions as tools/definitions.ts. In your app, import them from that file.
123const sendEmailDef = toolDefinition({
124 name: "send_email",
125 description: "Send an email to a recipient",
126 inputSchema: z.object({ to: z.string(), subject: z.string() }),
127 outputSchema: z.object({ sent: z.boolean() }),
128 needsApproval: true,
129});
130
131const ReportSchema = z.object({
132 summary: z.string(),
133 emailSent: z.boolean(),
134});
135
136const sendEmail = sendEmailDef.server(async ({ to, subject }) => {
137 console.log(`Sending "${subject}" to ${to}`);
138 return { sent: true };
139});
140
141export async function POST(request: Request) {
142 const params = await chatParamsFromRequest(request);
143
144 const stream = chat({
145 adapter: openaiText("gpt-6.1-sol"),
146 messages: params.messages,
147 threadId: params.threadId,
148 runId: params.runId,
149 parentRunId: params.parentRunId,
150 ...(params.resume ? { resume: params.resume } : {}),
151 tools: [sendEmail],
152 outputSchema: ReportSchema,
153 stream: true,
154 });
155
156 return toServerSentEventsResponse(stream);
157}
158```
159
160On the client, show each pending approval from `interrupts`:
161
162```tsx
163// app/report.tsx
164import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
165import { toolDefinition } from "@tanstack/ai";
166import { z } from "zod";
167
168// The same definitions as tools/definitions.ts. In your app, import them from that file.
169const sendEmailDef = toolDefinition({
170 name: "send_email",
171 description: "Send an email to a recipient",
172 inputSchema: z.object({ to: z.string(), subject: z.string() }),
173 outputSchema: z.object({ sent: z.boolean() }),
174 needsApproval: true,
175});
176
177const ReportSchema = z.object({
178 summary: z.string(),
179 emailSent: z.boolean(),
180});
181
182export function Report() {
183 const { sendMessage, interrupts, resuming, partial, final } = useChat({
184 connection: fetchServerSentEvents("/api/report"),
185 threadId: "support-chat",
186 tools: [sendEmailDef],
187 outputSchema: ReportSchema,
188 });
189
190 return (
191 <div>
192 <button
193 onClick={() =>
194 void sendMessage("Email ada@example.com a hello, then report back.")
195 }
196 >
197 Start
198 </button>
199
200 {interrupts.map((interrupt) =>
201 interrupt.kind === "tool-approval" ? (
202 <div key={interrupt.id}>
203 <p>Run {interrupt.toolName}?</p>
204 <button
205 disabled={!interrupt.canResolve || resuming}
206 onClick={() => interrupt.resolveInterrupt(true)}
207 >
208 Approve
209 </button>
210 <button
211 disabled={!interrupt.canResolve || resuming}
212 onClick={() => interrupt.resolveInterrupt(false)}
213 >
214 Deny
215 </button>
216 </div>
217 ) : null,
218 )}
219
220 <p>{(final ?? partial).summary ?? "Waiting..."}</p>
221 </div>
222 );
223}
224```
225
226Click Start, then Approve. The server logs the email, and the summary fills in. While the approval waits, `partial` stays `{}` because no JSON exists yet.
227
228For the full approval flow, see [Tool Approval](../tools/tool-approval).
229
230## Run a client tool inside the run
231
232A client tool runs in the browser. When the model calls it, the run pauses. The browser runs your `.client()` function and sends the result back. Then the loop continues into the structured JSON. You do not need an `onToolCall` option.
233
234Pass the definition to `chat()` on the server, the same way as in [Client Tools](../tools/client-tools). On the client, add the `.client()` implementation to `useChat`:
235
236```tsx
237import { toolDefinition } from "@tanstack/ai";
238import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
239import { z } from "zod";
240import { ReportSchema } from "../tools/definitions";
241
242const lookupContactDef = toolDefinition({
243 name: "lookup_contact",
244 description: "Find a contact by name in the local address book",
245 inputSchema: z.object({ name: z.string() }),
246 outputSchema: z.object({ email: z.string() }),
247});
248
249const lookupContact = lookupContactDef.client((input) => {
250 const email = localStorage.getItem(`contact:${input.name}`) ?? "";
251 return { email };
252});
253
254export function useReport() {
255 return useChat({
256 connection: fetchServerSentEvents("/api/report"),
257 threadId: "support-chat",
258 tools: [lookupContact],
259 outputSchema: ReportSchema,
260 });
261}
262```
263
264While the client tool runs, `partial` stays `{}` and `final` stays `null`. When `.client()` returns, the loop continues, and `partial` and `final` fill in.
265
266The server ends the paused run with an internal `client-tool-execution` interrupt. This interrupt is not in the public `interrupts` array. The client sends the tool output in a resume batch.
267
268## Advanced
269
270### Combined mode: one request for tools and schema
271
272Some adapters return tool calls and the schema-constrained answer in one streaming request. On these adapters, `chat({ tools, outputSchema, stream: true })` makes no extra final call:
273
274- OpenAI
275- Anthropic Claude 4.5 and newer
276- Gemini 3.x
277- Grok 4.x
278- [OpenRouter on those same upstream models](../adapters/openrouter.md#tools-and-structured-output-together)
279
280The React chat example has a live OpenRouter page at `/generations/openrouter-combined`.
281
282Other adapters make a separate final call after the agent loop. On that path, the loop can also finish a plain-text assistant message before `structured-output.start`. That message and the structured-output message stay separate. In combined mode, the JSON and its part are on one assistant message.
283
284For how this affects middleware, see [Middleware](./overview#middleware).
285
286### Harness agents
287
288Coding agents in a sandbox (Claude Code, Codex, OpenCode, Grok Build) run native tools and the schema on the same turn. They do not pause for TanStack tool approvals or client tools. See [Harness Agents](./harnesses).
289
290### Multi-turn with tools
291
292Each turn runs the agent loop, with any approvals, and then adds a structured-output message. The next turn sees the earlier objects as assistant content. On the separate-final-call path, the plain-text message from the loop can also stay before each structured message.
293
294Between `sendMessage()` and the first structured event, the latest turn has no `structured-output` part, so `find()` returns `undefined`. To show a placeholder, check `isLoading` and whether the last message is from the user. See [Multi-Turn Chat](./multi-turn).