Skip to content
Visual explainer 3h to learn 4 steps

Structured output & JSON schemas

Get validated, typed objects back from a model instead of free text.

By Invicly Tech, , in AI Engineering with Python. About 11 minutes to read.

Topic 6 of 33

In short

Structured output asks the model to return JSON matching a schema instead of free text. Parsing it into Pydantic models gives your code typed, validated objects to work with.

Explained simply

Normally a model replies with free text, like a person would. That is fine for a chat window, but your code cannot easily use "The priority is probably high, and it's about login." Code wants something exact, like priority = "high" and area = "auth".

Structured output means asking the model to reply in a fixed format, usually JSON, that matches a description of the fields you need. That description is called a schema. It says which fields exist, what type each one is, and which values are allowed.

In Python, you write the schema as a Pydantic class. Pydantic can turn the class into a JSON Schema to send with the request, and it can check the reply and turn it into a real Python object. If a field is missing or has a wrong value, you get a clear error instead of silent bad data.

Even with the best API settings, check every reply. A model can return a valid shape with wrong content, refuse to answer, or be cut off. Validation is the gate between the model's text and the rest of your system.

Press Play on a diagram to walk through it one step at a time.

FlowFrom prompt to typed object
  1. 1
    Define schema

    Pydantic model or JSON Schema

  2. 2
    Request JSON

    Use the API's structured output or JSON mode

  3. 3
    Parse

    model_validate_json turns text into an object

  4. 4
    Validate

    Types, required fields and allowed values

  5. 5
    Retry or fail

    Send errors back once, then give up cleanly

SequenceA one-time repair after a failed check
Your app
LLM API
  1. 1Document plus JSON Schema
    Your app to LLM API: Document plus JSON Schema
  2. 2JSON reply
    LLM API to Your app: JSON reply
  3. 3Pydantic: total does not match items
    Your app to Your app: Pydantic: total does not match items
  4. 4Your reply plus the error list
    Your app to LLM API: Your reply plus the error list
  5. 5Corrected JSON
    LLM API to Your app: Corrected JSON
  6. 6Validates: save the object
    Your app to Your app: Validates: save the object

In depth

Three levels of strictness

The weakest approach is asking in the prompt: reply only with JSON in this shape. It mostly works, but models sometimes add a sentence before the JSON, wrap it in a code fence, or miss a field.

JSON mode is a setting on some APIs that guarantees syntactically valid JSON, but not your shape: field names and types can still be wrong.

The strongest is schema-constrained output, often called structured outputs or strict mode, where you send a JSON Schema and the API guarantees the reply fits it. Tool or function calling gives a similar result: you define a tool whose parameters are your schema, and the model's tool call arguments are your data. Use the strictest option your provider supports, and still validate.

CompareHow sure can you be of the shape?
Prompt only
  • Ask for JSON in words
  • Works with any model
  • Extra text and missing fields happen
JSON mode
  • Always valid JSON syntax
  • Shape is not enforced
  • Wrong field names still possible
Schema-constrained
  • Reply must fit your schema
  • Supports a subset of JSON Schema
  • Content can still be wrong

How constrained decoding works

Schema-constrained output works at the sampling step. At each position, the system knows which tokens could legally come next in a JSON document that matches your schema. All other tokens get zero probability before the next token is drawn. After {"priority": " only the starts of low, medium or high are allowed, so the model cannot invent "urgent".

This guarantees the shape, not the truth. The model can still pick the wrong value, leave a field empty, or copy a number incorrectly.

Strict modes usually support only part of JSON Schema. Common rules are that every property must be listed as required and that additionalProperties must be false. Some keywords, such as certain string formats or length limits, may be rejected or ignored. Read your provider's list of supported features, and keep the checks it cannot enforce in your Pydantic model.

Designing a schema the model can fill well

Field names and descriptions act as instructions. invoice_date with the description "Date printed on the invoice, YYYY-MM-DD" is far clearer than date. Use Literal or Enum for fixed choices, so the model picks from your list.

For information that may be missing, use a required field that can be null, such as str | None, and say in the description when to use null. That is better than making the field optional, because the model must decide explicitly, and strict modes often require every field anyway.

The model writes fields in order, from first to last. If you want it to reason before deciding, put a short reasoning field before the answer field. Keep nesting shallow, and do not ask the model to compute things code can compute, such as totals or counts; check those in code instead.

  • Descriptions are instructions: be specific
  • Literal or Enum for every fixed choice
  • Required but nullable for maybe-missing values
  • Field order matters: reasoning before the answer
  • Compute totals in code, not in the model

Handling failures without breaking the app

Plan for four failure types. A validation error: the JSON parses but breaks a rule, such as a missing field or a total that does not add up. A truncated reply: the model hit the token limit and the JSON is cut off, which the stop reason tells you. A refusal: the model declines, and some APIs return this in a separate refusal field instead of your schema. And a correct shape with wrong content, which only business checks and evals catch.

For validation errors, one repair attempt usually works: send the model its own output plus the list of errors, and ask for corrected JSON. Do not loop forever; after one or two attempts, return a clear failure, queue the item for human review, or use a fallback.

Log every failure with the raw output. Patterns in those logs tell you which field descriptions to improve.

MapWhen structured output fails
Failed reply
  • Validation error
    • Send errors back once
    • Then human review
  • Cut off by token limit
    • Check stop reason
    • Raise limit or shorten task
  • Refusal
    • Do not retry blindly
    • Show a clear message
  • Valid but wrong
    • Business-rule checks
    • Catch it with evals

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Define an output JSON schema~45m
  2. 2
    Request structured output from the model~45m
  3. 3
    Parse responses into Pydantic models~45m
  4. 4
    Handle validation failures~45m

Key points

  • Many APIs can constrain output to a JSON schema; prefer that over prompt-only requests.
  • Always validate output, even when the API promises valid JSON.
  • Use enums and Literal types to restrict values to known options.
  • Field descriptions in the schema act as instructions for the model.

Key terms

Tap a card to flip it. 0/4 known

Examples

python
from typing import Literal
from pydantic import BaseModel, ValidationError

class Ticket(BaseModel):
    summary: str
    priority: Literal['low', 'medium', 'high']
    tags: list[str]

schema = Ticket.model_json_schema()  # send this with the request
raw = '{"summary": "Login fails", "priority": "high", "tags": ["auth"]}'
try:
    ticket = Ticket.model_validate_json(raw)
    print(ticket.priority)
except ValidationError as e:
    print('Retry with errors:', e.errors())

Generate a schema, then validate the model's JSON into an object.

An invoice schema with a business rule

You extract line items and totals from invoices. Step 1: describe each line item and the invoice as Pydantic models. Step 2: make invoice_date required but nullable, with a description saying when to use null. Step 3: use Decimal for money so 19.99 stays exact. Step 4: add a model_validator that checks the items add up to the total; the API's schema enforcement cannot check that, but Pydantic can. Step 5: send Invoice.model_json_schema() with the request and validate the reply with Invoice.model_validate_json.

python
from decimal import Decimal
from pydantic import BaseModel, Field, model_validator
class Item(BaseModel):
    description: str
    quantity: int = Field(ge=1)
    unit_price: Decimal
class Invoice(BaseModel):
    invoice_date: str | None = Field(description="YYYY-MM-DD, or null if not printed")
    items: list[Item]
    total: Decimal
    @model_validator(mode="after")
    def check_total(self) -> "Invoice":
        if sum(i.quantity * i.unit_price for i in self.items) != self.total:
            raise ValueError("total does not match the line items")
        return self

Retry once with the errors, then give up cleanly

Some invoices fail validation. Step 1: send the document and the schema. Step 2: try to validate the reply. Step 3: on ValidationError, add the model's reply and the error list to the conversation and ask for corrected JSON. Step 4: after two attempts, return None so the caller can send the invoice to a human review queue. call_model stands for your SDK call with structured output turned on.

python
from pydantic import ValidationError

def extract(text: str, call_model, attempts: int = 2) -> Invoice | None:
    messages = [{"role": "user", "content": f"Extract the invoice.\n<doc>{text}</doc>"}]
    for _ in range(attempts):
        raw = call_model(messages, schema=Invoice.model_json_schema())
        try:
            return Invoice.model_validate_json(raw)
        except ValidationError as e:
            messages += [
                {"role": "assistant", "content": raw},
                {"role": "user", "content": f"Fix these errors, reply with JSON only: {e.errors(include_url=False)}"},
            ]
    return None  # caller sends it to human review

Quick reference

  • Model.model_json_schema() gives the JSON Schema to send with the request
  • Model.model_validate_json(raw) parses and validates in one step
  • JSON mode guarantees valid JSON, not your schema; strict schema mode enforces the shape
  • Use Literal or Enum for fixed choices and required-but-nullable for maybe-missing values
  • Put a reasoning field before the answer field; models fill fields in order
  • Check the stop reason: a reply cut off by the token limit is broken JSON
  • Retry once with the error list, then fail cleanly or send to human review

Common mistakes

  • Using json.loads and trusting the result without schema validation.
  • Making every field optional, which hides missing information.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What does JSON mode guarantee?

Question 2

2How does schema-constrained decoding stop the model from writing an invalid value?

Question 3

3A field may be missing from some documents. What schema design is usually best?

Question 4

4Strict structured output is on, and the reply validates. Which problem can still remain?

Question 5

5Why put a short reasoning field before the final answer field?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a Pydantic model for a support ticket with summary, priority (low, medium, high) and product_area, print its JSON Schema, and validate one good and one bad JSON string.

  2. Exercise 2medium

    Extract tickets from 20 real or made-up customer emails twice: once with a prompt-only JSON request, once with your API's structured output feature. Count how many replies fail validation in each run.

  3. Exercise 3hard

    Add a business rule to the Ticket model: if priority is high, a non-empty error_message field is required. Then run the repair loop from the examples and log every first-attempt failure with the raw output.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Can I use structured output with any model?
Prompt-only JSON works with any model, but guaranteed schema output depends on the provider and model. Check the docs, and keep Pydantic validation either way.
Should I use tool calling or structured output to get JSON?
Use the structured output feature when you just need data back. Use tool calling when the model should choose between actions; its arguments are also schema-shaped JSON.
Why do I get a code fence or a sentence around the JSON?
That happens with prompt-only requests. Switch to the API's structured output mode, or as a stopgap, extract the text between the first { and the last } before validating.
Does structured output make answers less accurate?
For extraction and classification it usually helps. For complex reasoning, tight formats can hurt slightly, so give the model a reasoning field or let it think before the structured step, and measure with evals.
ShareXLinkedInWhatsApp