LLM structured output: get reliable JSON from any model, step by step

LLM structured output: get reliable JSON from any model, step by step

LLM structured output means making a language model return data in a fixed, machine-readable shape, usually JSON that matches a JSON Schema, instead of free text. This guide compares JSON mode, schema-constrained output and tool calling across Claude, OpenAI and Gemini, then shows validation with Pydantic and Zod, retry loops, and the failures that still get through.

In shortTL;DR
  • Use schema-constrained output (Claude output_config.format, OpenAI json_schema with strict: true) instead of JSON mode, which only guarantees parseable JSON, not your fields.
  • Use tool calling with strict schemas when the model triggers an action; use structured output when you only need a typed result.
  • Keep schemas flat, set additionalProperties: false, and give the model a legal way to say "not found" so it does not invent values.
  • Still validate every response with Pydantic or Zod: refusals, max_tokens truncation and wrong-but-valid values pass the schema or break it.
  • Let the model reason before it fills the schema; strict formats can hurt reasoning when they force an answer first.

What is LLM structured output?

LLM structured output is a response from a language model that follows a fixed, machine-readable format, almost always JSON that matches a JSON Schema you define. You use it whenever code, not a person, reads the answer: extracting fields from documents, classifying tickets, filling a database row, or passing arguments to a function.

The problem it solves is old. If you ask a model "return JSON with name, email and plan", you usually get JSON. Sometimes you get JSON wrapped in a Markdown fence, a friendly sentence before it, a missing field, "2" where you wanted 2, or a trailing comma. Each of those breaks a parser at 3 a.m.

Modern APIs fix most of this with constrained decoding: while the model generates, the provider only allows tokens that keep the output valid against your schema. Anthropic's strict tool use docs call this grammar-constrained sampling. The model can't emit a missing required key or a string where your schema says integer, because those tokens are never on the table.

Three things remain your job, and they are what this guide is about: choosing the right mode, designing a schema the model can fill without guessing, and validating what comes back.

JSON mode vs structured outputs vs tool calling: which should you use?

Use schema-constrained structured outputs for typed results, strict tool calling when the model chooses an action, and JSON mode only on models that offer nothing better. The three get confused because they all produce JSON, but they guarantee different things.

ApproachValid JSON?Matches your schema?Model can pick an action?Where the schema lives
Prompt only ("reply in JSON")No guaranteeNoNoIn the prompt text
JSON modeYesNoNoIn the prompt text
Structured outputs (strict schema)YesYes, in most casesNoRequest parameter
Tool or function calling, non-strictUsuallyUsuallyYesTool definition
Tool or function calling, strictYesYes, in most casesYesTool definition

The OpenAI Structured Outputs guide is direct about JSON mode: it guarantees valid JSON, but "only Structured Outputs ensure schema adherence." It also warns that in JSON mode you must tell the model to produce JSON in a message, or it may emit whitespace until it hits the token limit.

A practical rule:

  • Extraction, classification, transformation: structured outputs. You want one typed object back.
  • Agents and workflows: tool calling with strict schemas. The model decides whether to search, book or write, and the arguments must be typed. Our guide to LLM function calling covers the loop.
  • Both in one request: Claude lets you combine JSON outputs and strict tools in the same call, so an agent can call typed tools and still return a typed final answer.

How do Claude, OpenAI and Gemini enforce a JSON schema?

All three major APIs accept a JSON Schema and constrain generation to it, but each supports a different subset of JSON Schema and puts the schema in a different place. Write schemas to the strictest common subset if you switch providers.

Claude (Anthropic)OpenAIGemini (Google)
Where the schema goesoutput_config.format with type: "json_schema"; strict: true on toolstext.format with type: "json_schema" and strict: true (Responses API); response_format (Chat Completions)A JSON schema in the request's response format config
Optional fieldsLeave out of requiredEvery field in required; allow null insteadLeave out of required or allow null
additionalPropertiesMust be falseMust be false in every objectSupported
Recursive schemasNot supportedSupported via $refSupported via $ref
Numeric bounds (minimum, maximum)Not supported; SDK moves them to descriptionsSupportedSupported
Key order in outputRequired properties first, then optionalFollows the schema orderNot documented

A few details from the docs that the comparison pages tend to miss:

  • Claude. Structured outputs are available on every current Claude model, and the old output_format parameter is deprecated in favor of output_config.format with no beta header. The Claude structured outputs docs list what returns a 400: recursive schemas, external $ref, numeric and string-length constraints, and additionalProperties set to anything but false. The SDK helpers move unsupported constraints into field descriptions and still check them locally after the response arrives.
  • OpenAI. Strict schemas must have an object at the root (not anyOf), and the docs set hard size limits, shown below.
  • Gemini. The Gemini structured output docs say minLength, maxLength, uniqueItems and a few other keywords are not enforced and are stripped without an error, while minItems and maxItems are enforced. Very large or deeply nested schemas can be rejected with 400 INVALID_ARGUMENT.
5,000object properties per schema, at most
10levels of nesting, at most
1,000enum values across all enum properties
Source: OpenAI API docs, Structured Outputs, supported schemas (November 2026)

How do you get structured output in Python and TypeScript?

Define the shape once as a Pydantic model or Zod schema, pass it to the SDK's parse helper, and read a typed object back. The helper converts your model to JSON Schema, sends it, and validates the response.

With the Anthropic Python SDK, client.messages.parse() takes the Pydantic class as output_format and returns the validated instance in parsed_output:

extract.py
from pydantic import BaseModelimport anthropicclass Invoice(BaseModel):    vendor: str    invoice_number: str    total_cents: int    currency: str    due_date: str | None  # None when the document has no due dateclient = anthropic.Anthropic()response = client.messages.parse(    model="claude-sonnet-5-5",    max_tokens=2000,    messages=[{"role": "user", "content": f"Extract the invoice fields:\n\n{invoice_text}"}],    output_format=Invoice,)if response.stop_reason in ("refusal", "max_tokens"):    raise RuntimeError(f"No usable output: {response.stop_reason}")invoice = response.parsed_output  # an Invoice instance

In TypeScript, the same pattern uses Zod and the zodOutputFormat helper. parsed_output is null if parsing failed, so guard it:

extract.ts
import Anthropic from "@anthropic-ai/sdk";import { z } from "zod";import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";const Invoice = z.object({  vendor: z.string(),  invoice_number: z.string(),  total_cents: z.number().int(),  currency: z.string(),  due_date: z.string().nullable(),});const client = new Anthropic();const response = await client.messages.parse({  model: "claude-sonnet-5-5",  max_tokens: 2000,  messages: [{ role: "user", content: `Extract the invoice fields:\n\n${invoiceText}` }],  output_config: { format: zodOutputFormat(Invoice) },});if (!response.parsed_output) throw new Error(`No usable output: ${response.stop_reason}`);const invoice = response.parsed_output;

OpenAI's SDKs follow the same idea with responses.parse and a Pydantic model in Python, or zodTextFormat in JavaScript. If you work without an SDK helper, the raw Claude request carries the schema like this:

request body (excerpt)
{  "output_config": {    "format": {      "type": "json_schema",      "schema": {        "type": "object",        "properties": {          "sentiment": { "type": "string", "enum": ["positive", "neutral", "negative"] },          "summary": { "type": "string" }        },        "required": ["sentiment", "summary"],        "additionalProperties": false      }    }  }}

New to the Anthropic SDK? Start with our Claude API tutorial, then come back to add schemas.

How should you design a schema the model can fill?

Design the schema as if it were a form for a careful new hire: few fields, clear names, a description on anything ambiguous, and a legal answer for "I don't know." Most bad structured output comes from schemas that force the model to guess.

Rules that hold on every provider:

  1. Keep it flat. Two or three levels of nesting is plenty. Deep trees cost tokens and hit provider limits.
  2. Set additionalProperties: false on every object. Claude and OpenAI strict modes require it anyway.
  3. Allow null for anything that may be missing. A required, non-nullable due_date forces the model to make one up. OpenAI's guide says it plainly: if the input can't produce a valid result, tell the model what to return, or it may hallucinate to fit the schema.
  4. Use enums for categories, and keep them short. On Claude, compare enum values case-insensitively: the docs note values may differ from the schema only in capitalization.
  5. Put instructions in description fields. "Amount in cents, integer, no currency symbol" beats a bare total.
  6. Use integers for money and counts (cents, not 12.50) to avoid float rounding and locale commas.
  7. Don't rely on key order. Claude outputs required properties first, then optional ones.
  8. Keep secrets and personal data out of the schema. Anthropic caches compiled schemas for up to 24 hours, separately from your messages.

A bad and a good field, side by side:

bad: forces a guess
"due_date": { "type": "string" }
good: allows a truthful answer
"due_date": {  "type": ["string", "null"],  "format": "date",  "description": "Payment due date as YYYY-MM-DD. null if the document shows no due date."}

Why validate the output if the API already enforces the schema?

Because the schema only enforces shape, not truth, and it has documented exceptions. Validate every response in your code, check business rules the schema can't express, and retry with the error message when validation fails.

Pydantic and Zod both give you this for free. Pydantic's model_validate_json parses and validates a JSON string in one step and raises ValidationError with a precise list of problems; Zod's safeParse returns either the data or a ZodError without throwing. Add the rules JSON Schema can't express as validators:

validate.py
from pydantic import BaseModel, model_validatorclass LineItem(BaseModel):    description: str    amount_cents: intclass Invoice(BaseModel):    total_cents: int    line_items: list[LineItem]    @model_validator(mode="after")    def total_matches_items(self):        if sum(i.amount_cents for i in self.line_items) != self.total_cents:            raise ValueError("total_cents does not equal the sum of line_items")        return self

When validation fails, send the error back and ask for a corrected object. Two or three attempts is enough; if the third fails, the input is probably the problem.

retry.py
from pydantic import ValidationErrordef extract(text: str, attempts: int = 3) -> Invoice:    messages = [{"role": "user", "content": f"Extract the invoice as JSON:\n\n{text}"}]    for _ in range(attempts):        raw = call_model(messages)  # your API call; returns the JSON text        try:            return Invoice.model_validate_json(raw)        except ValidationError as err:            messages += [                {"role": "assistant", "content": raw},                {"role": "user", "content": f"That JSON failed validation:\n{err}\nReturn a corrected object only."},            ]    raise RuntimeError("No valid invoice after retries")

If you'd rather not write this loop, Instructor wraps it: you pass a Pydantic response_model, it validates and re-asks the model on failure, and max_retries sets how many times. It supports more than 15 providers and has a TypeScript version.

Close-up of code in an editor on a dark monitor
Validation and business rules live in your code, not in the schema

What are the most common structured output failures?

The failures that survive strict mode are refusals, truncation, invented values, and small drifts such as enum casing. Each has a specific signal you can check.

FailureWhat you seeHow to handle it
RefusalClaude: stop_reason: "refusal"; OpenAI: a refusal content itemTreat as an error case; the output may not match the schema
TruncationClaude: stop_reason: "max_tokens"; OpenAI: status incomplete, reason max_output_tokensRaise max_tokens, shrink the schema, or split the task
Invented valuesPlausible data that isn't in the sourceNullable fields, a "not found" path, spot-check against the input
Enum casing drift"Conversation Topic 3" vs "Conversation topic 3"Compare enums case-insensitively (documented for Claude)
Schema rejectedHTTP 400 on the requestRemove unsupported keywords; check provider limits
Slow first callExtra latency on a new schemaExpected while the grammar compiles; warm it at deploy time
Cache missesPrompt cache resets mid-conversationOn Claude, changing output_config.format invalidates the prompt cache for that thread
PrefillNot supportedPrefilling the assistant turn is incompatible with Claude JSON outputs; drop the old { prefill trick

Two more that bite in practice. Claude JSON outputs can't be combined with citations (the API returns a 400), so if you need a source for every extracted value, use the citations-based extraction pattern in Anthropic's docs instead. And "valid but wrong" is the failure no parser catches: measure it with a labeled test set, as described in our guide to LLM evaluation.

Warning

Logging only parse failures makes a pipeline look 100 percent reliable while it ships wrong values. Track field-level accuracy on a sample, not only "did it parse."

Does forcing JSON output hurt the model's reasoning?

It can, when the format forces the model to commit to an answer before it has worked the problem out. The fix is to let reasoning happen first, then constrain only the final answer.

The 2024 paper Let Me Speak Freely? by Tam and colleagues reported a significant decline in reasoning ability under format restrictions, with stricter formats generally causing larger drops. Simple extraction barely suffers; multi-step math or judgment calls do.

Three ways to keep the reasoning:

  • Use thinking. On Claude, the grammar applies only to the direct output, not to thinking, so the model can reason freely and then write schema-valid JSON.
  • Put a reasoning field first. On providers that keep schema key order, such as OpenAI, a reasoning string before answer lets the model think in the output. Don't count on this on Claude, which writes required properties first.
  • Use two passes. Ask for a free-text analysis, then run a second, cheap call that extracts the structured fields from it.

Structured output also helps with AI hallucinations only up to a point: it stops format errors, not factual ones.

Checklist: reliable JSON from an LLM in production

Start with the strictest mode your provider offers, then add validation and monitoring around it.

  1. Pick the mode: structured outputs for typed results, strict tools for actions, JSON mode only as a fallback.
  2. Define the shape once in Pydantic or Zod and generate the JSON Schema from it.
  3. Make missing data nullable and say in the prompt what to return when the input has no answer.
  4. Check stop_reason (or the response status) for refusals and truncation before you read the object.
  5. Validate every response, including business rules, and retry with the error message up to three times.
  6. Keep a small labeled set of real inputs and check field accuracy whenever you change the prompt, schema or model.
  7. Log schema failures, retries and refusals so you see drift before your users do; our guide to LLM observability covers what to record.

If you build extraction pipelines with a coding agent, Orkio runs Claude Code on an always-on cloud box, so the agent can keep iterating on schemas and tests after you close your laptop.

Frequently asked questions

What is the difference between JSON mode and structured outputs?

JSON mode guarantees that the response parses as JSON, but not that it contains your fields or types. Structured outputs constrain generation to a JSON Schema you supply, so required keys and types are enforced while the model writes. OpenAI's own guide says only Structured Outputs ensure schema adherence.

Is LLM structured output 100 percent reliable?

No. The schema is enforced in most cases, but a refusal or a response cut off at the token limit can still return output that doesn't match. A schema-valid response can also contain wrong values, so you need validation and business-rule checks in your own code.

Should I use function calling or structured outputs for data extraction?

Use structured outputs when all you want is a typed result, such as fields pulled from an invoice. Use tool or function calling when the model decides whether to call one of several functions, such as searching flights or creating a ticket. Both use the same constrained decoding when strict mode is on.

How do I make a field optional in a strict JSON schema?

OpenAI's strict mode requires every property to be listed in required, so you make a field optional by allowing null, for example a type of string or null. Claude accepts properties that are left out of required. A nullable field works on both and makes the absence explicit.

Does structured output make responses slower?

Only the first time you use a new schema. Anthropic and OpenAI both document extra latency on the first request while the schema is compiled into a grammar; Anthropic caches compiled grammars for 24 hours from last use. Later requests with the same schema have no added delay.

Can I put customer data in the JSON schema itself?

Avoid it. Anthropic caches compiled schemas separately from message content and tells HIPAA users not to put protected health information in property names, enum values or patterns. Keep schemas generic and put real data only in the prompt.

SOURCES

  1. Claude docs: Structured outputs
  2. Claude docs: Strict tool use
  3. OpenAI API docs: Structured Outputs
  4. Gemini API docs: Structured output
  5. Pydantic docs: JSON
  6. Zod docs: Basic usage
  7. Instructor documentation
  8. Tam et al., Let Me Speak Freely? A Study on the Impact of Format Restrictions on Performance of Large Language Models (arXiv, 2024)
  • #structured output
  • #json schema
  • #llm api
  • #pydantic
  • #zod
Orkio team

The team building Orkio. We write about putting AI to work: coding agents that run overnight, always-on boxes and pull requests ready by morning.

Keep reading

All posts

07:06 · YOU MERGED #128

Go to sleep. Wake up to pull requests.

Start for $19 a month
© 2026 Orkio · Hosted in Europe TürkçeStatus