Skip to content
AI Skills Central

Type to search Agent Skills, workflows, tutorials, tools and the glossary.

Tutorial

Get reliable JSON from an LLM with structured outputs

Describe the output as a schema, let the provider enforce it, validate it with Pydantic AI or the AI SDK, and handle failures.

By Beginner30 min hands-on
Bookmark

Bookmarks are kept in your free account, so you can find this page again on any device.

Sign in to bookmark
Quiz at the end
On this page

The moment a model’s answer feeds into code (a database row, a ticket, a chart) “usually returns valid JSON” stops being good enough. One stray sentence before the opening brace and your parser throws. This tutorial shows the reliable way: describe the output as a schema, let the library and the provider enforce it, validate the result in your own code anyway, and decide in advance what happens when it fails.

There are two tracks. The Python track extracts invoice data with Pydantic AI. The TypeScript track triages support emails with the AI SDK. Do one or both; the ideas are the same.

How structured output works

There are three levels of “please return JSON”, from weakest to strongest:

  1. Asking in the prompt. “Reply with JSON only.” Works most of the time, fails in ways that are hard to predict: extra prose, trailing commas, a missing field.
  2. JSON mode. The provider guarantees syntactically valid JSON, but not that it matches your fields.
  3. Schema-constrained output. You send a JSON Schema and the provider constrains generation so the output matches it. Anthropic, OpenAI and Google all offer this for their current models, under names like structured outputs or response schemas. The LLM API parameters cheat sheet lists the exact switch for each provider.

Libraries such as Pydantic AI and the AI SDK hide the differences. You write a Pydantic model or a Zod schema, the library converts it to JSON Schema, picks the best mechanism the provider supports and parses the result back into a typed object.

Design the schema first

Most structured-output bugs are schema design bugs. Before you write code, decide:

  • Which fields are required. If the source might not contain a value, make the field nullable rather than letting the model invent something to satisfy “required”.
  • Closed sets. Use enums for categories. A free-text category field will come back as “Billing”, “billing issue” and “payments” on three runs.
  • Descriptions. Field descriptions are sent to the model. “Price per unit, without currency symbol” removes a whole class of parsing problems.
  • What you compute yourself. Do not ask the model to add up line items. Extract the items and the stated total, then compare them in code.

Python track: extract invoices with Pydantic AI

Install Pydantic AI with the Anthropic extra:

pip install "pydantic-ai-slim[anthropic]"
export ANTHROPIC_API_KEY="your-key"

Define the schema as Pydantic models and pass the top-level model as output_type:

# extract.py
from datetime import date
from decimal import Decimal
from typing import Literal

from pydantic import BaseModel, Field
from pydantic_ai import Agent


class LineItem(BaseModel):
    description: str
    quantity: int = Field(ge=1)
    unit_price: Decimal = Field(ge=0, description="Price per unit, without currency symbol")


class Invoice(BaseModel):
    supplier: str
    invoice_number: str
    issue_date: date
    currency: Literal["GBP", "EUR", "USD"]
    items: list[LineItem] = Field(min_length=1)
    total: Decimal

    def items_total(self) -> Decimal:
        return sum((i.quantity * i.unit_price for i in self.items), Decimal("0"))


agent = Agent(
    "anthropic:claude-opus-5-5",
    output_type=Invoice,
    instructions=(
        "Extract the invoice fields from the text. Copy numbers exactly as written. "
        "If a field is missing, do not invent it."
    ),
)

TEXT = """
Northwind Supplies Ltd - Invoice INV-20931
Date: 3 November 2026
2 x USB-C dock @ £89.00
5 x HDMI cable @ £6.50
Total due: £210.50
"""

if __name__ == "__main__":
    result = agent.run_sync(TEXT)
    invoice = result.output
    print(invoice.model_dump_json(indent=2))
    if invoice.items_total() != invoice.total:
        print(f"Check this one: items add up to {invoice.items_total()}, invoice says {invoice.total}")

Run it with python extract.py. You get an Invoice object, not a string: invoice.issue_date is a real date, invoice.total a Decimal.

Three things are doing the work here:

  • The Field constraints (ge=1, min_length=1) and the Literal currency are part of the JSON Schema sent to the model and are checked again by Pydantic when the response comes back.
  • If validation fails, Pydantic AI sends the validation error back to the model and asks it to try again, up to a retry limit you can set with the agent’s retries argument. If it still fails, the run raises UnexpectedModelBehavior, which you should catch and route to a human queue.
  • The business check (items_total() != total) runs in plain Python. The model is never asked to do arithmetic.

TypeScript track: triage emails with the AI SDK

Install the AI SDK, the Anthropic provider and Zod:

npm install ai @ai-sdk/anthropic zod
export ANTHROPIC_API_KEY="your-key"

In the AI SDK, structured output is an option on generateText. Pass Output.object with a Zod schema:

// triage.ts
import { anthropic } from "@ai-sdk/anthropic";
import { NoObjectGeneratedError, Output, generateText } from "ai";
import { z } from "zod";

const Ticket = z.object({
  category: z.enum(["billing", "bug", "feature-request", "account", "other"]),
  priority: z.enum(["low", "normal", "urgent"]),
  summary: z.string().max(140).describe("One sentence, in our words, not the customer's"),
  product_area: z.string().nullable().describe("Feature or page mentioned, or null if none"),
  needs_human: z.boolean().describe("True if the customer is angry, mentions legal action or asks for a refund"),
});
type Ticket = z.infer<typeof Ticket>;

export async function triage(message: string): Promise<Ticket | null> {
  try {
    const { output } = await generateText({
      model: anthropic("claude-opus-5-5"),
      output: Output.object({ schema: Ticket }),
      instructions: "You triage support emails for a project-management SaaS. Classify the email. Do not answer it.",
      prompt: message,
    });
    return output;
  } catch (error) {
    if (NoObjectGeneratedError.isInstance(error)) {
      console.error("Model output did not match the schema:", error.text);
      return null;
    }
    throw error;
  }
}

const ticket = await triage(
  "Hi, I was charged twice for November and I need one refunded today. The invoices page shows both payments.",
);
console.log(ticket);

The file uses top-level await, so make the project an ES module with npm pkg set type=module, then run it with npx tsx triage.ts. The return type is inferred from the schema, so ticket.priority autocompletes and a typo is a compile error.

Notice product_area is .nullable() rather than optional-and-hoped-for. Telling the model that null is acceptable is what stops it inventing a feature name for an email that does not mention one.

Handle failure on purpose

Schema enforcement makes failures rare, not impossible. Plan for these cases:

Failure What you see What to do
Output does not validate after retries UnexpectedModelBehavior (Pydantic AI) or NoObjectGeneratedError (AI SDK) Log the raw text, send the item to a review queue
Output was cut off Truncation error or missing fields Raise the max output tokens, or split the input
Model declined Refusal stop reason, no object Treat as “needs human”, never retry blindly in a loop
Valid but wrong Passes validation, fails your business check Flag for review; collect these cases for your eval set

The last row matters most. Every item that fails a business check is a free test case. Save the input and the expected answer, and you have the start of an eval.

Pitfalls

Giant schemas. A schema with 60 fields and deep nesting is harder for the model and slower. If you need that much, split extraction into two calls (header fields, then line items).

Required fields with no source. If the document has no PO number and the field is required, you will get a plausible-looking fake. Make it nullable.

Free-text categories. Use enums, and include an “other” value so the model is not forced into the wrong bucket.

Asking for reasoning inside the object. A reasoning field can help on hard classifications, but put it first in the schema so it is generated before the answer, and do not store it as if it were a fact.

Trusting numbers. Extract, then compute. Models are good at reading numbers off a page and unreliable at arithmetic across many items.

Next steps

Covers

Check your understanding

Structured outputs quiz

Getting JSON that matches a schema, validating it in code and handling the cases where it fails.

7 questions · pass mark 70%

Question 1 of 70 answered
  1. What does a JSON Schema give you when asking a model for structured output?
  • Prompting fundamentals: clear tasks, examples and formats

    How to write a good prompt: frame the task, say who the output is for, show an example and specify the format, so a model's answers are useful and repeatable.

    TutorialBeginner25 min

  • Write your first LLM eval

    Turn real outputs into a small test set, add code-based checks in promptfoo and run them in CI to catch regressions on every change.

    TutorialBeginner40 min

  • Clean and analyse a messy spreadsheet with AI

    Clean a messy spreadsheet with ChatGPT or Claude without losing rows: profile it, agree the rules, keep a cleaning log and reconcile totals before any chart.

    WorkflowBeginner45 min7 steps

  • Build your first agent in TypeScript

    Tools that search and read notes, a step limit, a clear stop condition and logged steps.

    TutorialIntermediate1 h

Back to top