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

overview.md

164 lines8.8 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### Anthropic schema complexity limits
66​
67Anthropic 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.
68​
69If 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:
70​
71- `.optional()` fields you don't strictly need
72- `.catch()` / `.default()` wrappers (they widen the accepted input)
73- Union types and deeply nested objects
74- Unconstrained optional strings — tighten with enums or formats where possible
75​
76Anthropic'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.
77​
78## Which page do I read?
79​
80Pick the journey that matches what you're building. The guides under Structured Outputs cover separate use cases. Read the one that fits.
81​
82| You want to… | Read |
83|---|---|
84| 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) |
85| Build a UI that fills in field-by-field as the model streams (progressive form, live card, typewriter preview) | [Streaming UIs](./streaming) |
86| Walk through a Start app that fills a table from streamed rows | [Streaming Structured Table](../tutorials/streaming-structured-table) |
87| 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) |
88| Combine structured output with tool calls (agent loop that runs tools first, then returns a typed object) | [With Tools](./with-tools) |
89| Ask a coding agent in a sandbox to inspect files, then return a typed object | [Harness Agents](./harnesses) |
90​
91The 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.
92​
93> **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.
95> 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.
96​
97## Middleware integration
98​
99Middleware configured on `chat()` now observes the final structured-output
100provider call in addition to the agent loop. Chunks from the structured-output
101adapter are attributed to `ctx.phase === 'structuredOutput'`; `onFinish` fires
102exactly once at the end of the entire run.
103​
104> **Path-dependent:** Adapters that natively combine `tools` + a schema-
105> constrained final answer in one streaming call do **not** issue a separate
106> finalization round-trip. The engine wires `outputSchema` into the regular
107> `chatStream` request and harvests the structured result from the agent
108> loop's final-turn text. On this path the `'structuredOutput'` middleware
109> phase does **not** fire — middleware sees the run through `'beforeModel'`
110> / `'modelStream'` as usual, and `onStructuredOutputConfig` is not invoked.
112> **Native combined providers:**
113> - Modern OpenAI (Chat Completions + Responses)
114> - Anthropic Claude 4.5+
115> - Gemini 3.x
116> - Grok 4.x family
117> - OpenRouter, when every routed model is in
118> `OPENROUTER_COMBINED_TOOLS_AND_SCHEMA_MODELS` (see the
119> [OpenRouter adapter](../adapters/openrouter.md#tools-and-structured-output-together))
121> **Adapters without native combined-mode support** (Anthropic 4.4-, Gemini
122> 2.x, Grok 2/3, Groq, Ollama, and OpenRouter models outside that set) keep
123> the legacy finalization path and the `'structuredOutput'` phase fires as
124> before.
125​
126### Observing structured-output chunks
127​
128```ts
129import { chat } from "@tanstack/ai";
130import type { ChatMiddleware } from "@tanstack/ai";
131import { span } from "./span";
132​
133const tracing: ChatMiddleware = {
134 name: "tracing",
135 onChunk(ctx, chunk) {
136 // Fires for chunks from the agent loop AND the final structured-output call
137 // chunk.type narrows inside a conditional — use a discriminant check first:
138 if ("type" in chunk) {
139 span.addEvent("chunk", { phase: ctx.phase, type: chunk.type });
140 }
141 },
142};
143```
144​
145### Transforming the JSON Schema before the provider call
146​
147Use the `onStructuredOutputConfig` hook when you need to mutate the schema:
148​
149```ts
150import type { ChatMiddleware } from "@tanstack/ai";
151import { sharedDefs } from "./schema-defs";
152​
153const injectDefs: ChatMiddleware = {
154 name: "inject-defs",
155 onStructuredOutputConfig(_ctx, config) {
156 return {
157 outputSchema: { ...config.outputSchema, $defs: { ...sharedDefs } },
158 };
159 },
160};
161```
162​
163See [Advanced: Middleware](../advanced/middleware.md) for the full hook
164reference.