◆ AI All-in-One

Level 2 Agentic Coding · Building with AI

Structured Output and JSON

How to get data your code can trust out of a language model. Describe the shape with a schema, let the API enforce it with constrained decoding, validate the result with Pydantic, and repair or retry when it fails.

Level
●●●●● Easy
Reading
12 min
To learn it well
45 minutes to read, an afternoon to practise
↗ Plan a path here

Read first

Using LLM APIs

This leads to

Tool Use and Function Calling
The full path from zero — 5 concepts before this one
  1. What Is AI?
  2. Python for AI
  3. How Machines Learn
  4. Large Language Models, Explained Simply
  5. Using LLM APIs
  6. Structured Output and JSON

Read them roughly in this order. See it on the concept map →

Why it matters

Language models write text. Programs need data. If you ask a model to pull the total out of an invoice, a person is happy with "The total comes to £1,250, due by the end of December." Your accounting code is not. It needs {"total": 1250.0, "currency": "GBP", "due_date": "2026-12-31"}, every time, with exactly those field names and types.

Structured output means getting model output in a precise, machine-readable shape, almost always JSON (JavaScript Object Notation: nested lists and key–value pairs written as text, the lingua franca of web APIs). It is what turns a model into a component you can build on. Information extraction (pulling fields out of invoices, emails, CVs, contracts and medical notes), classification with labels, routing, form filling, and the arguments of every tool call an agent makes all depend on it.

The good news is that this is now largely a solved problem. As of late 2026 the major APIs can guarantee that output matches a schema you supply. The remaining work is designing good schemas and validating the meaning of the values, which no API can do for you.

The intuition

Asking for structured data in plain words is like asking someone to write you a letter and hoping it contains the six facts you need, in the order you need them. Giving them a form with labelled boxes, some with tick-box choices, is far more reliable. A schema is that form.

There are three levels of reliability:

  1. Ask nicely. "Reply in JSON with fields vendor, total…" Usually works with good models. Occasionally you get a stray sentence before the JSON, a trailing comma, or "total": "£1,250" instead of a number.
  2. Validate and repair. Parse the reply, check it against the schema in code, and if it fails, send the error back and ask the model to fix it. Works with any model.
  3. Constrain the decoding. The API itself only allows tokens that keep the output valid. The output cannot be malformed.
Output so far: {"vendor": "Acme Ltd", "currency": "▮ Model's next-token probabilities (illustrative) 0.40 0.35 0.15 0.06 0.04 £ GBP pounds EUR USD mask + renormalise After the schema mask enum allows GBP, EUR, USD 0.78 0.13 0.09 0 0 £ GBP pounds EUR USD Tokens that would break the schema get probability 0, so the output cannot be malformed.
Fig. 1 How constrained decoding works. The model has written {"currency": " so far. Its next-token probabilities would allow £ or pounds, which break the schema. A mask removes every token not allowed by the schema at this point, leaving only GBP, EUR and USD, and the model picks from those.

You want level 3 where it is available, and level 2 always, because a schema-valid answer can still be wrong.

Key idea Describe the shape you want with a schema. Let the API enforce the syntax, and validate the meaning in your own code. Never feed unvalidated model output to code that acts on it.

How it works

JSON Schema and Pydantic

JSON Schema is a standard way to describe a JSON shape: which fields exist, their types, which are required, and allowed values. Writing it by hand is tedious, so in Python almost everyone uses Pydantic, a library that turns a class with type hints into a schema and validates data against it:

from typing import Literal, Optional
from pydantic import BaseModel, Field

class Invoice(BaseModel):
    vendor: str
    invoice_number: str
    total: float = Field(ge=0, description="Amount due, in the invoice currency")
    currency: Literal["GBP", "EUR", "USD"]
    due_date: Optional[str] = Field(None, description="YYYY-MM-DD, or null if absent")
  • Each line is a field with a type: str, float, int, bool, list[str], or another model for nesting.
  • Literal["GBP", "EUR", "USD"] is an enum: the value must be one of a fixed list. Enums are the best tool you have for reliable classification.
  • Optional[...] = None makes a field nullable, giving the model an honest way to say "not present" instead of inventing a value.
  • Field(ge=0, description=...) adds constraints (here "greater than or equal to 0") and a description. Descriptions end up in the schema, so they act as instructions to the model.

Invoice.model_json_schema() produces the JSON Schema. Invoice.model_validate_json(text) parses a JSON string and checks every rule. On success you get a real Python object (invoice.total is a float). On failure you get a ValidationError listing exactly which fields are wrong and why. That is validation: checking data against rules before you trust it.

Level 1 and 2: prompt, validate, repair

With any model, you can put the schema in the prompt, ask for JSON only, and validate the reply. When validation fails, a repair loop sends the error message back to the model and asks for a corrected version. Models are good at fixing their own output when told precisely what's wrong, because Pydantic's errors are specific: "total: Input should be a valid number, unable to parse string as a number."

Prompt task + schema LLM writes JSON Parse + validate Pydantic model Your code typed object valid invalid Repair message "total: should be a valid number. Fix it." try again (max 2–3 times) Give up safely log for a human out of tries Works with any model. With API-enforced schemas the loop rarely runs, but keep it for cut-off or refused replies.
Fig. 2 The validation and repair loop. The model's reply is parsed and validated against the schema. Valid output goes on to your code. Invalid output is sent back with the exact validation errors, up to a fixed number of attempts, after which the input is flagged for a human.

Two rules keep this loop safe: cap the number of attempts (two or three is plenty), and have a fallback when they run out, such as logging the input for human review. The code below implements it in about 25 lines. The Instructor library packages the same idea for many providers.

Level 3: constrained decoding

A language model produces each token by computing a probability for every token in its vocabulary and sampling one (see Decoding: Temperature, Top-k and Top-p). Constrained decoding adds one step: before sampling, it sets the probability of every token that would make the output invalid to zero.

To know which tokens are invalid, the provider compiles your schema into a grammar, essentially a state machine that tracks where you are in the JSON. After {"currency": " the grammar knows a string from the enum must come next, so only tokens that begin GBP, EUR or USD survive. After "total": only digits are allowed. After the last required field, only }. The model still chooses which valid token to write, so its intelligence is intact, but it can't write anything outside the schema.

Worked example with illustrative numbers. Suppose after {"currency": " the model's top next-token probabilities are £ 0.40, GBP 0.35, pounds 0.15, EUR 0.06, USD 0.04. The schema allows only GBP, EUR and USD. Masking leaves 0.35, 0.06 and 0.04, which sum to 0.45. Renormalising (dividing by 0.45) gives GBP 0.78, EUR 0.13, USD 0.09. The model now almost certainly writes GBP, which is what it meant by £ anyway.

Providers' names for this:

  • Anthropic: structured outputs, via output_config={"format": {"type": "json_schema", "schema": ...}}, or the SDK helper client.messages.parse(..., output_format=Invoice) which takes a Pydantic class and returns a validated object. Tool definitions can set strict: True so tool-call arguments always match their schema.
  • OpenAI: Structured Outputs, via client.responses.parse(..., text_format=Invoice). An older "JSON mode" guarantees valid JSON but not your particular schema.
  • Open models: libraries such as Outlines, and servers such as llama.cpp and vLLM, offer grammar-constrained generation for models you run yourself (see Running Models Locally).

Schema support has limits: providers implement a subset of JSON Schema, and very large or deeply recursive schemas may be rejected. The first request with a new schema can also be slower while the grammar is compiled.

Designing schemas that work

The schema is a prompt as much as a data format. The patterns from Prompt Engineering apply:

  • Use enums for categories. Literal["refund", "exchange", "complaint", "other"] beats a free-text category that comes back as "Refund request" one time and "refund" the next. Always include an "other" or "unknown" option.
  • Allow nulls. If a field might be missing from the source, make it optional. A required field forces the model to invent something.
  • Order fields for thinking. The model writes fields in order. Put a reasoning or evidence field (for example, a quote from the source) before the decision field, and the decision benefits from the reasoning, as in Chain-of-Thought and Reasoning Prompts. Put it after, and it is only a justification written once the decision is fixed.
  • Describe fields. Formats ("YYYY-MM-DD"), units ("in kilograms") and edge cases ("if several totals appear, use the one labelled 'amount due'") belong in field descriptions.
  • Keep it flat and small. Deep nesting and dozens of fields raise the error rate. Two simpler calls often beat one huge schema.

Validating meaning, not just shape

Constrained decoding guarantees total is a non-negative number. It doesn't guarantee it is the right number. Add checks that use your domain knowledge:

  • Pydantic validators for rules such as "due date is after invoice date" or "line items sum to the subtotal".
  • Cross-checks against the source: does the extracted invoice number actually appear in the document?
  • For important fields, measure accuracy on a labelled test set, field by field. Extraction often has one or two hard fields that drag down quality, and per-field numbers tell you where to focus (see Evaluating LLM Applications).

In code

A complete validate-and-repair loop, runnable offline. Install Pydantic first (pip install pydantic). The fake model's first reply has two errors, a currency symbol instead of a code and the total as a string with a pound sign. The loop sends the error back and the "model" corrects it.

import json
from typing import Literal, Optional
from pydantic import BaseModel, Field, ValidationError

class Invoice(BaseModel):
    vendor: str
    invoice_number: str
    total: float = Field(ge=0, description="Amount due, in the invoice currency")
    currency: Literal["GBP", "EUR", "USD"]
    due_date: Optional[str] = Field(None, description="YYYY-MM-DD, or null if absent")

def extract(text, call_model, max_attempts=3):
    prompt = (f"Extract the invoice fields as JSON matching this schema:\n"
              f"{json.dumps(Invoice.model_json_schema())}\n\n<invoice>\n{text}\n</invoice>")
    messages = [{"role": "user", "content": prompt}]
    for attempt in range(1, max_attempts + 1):
        reply = call_model(messages)
        try:
            return Invoice.model_validate_json(reply)          # parse + validate
        except ValidationError as err:
            print(f"attempt {attempt}: {err.error_count()} error(s): "
                  f"{err.errors()[0]['loc']} {err.errors()[0]['msg']}")
            messages += [{"role": "assistant", "content": reply},
                         {"role": "user", "content": f"That JSON was invalid:\n{err}\n"
                                                     "Reply with corrected JSON only."}]
    raise RuntimeError("no valid JSON after retries")

# Offline stand-in: first reply has a wrong currency and a total with a symbol.
replies = iter(['{"vendor": "Acme Ltd", "invoice_number": "INV-0042", '
                '"total": "£1,250.00", "currency": "£", "due_date": "2026-12-31"}',
                '{"vendor": "Acme Ltd", "invoice_number": "INV-0042", '
                '"total": 1250.0, "currency": "GBP", "due_date": "2026-12-31"}'])
fake_model = lambda messages: next(replies)

invoice = extract("ACME LTD ... Invoice INV-0042 ... Total due £1,250.00 by 31/12/2026",
                  fake_model)
print(invoice)
print(invoice.total * 1.2)            # a real float, ready for arithmetic
# attempt 1: 2 error(s): ('total',) Input should be a valid number, unable to parse string as a number
# vendor='Acme Ltd' invoice_number='INV-0042' total=1250.0 currency='GBP' due_date='2026-12-31'
# 1500.0

model_validate_json also raises a ValidationError for text that isn't JSON at all, such as "Sure! Here's the JSON:" in front of it, so the same loop handles that case.

With native structured outputs the API does the constraining and the SDK does the validation. Anthropic's SDK (pip install anthropic, key in ANTHROPIC_API_KEY):

import anthropic

client = anthropic.Anthropic()
response = client.messages.parse(
    model="claude-haiku-5-5",                 # extraction is a good job for a small model
    max_tokens=2000,
    messages=[{"role": "user", "content":
               "Extract the invoice fields.\n<invoice>\nACME LTD ... Invoice INV-0042 "
               "... Total due £1,250.00 by 31/12/2026\n</invoice>"}],
    output_format=Invoice,                    # the Pydantic class from above
)
invoice = response.parsed_output              # an Invoice instance

And OpenAI's (pip install openai, key in OPENAI_API_KEY):

from openai import OpenAI

client = OpenAI()
response = client.responses.parse(
    model="gpt-6-luna",                       # check the models page for current ids
    input="Extract the invoice fields.\n<invoice>\n...\n</invoice>",
    text_format=Invoice,
)
invoice = response.output_parsed

Even with these, keep a try/except around the call. A reply cut off by max_tokens, or a refusal, can still fail to parse.

Common pitfalls

  • Parsing with regular expressions. Pulling JSON out of chatty text with a regex works until the text contains a brace. Use the API's structured output or a proper parser plus validation.
  • Required fields for optional facts. If half your invoices have no due date but the field is required, the model will invent dates. Make it nullable.
  • Free-text categories. Labels drift ("Billing", "billing issue", "payments"). Use an enum.
  • Trusting valid output. Schema-valid means well-formed, not correct. A perfectly formatted wrong total is still wrong. Validate meaning and measure accuracy.
  • Putting the answer before the reasoning. Fields are generated in order. A confidence or explanation field after the answer can't improve the answer.
  • Unbounded repair loops. Always cap retries and handle the failure path.

Watch out Model output that controls actions (database writes, payments, emails, shell commands) must be validated as strictly as input from an untrusted user, because if the model read untrusted text it effectively is untrusted input. A document can contain instructions that steer the extraction. See Prompt Injection and LLM Security.

Where it leads

A bit of history

Early users of GPT-3 got JSON by prompting with examples and hoping. Through 2023 a series of tools appeared to make it reliable: OpenAI's function calling (June 2023) gave models a structured way to emit arguments, and JSON mode (November 2023) guaranteed syntactically valid JSON. Open-source libraries such as Outlines and Guidance, and grammar support in llama.cpp, showed that constraining decoding with a grammar could guarantee a schema for open models. Instructor popularised the Pydantic validate-and-retry pattern. In August 2024 OpenAI launched Structured Outputs with schema-constrained decoding, and Anthropic followed with its own structured outputs in 2025. By then the question had moved from "how do I get valid JSON?" to "how do I design a schema that gets correct JSON?"

Try it

  1. Add a Pydantic validator to Invoice that rejects a due_date that isn't in YYYY-MM-DD format. (Hint: from pydantic import field_validator, or change the type to datetime.date, which Pydantic parses for you.) Make the fake model's second reply use 31/12/2026 and watch the loop catch it.
  2. Design a schema for support emails with category (enum), urgency (1–5), order_id (nullable) and summary (at most 30 words). Where would you put a reasoning field, and why?
  3. With a real API, extract invoices from five varied example texts, with and without native structured outputs. Count schema failures and wrong values separately.

Hint for 3: you will likely see zero schema failures with structured outputs but a few wrong values in both. Those are two different problems with different fixes.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Half your invoices have no due date, but due_date is a required field. What will the model likely do?

  2. With constrained decoding, after {"currency": " the model's probabilities are £ 0.40, GBP 0.35, pounds 0.15, EUR 0.06, USD 0.04, and only GBP, EUR and USD are allowed. What is GBP's probability after masking and renormalising?

  3. Your API guarantees schema-valid JSON, yet some extracted totals are wrong. What does that tell you?

  4. You add a reasoning field to an extraction schema to improve the decision field. Where should it go?

  5. What two rules keep a validate-and-repair loop safe?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Docs

Structured outputs (Claude)

Anthropic · Intermediate · Free

How to constrain Claude's response to a JSON schema with output_config.format, or validate tool inputs with strict tools, including the Pydantic helper.

Docs

Structured Outputs (OpenAI)

OpenAI · Intermediate · Free

Schema-constrained JSON from OpenAI models, with Pydantic examples, refusal handling and the supported subset of JSON Schema.

Docs

Pydantic documentation

Pydantic · Beginner · Free

The data-validation library almost every LLM tool uses for schemas: models, field types, validators and JSON Schema generation.

Tool

Instructor

Jason Liu and contributors · Intermediate · Free

A small library that wraps many LLM providers to return validated Pydantic objects, with automatic retries that feed validation errors back to the model.

Course

Anthropic Courses

Anthropic · Beginner · Free

Notebook courses on the Claude API, prompt engineering, real-world prompting, prompt evaluations and tool use.

Tutorial

Claude Cookbooks

Anthropic · Intermediate · Free

Runnable notebooks for real tasks with Claude: RAG, contextual retrieval, structured JSON, tool use, prompt caching, sub-agents and more.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/building/structured-output.md