Open History to see the last commit
1---
2title: Structured Outputs With Tools
3id: structured-outputs-with-tools
4order: 5
5description: "Combine outputSchema with tools so the agent loop runs first (calling tools as needed) and then returns a validated typed object. Includes the pause / resume flow for tool-approval gates and client-tool invocations inside a structured run."
6keywords:
7 - tanstack ai
8 - structured outputs
9 - tools
10 - agent loop
11 - tool approval
12 - client tools
13 - outputSchema tools
14---
15
16You want the agent to use tools to gather information, then return a structured object summarizing what it found. "Recommend a product for a developer" → the loop calls `getProductPrice`, hits an inventory API, then returns `{ productName, currentPrice, reason }` validated against your schema. The structured response only fires after every tool resolves.
17
18This page covers the combined `outputSchema` + `tools` shape, including the pause/resume points (server-tool approval prompts, client-tool invocations) that can land mid-run before the structured object arrives.
19
20On adapters that support native combined mode (modern OpenAI, Claude 4.5+, Gemini 3.x, Grok 4.x, and [OpenRouter on those same upstream models](../adapters/openrouter.md#tools-and-structured-output-together)), `chat({ tools, outputSchema, stream: true })` is one streaming request. The extra finalization call does not run.
21
22The React chat example has a live OpenRouter page at `/generations/openrouter-combined`.
23
24> **Note:** If you're not yet familiar with how tools work in TanStack AI, read [Tool Architecture](../tools/tool-architecture) and [Server Tools](../tools/server-tools) first. The patterns here build on the regular agent-loop flow — `outputSchema` just adds a final terminal event.
25
26## Non-streaming: tools first, then structured object
27
28The simplest shape: `await chat({ tools, outputSchema })`. The agent loop runs to completion (every tool resolved, every approval responded to), then the model produces the structured object. The promise resolves with the validated, typed result.
29
30```typescript
31import { chat, toolDefinition } from "@tanstack/ai";
32import { openaiText } from "@tanstack/ai-openai";
33import { z } from "zod";
34
35const getProductPrice = toolDefinition({
36 name: "get_product_price",
37 description: "Get the current price of a product",
38 inputSchema: z.object({ productId: z.string() }),
39}).server(async ({ productId }) => {
40 return { price: 29.99, currency: "USD" };
41});
42
43const RecommendationSchema = z.object({
44 productName: z.string(),
45 currentPrice: z.number(),
46 reason: z.string(),
47});
48
49const recommendation = await chat({
50 adapter: openaiText("gpt-5.5"),
51 messages: [{ role: "user", content: "Recommend a product for a developer" }],
52 tools: [getProductPrice],
53 outputSchema: RecommendationSchema,
54});
55
56recommendation.productName; // string — fully typed
57recommendation.currentPrice; // number
58recommendation.reason; // string
59```
60
61The agent decides when to call `get_product_price`, executes the tool, integrates the result into its reasoning, and only then produces the final structured response. You see the validated object; the tool calls happen behind the scenes.
62
63> **Note:** Coding 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 approval or client tools. See [Harness Agents](./harnesses).
64
65## Streaming: lifecycle events before the structured payload
66
67Pass `stream: true` and the wire format changes — the client now sees tool-call events as they happen, _then_ the structured-output stream emits its terminal event. The lifecycle ordering is:
68
691. `RUN_STARTED`
702. (Agent loop) `TOOL_CALL_START` → `TOOL_CALL_ARGS` → `TOOL_CALL_END` → `TOOL_CALL_RESULT`, possibly repeating for multiple tool calls or iterations
713. `structured-output.start` (once the model begins emitting the JSON response)
724. `TEXT_MESSAGE_CONTENT` deltas (the JSON itself)
735. `structured-output.complete` (completed payload)
746. `RUN_FINISHED`
75
76`useChat`'s `partial` stays `{}` and `final` stays `null` while step 2 is running — the structured stream hasn't started yet. Once step 3 fires, `partial` begins filling in; on step 5, `final` snaps.
77
78On the separate-finalization path, the agent loop may also complete a plain-text assistant message before step 3. That message and the structured-output assistant message remain separate. Native-combined output keeps the structured JSON and its part on one assistant message.
79
80The tool-call parts land on the assistant message exactly as they would in a normal streaming chat. Render them however you'd render tool calls outside a structured-output run.
81
82## Server tools that need approval
83
84A server tool registered with `needsApproval: true` doesn't execute automatically — the agent loop pauses, the queued tool-call lands on the assistant message as a `ToolCallPart` with `state === "approval-requested"`, and the loop waits for you to call `addToolApprovalResponse({ id, approved })` from the hook return. The structured-output stream only takes over once approval is granted (or denied and the loop resumes).
85
86```tsx ignore
87import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
88import { RecommendationSchema } from "./api/recommend";
89import { sendEmail } from "./tools";
90
91const { messages, sendMessage, partial, final, addToolApprovalResponse } =
92 useChat({
93 connection: fetchServerSentEvents("/api/recommend"),
94 outputSchema: RecommendationSchema,
95 tools: [sendEmail], // server tool with needsApproval: true
96 });
97
98const last = messages.at(-1);
99
100return (
101 <>
102 {last?.parts.map((part, i) => {
103 // Surface approval prompts inline.
104 if (
105 part.type === "tool-call" &&
106 part.state === "approval-requested" &&
107 part.approval
108 ) {
109 return (
110 <ApprovalPrompt
111 key={i}
112 part={part}
113 onApprove={() =>
114 addToolApprovalResponse({ id: part.approval!.id, approved: true })
115 }
116 onDeny={() =>
117 addToolApprovalResponse({ id: part.approval!.id, approved: false })
118 }
119 />
120 );
121 }
122 if (part.type === "thinking") return <ReasoningView key={i} text={part.content} />;
123 if (part.type === "tool-call") return <ToolCallView key={i} part={part} />;
124 return null;
125 })}
126
127 {/* The structured payload — fills in once tools resolve. */}
128 <StructuredView data={final ?? partial} />
129 </>
130);
131```
132
133While the approval is pending, `partial` stays at its last value (which is `{}` on a first run) and `final` stays `null`. As soon as the user approves (or denies and the loop continues), the agent loop resumes, the structured stream runs, and `partial` / `final` populate.
134
135The full server-tool approval pattern lives in [Tool Approval Flow](../tools/tool-approval). The only structured-output-specific note: the approval can land **before** the structured stream starts. That's why `partial` reads `{}` while you're staring at an approval prompt — there's no JSON yet.
136
137## Client tools mid-run
138
139Client tools — defined with `.client((input) => ...)` on the tool definition — execute automatically when the model calls them. The server ends the current run with an internal `client-tool-execution` interrupt that does not appear in the public `interrupts` array. The client runs the registered `.client()` implementation and submits its output in a resume batch. Once every client tool resolves, the agent loop continues into the structured-output stream. There's no `onToolCall` option to wire up on the hook side.
140
141```tsx
142import { toolDefinition } from "@tanstack/ai";
143import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
144import { z } from "zod";
145import { runLookupOnClient } from "./client-utils";
146import { RecommendationSchema } from "./api/recommend";
147
148const lookupContactDef = toolDefinition({
149 name: "lookup_contact",
150 description: "Find a contact by name",
151 inputSchema: z.object({ name: z.string() }),
152 outputSchema: z.object({ email: z.string(), phone: z.string() }),
153});
154
155// `.client()` registers the browser-side implementation. Calls land here
156// automatically when the model invokes the tool.
157const lookupContact = lookupContactDef.client((input) => {
158 // Look up in local state, IndexedDB, an in-process address book, etc.
159 return runLookupOnClient(input);
160});
161
162const { messages, sendMessage, partial, final } = useChat({
163 outputSchema: RecommendationSchema,
164 tools: [lookupContact],
165 connection: fetchServerSentEvents("/api/recommend"),
166});
167```
168
169While the client tool runs, the agent loop is paused and the structured-output stream hasn't started — `partial` stays `{}` and `final` stays `null`. As soon as the `.client()` implementation returns, the loop resumes, the structured stream takes over, and `partial` / `final` populate.
170
171See [Client Tools](../tools/client-tools) for the full pattern (typed inputs / outputs, multiple client tools, mixing with server tools, surfacing tool calls in the message renderer).
172
173## Multi-turn + tools + structured output
174
175Composes naturally. Every turn runs the agent loop (with any tool gates), then produces a structured-output assistant message when the run completes successfully. The next turn sees the prior recipe (or recommendation, or report) as assistant content and can iterate on it. The separate-finalization path can also retain the agent loop's plain-text assistant message before that structured response.
176
177The only thing to be careful of: between `sendMessage()` and the first structured-output event, the latest turn has no `structured-output` part yet — your render loop's `m.parts.find(p => p.type === "structured-output")` returns `undefined`. Render a "streaming…" placeholder when `isLoading && messages[last]?.role === "user"` to cover that gap. See [Multi-Turn Chat](./multi-turn) for the full pattern.