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

overview.md

197 lines10.1 KB

1---
2title: Structured Outputs Overview
3id: structured-outputs-overview
4order: 1
5description: "Constrain TanStack AI responses to a JSON Schema so the model returns typed, predictable objects. Pick the journey that matches what you're building — one-shot extraction, a streaming UI, or a multi-turn structured chat."
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​
17Structured outputs constrain model responses to match a JSON Schema you control. You get back a typed object — not a string you have to parse, not a "mostly-JSON" blob you have to guess at, not a regex match. The model either returns something that fits your schema or you get a typed error.
18​
19You wire this in once with `outputSchema`. The runtime takes care of the rest: it converts your schema to JSON Schema, hands it to the provider's native structured-output API, validates the response, and infers the TypeScript type from your schema definition.
20​
21```typescript
22import { chat } from "@tanstack/ai";
23import { openaiText } from "@tanstack/ai-openai";
24import { z } from "zod";
25​
26const Person = z.object({ name: z.string(), age: z.number() });
27​
28const person = await chat({
29 adapter: openaiText("gpt-5.5"),
30 messages: [{ role: "user", content: "John Doe, 30" }],
31 outputSchema: Person,
32});
33​
34person.name; // string — fully typed, no cast
35person.age; // number
36```
37​
38## Schema Libraries
39​
40TanStack AI accepts any library that implements [Standard JSON Schema](https://standardschema.dev/json-schema):
41​
42- [Zod](https://zod.dev/) (v4.2+)
43- [ArkType](https://arktype.io/)
44- [Valibot](https://valibot.dev/) (via `@valibot/to-json-schema`)
45- Plain JSON Schema objects (loses TypeScript type inference — see [One-Shot Extraction](./one-shot#using-plain-json-schema))
46​
47Refer to your schema library's docs for field descriptions, refinements, and enums. TanStack AI converts the schema to JSON Schema automatically.
48​
49## Provider Support
50​
51Every adapter handles structured output through its provider's native API:
52​
53| Provider | Implementation |
54|---|---|
55| OpenAI | `response_format` with `json_schema` |
56| Anthropic | Tool-based extraction |
57| Google Gemini | `responseSchema` |
58| Ollama | JSON mode with schema |
59| OpenRouter / Grok / Groq | `response_format` with `json_schema` |
60| Claude Code / Codex | Native schema flag on the same harness turn (`--json-schema` / `--output-schema`) |
61| OpenCode / Grok Build / ACP compatible | Same-turn prompt-and-parse |
62​
63The provider-specific details are handled for you. The same `chat({ outputSchema })` call works across all of them. For a coding agent in a sandbox, see [Harness Agents](./harnesses).
64​
65### When strict JSON schema is rejected
66​
67Some models reject strict JSON schema. They accept JSON mode (`response_format` type `json_object`) only. A strict request to one of these models fails before the model runs.
68​
69The OpenRouter and Groq adapters find these models in their catalogs. For these models, `chat({ outputSchema })` does two things:
70​
71- It sends JSON mode.
72- It adds your schema to the system prompt, because JSON mode does not send the schema.
73​
74When your schema is a Standard Schema, such as Zod, `await chat({ outputSchema })` still checks the reply. JSON of the wrong shape throws. TanStack AI does not check a plain JSON Schema or a streamed reply. Check those in your own code.
75​
76```typescript
77import { chat } from "@tanstack/ai";
78import { openRouterText } from "@tanstack/ai-openrouter";
79import { z } from "zod";
80​
81const Person = z.object({ name: z.string(), age: z.number() });
82​
83const person = await chat({
84 adapter: openRouterText("qwen/qwen3.7-flash"),
85 messages: [{ role: "user", content: "Return Ada Lovelace, age 36." }],
86 outputSchema: Person,
87});
88​
89person.name;
90person.age;
91```
92​
93To send JSON mode to a model that is not in the catalog, set it in `modelOptions`:
94​
95- OpenRouter: `modelOptions: { responseFormat: { type: "json_object" } }`
96- Groq: `modelOptions: { response_format: { type: "json_object" } }`
97​
98### Anthropic schema complexity limits
99​
100Anthropic compiles a structured-output schema into a grammar and rejects schemas it considers too large or too complex with a 400 error — typically `Schema is too complex for compilation` or `output_config.format.schema: Invalid schema: The compiled grammar is too large`. This affects Claude models directly and `anthropic/*` models routed through OpenRouter, even when every other provider accepts the same schema.
101​
102If you hit one of these errors, simplify the schema. Complexity is driven less by overall size than by constructs that multiply the grammar's branching — common offenders:
103​
104- `.optional()` fields you don't strictly need
105- `.catch()` / `.default()` wrappers (they widen the accepted input)
106- Union types and deeply nested objects
107- Unconstrained optional strings — tighten with enums or formats where possible
108​
109Anthropic's exact limits change over time and aren't all published, so we deliberately don't reproduce the numbers here — see Anthropic's [structured outputs documentation](https://docs.claude.com/en/docs/build-with-claude/structured-outputs) for the current limits and reduction strategies.
110​
111## Which page do I read?
112​
113Pick the journey that matches what you're building. The guides under Structured Outputs cover separate use cases. Read the one that fits.
114​
115| You want to… | Read |
116|---|---|
117| Extract one structured object from a single prompt — and consume it server-side (script, endpoint, CLI) or in a browser via `final` | [One-Shot Extraction](./one-shot) |
118| Build a UI that fills in field-by-field as the model streams (progressive form, live card, typewriter preview) | [Streaming UIs](./streaming) |
119| Walk through a Start app that fills a table from streamed rows | [Streaming Structured Table](../tutorials/streaming-structured-table) |
120| Let users iterate on a structured object across multiple turns — each turn produces a new typed object and history stays renderable | [Multi-Turn Chat](./multi-turn) |
121| Combine structured output with tool calls (agent loop that runs tools first, then returns a typed object) | [With Tools](./with-tools) |
122| Ask a coding agent in a sandbox to inspect files, then return a typed object | [Harness Agents](./harnesses) |
123​
124The streaming and multi-turn paths both build on `useChat({ outputSchema })`. The "with tools" path layers on top of either. Pick the one that describes your shipping shape — start there, follow the cross-links when you need a piece of another story.
125​
126> **Note:** Server-side validation is **path-dependent**. For the non-streaming agentic path (`await chat({ outputSchema })`), the engine runs Standard Schema validation inside the finalization step and routes failures through `onError` (the awaited promise rejects). For the streaming path (`chat({ outputSchema, stream: true })`), Standard Schema _validation_ is deliberately deferred to the consumer — consumers read the object from the `structured-output.complete` event's `value.object` field (or call `parseWithStandardSchema` themselves on the raw text). The schema you pass to `useChat({ outputSchema })` on the client is used for TypeScript inference and (in `useChat`) for client-side `parsePartialJSON`-based progressive parsing — the typed-object guarantee comes from the server-side path you pick.
128> On **both** paths the engine normalizes the captured object before it reaches you: to satisfy strict providers, optional fields are widened to `required` + nullable, so the provider returns `null` for an absent optional. The engine undoes exactly that widening — an `.optional()` field that came back `null` reads back as **absent** (matching `T | undefined`), while a genuine `.nullable()` field's `null` is **preserved**. So `value.object` (streaming) and the awaited result (non-streaming) both carry the un-widened shape your schema describes.
129​
130## Middleware integration
131​
132Middleware configured on `chat()` now observes the final structured-output
133provider call in addition to the agent loop. Chunks from the structured-output
134adapter are attributed to `ctx.phase === 'structuredOutput'`; `onFinish` fires
135exactly once at the end of the entire run.
136​
137> **Path-dependent:** Adapters that natively combine `tools` + a schema-
138> constrained final answer in one streaming call do **not** issue a separate
139> finalization round-trip. The engine wires `outputSchema` into the regular
140> `chatStream` request and harvests the structured result from the agent
141> loop's final-turn text. On this path the `'structuredOutput'` middleware
142> phase does **not** fire — middleware sees the run through `'beforeModel'`
143> / `'modelStream'` as usual, and `onStructuredOutputConfig` is not invoked.
145> **Native combined providers:**
146> - Modern OpenAI (Chat Completions + Responses)
147> - Anthropic Claude 4.5+
148> - Gemini 3.x
149> - Grok 4.x family
150> - OpenRouter, when every routed model is in
151> `OPENROUTER_COMBINED_TOOLS_AND_SCHEMA_MODELS` (see the
152> [OpenRouter adapter](../adapters/openrouter.md#tools-and-structured-output-together))
154> **Adapters without native combined-mode support** (Anthropic 4.4-, Gemini
155> 2.x, Grok 2/3, Groq, Ollama, and OpenRouter models outside that set) keep
156> the legacy finalization path and the `'structuredOutput'` phase fires as
157> before.
158​
159### Observing structured-output chunks
160​
161```ts
162import { chat } from "@tanstack/ai";
163import type { ChatMiddleware } from "@tanstack/ai";
164import { span } from "./span";
165​
166const tracing: ChatMiddleware = {
167 name: "tracing",
168 onChunk(ctx, chunk) {
169 // Fires for chunks from the agent loop AND the final structured-output call
170 // chunk.type narrows inside a conditional — use a discriminant check first:
171 if ("type" in chunk) {
172 span.addEvent("chunk", { phase: ctx.phase, type: chunk.type });
173 }
174 },
175};
176```
177​
178### Transforming the JSON Schema before the provider call
179​
180Use the `onStructuredOutputConfig` hook when you need to mutate the schema:
181​
182```ts
183import type { ChatMiddleware } from "@tanstack/ai";
184import { sharedDefs } from "./schema-defs";
185​
186const injectDefs: ChatMiddleware = {
187 name: "inject-defs",
188 onStructuredOutputConfig(_ctx, config) {
189 return {
190 outputSchema: { ...config.outputSchema, $defs: { ...sharedDefs } },
191 };
192 },
193};
194```
195​
196See [Advanced: Middleware](../advanced/middleware.md) for the full hook
197reference.