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

overview.md

308 lines11.1 KB

1---
2title: Structured Outputs Overview
3id: structured-outputs-overview
4order: 1
5description: "Get a typed object back from the model instead of text. Pass a schema as outputSchema, read the result on the server or in useChat, then pick the streaming, multi-turn, tools, or harness guide."
6keywords:
7 - tanstack ai
8 - structured outputs
9 - json schema
10 - zod
11 - valibot
12 - standard schema
13 - type-safe llm
14 - outputSchema
15---
16​
17Pass `outputSchema` so the model returns an object that matches the schema. The call fails when the output does not match.
18​
19Pass a schema as `outputSchema`. The model must answer in that shape, and you get a typed object back.
20​
21## Quick setup
22​
23This setup adds a "person extractor" to an app that already has chat. It takes about 5 minutes.
24​
25### 1. Install a schema library
26​
27<!-- ::start:tabs variant="package-manager" mode="install" -->
28​
29react: zod
30vue: zod
31solid: zod
32svelte: zod
33preact: zod
34angular: zod
35vanilla: zod
36octane: zod
37​
38<!-- ::end:tabs -->
39​
40### 2. Define the schema
41​
42Put the schema in a file that the server and the client can both import:
43​
44```typescript
45// schemas/person.ts
46import { z } from "zod";
47​
48export const PersonSchema = z.object({
49 name: z.string().meta({ description: "The full name of the person" }),
50 age: z.number().meta({ description: "The age in years" }),
51 email: z.string().email(),
52});
53```
54​
55### 3. Add the server endpoint
56​
57```typescript
58// api/extract-person.ts
59import {
60 chat,
61 chatParamsFromRequest,
62 toServerSentEventsResponse,
63} from "@tanstack/ai";
64import { openaiText } from "@tanstack/ai-openai";
65import { PersonSchema } from "../schemas/person";
66​
67export async function POST(request: Request) {
68 const { messages, threadId, runId } = await chatParamsFromRequest(request);
69​
70 const stream = chat({
71 adapter: openaiText("gpt-6.1-sol"),
72 messages,
73 threadId,
74 runId,
75 outputSchema: PersonSchema,
76 stream: true,
77 });
78​
79 return toServerSentEventsResponse(stream);
81```
82​
83### 4. Read the object on the client
84​
85Give `useChat` the same schema. Then read `final`:
86​
87```tsx
88import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
89import { PersonSchema } from "./schemas/person";
90​
91export function PersonExtractor() {
92 const { sendMessage, isLoading, final } = useChat({
93 connection: fetchServerSentEvents("/api/extract-person"),
94 threadId: "support-chat",
95 outputSchema: PersonSchema,
96 });
97​
98 return (
99 <div>
100 <button
101 disabled={isLoading}
102 onClick={() => void sendMessage("John Doe is 30, john@example.com")}
103 >
104 Extract
105 </button>
106 {final && (
107 <p>
108 {final.name} ({final.age}): {final.email}
109 </p>
110 )}
111 </div>
112 );
114```
115​
116Click Extract. When the run ends, the card shows `John Doe (30): john@example.com`. `final.age` is a `number`, with no cast.
117​
118Vue, Solid, Svelte, Angular, Preact, and Octane take the same `outputSchema` option and return the same `partial` and `final` values.
119​
120## How it works
121​
1221. TanStack AI converts your schema to JSON Schema.
1232. The adapter sends that JSON Schema to the native structured-output API of the provider.
1243. The server streams the JSON. The last event, `structured-output.complete`, holds the full object.
1254. `useChat` sets `final` from that event. TypeScript infers its type from the schema.
126​
127## No UI? Await the object
128​
129In a script, a CLI, or a server job, leave out `stream: true`. Then `chat()` returns a promise of the typed object:
130​
131```typescript
132import { chat } from "@tanstack/ai";
133import { openaiText } from "@tanstack/ai-openai";
134import { PersonSchema } from "./schemas/person";
135​
136const person = await chat({
137 adapter: openaiText("gpt-6.1-sol"),
138 messages: [{ role: "user", content: "John Doe is 30, john@example.com" }],
139 threadId: "thread-1",
140 outputSchema: PersonSchema,
141});
142​
143console.log(person.name, person.age);
144```
145​
146## Pick your next page
147​
148| You want to | Read |
149| --- | --- |
150| Extract one object, with field hints and error handling | [One-Shot Extraction](./one-shot) |
151| Fill a form or card field by field while the JSON streams | [Streaming UIs](./streaming) |
152| Fill a table from streamed rows in a TanStack Start app | [Streaming Structured Table](../tutorials/streaming-structured-table) |
153| Let the user change the object over many turns, and keep each version | [Multi-Turn Chat](./multi-turn) |
154| Call tools first, then return a typed object | [With Tools](./with-tools) |
155| Let a coding agent read files in a sandbox, then return a typed object | [Harness Agents](./harnesses) |
156​
157## Advanced
158​
159### Schema libraries
160​
161`outputSchema` accepts any library that implements [Standard JSON Schema](https://standardschema.dev/json-schema):
162​
163- [Zod](https://zod.dev/) (v4.2+)
164- [ArkType](https://arktype.io/)
165- [Valibot](https://valibot.dev/) (with `@valibot/to-json-schema`)
166- Plain JSON Schema objects. You lose type inference. See [Using plain JSON Schema](./one-shot#using-plain-json-schema).
167​
168For field descriptions, refinements, and enums, read the docs of your schema library. TanStack AI converts the schema to JSON Schema for you.
169​
170### Provider support
171​
172Each adapter uses the native structured-output API of its provider. The same `chat({ outputSchema })` call works with all of them.
173​
174| Provider | Implementation |
175| --- | --- |
176| OpenAI | `response_format` with `json_schema` |
177| Anthropic | Tool-based extraction |
178| Google Gemini | `responseSchema` |
179| Ollama | JSON mode with schema |
180| OpenRouter, Grok, Groq | `response_format` with `json_schema` |
181| Claude Code, Codex | Native schema flag on the same harness turn (`--json-schema`, `--output-schema`) |
182| OpenCode, Grok Build, ACP compatible | Schema in the prompt, then the adapter parses the reply on the same turn |
183​
184For a coding agent in a sandbox, see [Harness Agents](./harnesses).
185​
186### When strict JSON schema is rejected
187​
188Some models reject strict JSON schema. They accept only JSON mode (`response_format` type `json_object`). A strict request to one of these models fails before the model runs.
189​
190The OpenRouter and Groq adapters find these models in their catalogs. For these models, `chat({ outputSchema })` does two things:
191​
192- It sends JSON mode.
193- It adds your schema to the system prompt, because JSON mode does not send the schema.
194​
195If your schema is a Standard Schema, such as Zod, `await chat({ outputSchema })` still validates the reply. JSON of the wrong shape throws. TanStack AI does not validate a plain JSON Schema or a streamed reply. Validate those in your own code.
196​
197```typescript
198import { chat } from "@tanstack/ai";
199import { openRouterText } from "@tanstack/ai-openrouter";
200import { z } from "zod";
201​
202const Person = z.object({ name: z.string(), age: z.number() });
203​
204const person = await chat({
205 adapter: openRouterText("qwen/qwen3.7-flash"),
206 messages: [{ role: "user", content: "Return Ada Lovelace, age 36." }],
207 threadId: "thread-1",
208 outputSchema: Person,
209});
210​
211console.log(person.name, person.age);
212```
213​
214To send JSON mode to a model that is not in the catalog, set it in `modelOptions`:
215​
216- OpenRouter: `modelOptions: { responseFormat: { type: "json_object" } }`
217- Groq: `modelOptions: { response_format: { type: "json_object" } }`
218​
219### Anthropic schema complexity limits
220​
221Anthropic compiles a structured-output schema into a grammar. It rejects a schema that is too large or too complex with a 400 error. Two common messages:
222​
223- `Schema is too complex for compilation`
224- `output_config.format.schema: Invalid schema: The compiled grammar is too large`
225​
226This applies to Claude models directly and to `anthropic/*` models on OpenRouter. Other providers can accept the same schema.
227​
228If you get one of these errors, make the schema simpler. Constructs that add branches to the grammar cost more than size:
229​
230- `.optional()` fields that you do not need
231- `.catch()` and `.default()` wrappers, because they widen the accepted input
232- Union types and deeply nested objects
233- Optional strings with no constraint. Use enums or formats where you can.
234​
235Anthropic changes its limits and does not publish all of them. For the current limits, read the Anthropic [structured outputs documentation](https://docs.claude.com/en/docs/build-with-claude/structured-outputs).
236​
237### Where validation runs
238​
239Validation on the server depends on the path:
240​
241- `await chat({ outputSchema })`: the engine validates the object with your Standard Schema when the run ends. A failure goes to the `onError` middleware hook, and the promise rejects.
242- `chat({ outputSchema, stream: true })`: the engine does not validate. Read the object from `value.object` on the `structured-output.complete` event, or call `parseWithStandardSchema` on the raw text yourself.
243​
244On the client, the schema you give `useChat` is for TypeScript types and for the progressive parse of `partial`.
245​
246### Optional fields come back absent
247​
248Strict providers need every field to be required. So the engine sends each optional field as required and nullable, and the provider returns `null` for a missing optional field. Before you get the object, the engine undoes this change:
249​
250- An `.optional()` field that came back `null` is absent, which matches `T | undefined`.
251- A `.nullable()` field keeps its `null`.
252​
253This applies to the awaited result and to `value.object` on the stream.
254​
255### Middleware
256​
257Middleware on `chat()` sees the agent loop and the final structured-output call. Chunks from that final call have `ctx.phase === "structuredOutput"`. `onFinish` fires once, at the end of the full run.
258​
259Some adapters return tool calls and the schema-constrained answer in one streaming request. On these adapters there is no separate final call:
260​
261- The engine adds `outputSchema` to the normal request and reads the object from the text of the last turn.
262- The `"structuredOutput"` phase does not fire. Middleware sees the run through `"beforeModel"` and `"modelStream"`.
263- `onStructuredOutputConfig` does not run.
264​
265Adapters with this combined mode:
266​
267- OpenAI (Chat Completions and Responses)
268- Anthropic Claude 4.5 and newer
269- Gemini 3.x
270- Grok 4.x
271- OpenRouter, when every routed model is in `OPENROUTER_COMBINED_TOOLS_AND_SCHEMA_MODELS`. See the [OpenRouter adapter](../adapters/openrouter.md#tools-and-structured-output-together).
272​
273Other adapters make a separate final call, and the `"structuredOutput"` phase fires. These include Anthropic 4.4 and older, Gemini 2.x, Grok 2 and 3, Groq, Ollama, and OpenRouter models outside that set.
274​
275To see the structured-output chunks, read `ctx.phase` in `onChunk`:
276​
277```ts
278import type { ChatMiddleware } from "@tanstack/ai";
279import { span } from "./span";
280​
281const tracing: ChatMiddleware = {
282 name: "tracing",
283 onChunk(ctx, chunk) {
284 // Fires for chunks from the agent loop and from the final structured-output call.
285 if ("type" in chunk) {
286 span.addEvent("chunk", { phase: ctx.phase, type: chunk.type });
287 }
288 },
289};
290```
291​
292To change the JSON Schema before the provider call, use `onStructuredOutputConfig`:
293​
294```ts
295import type { ChatMiddleware } from "@tanstack/ai";
296import { sharedDefs } from "./schema-defs";
297​
298const injectDefs: ChatMiddleware = {
299 name: "inject-defs",
300 onStructuredOutputConfig(_ctx, config) {
301 return {
302 outputSchema: { ...config.outputSchema, $defs: { ...sharedDefs } },
303 };
304 },
305};
306```
307​
308For all hooks, see [Middleware](../advanced/middleware.md).