The Problem: A 2 A.M. Parsing Failure

Picture a common automation: a nightly job reads supplier invoices that arrive by email, asks a large language model (LLM) to pull out the vendor, date, line items and total, and writes the result into the accounting system.

It works for weeks. Then one night it stops, and the next morning you find:

  • A total of "$1,299.00" as a string, where your code expected a number.
  • An invoice dated 03/04/2025. Is that March 4 or April 3? The model picked one.
  • A scanned invoice with no visible total, where the model invented a plausible one rather than leaving it empty.
  • One response cut off halfway through the JSON because it hit the output token limit.

Each of these either crashes the job or, worse, quietly writes wrong numbers into the books.

If an LLM's output feeds code instead of a human, you need structured outputs: responses that always match a schema you define, validated before anything trusts them. In Python, the natural tool is Pydantic. You describe the shape once, and Pydantic generates the JSON Schema, validates the response and gives you typed objects.

This guide walks through the patterns that make extraction like this dependable: schema design, JSON mode, validation with automatic retries, evidence checks, and a FastAPI endpoint that ties it together.

Why Free-Form Output Breaks in Production

LLMs are probabilistic. Even with a perfect prompt you'll eventually see:

  • Wrapping: JSON inside a code fence or with commentary around it.
  • Drift: "price": "$19.99" when you wanted a number.
  • Missing fields: an optional-looking field silently dropped.
  • Invented values: a status of "pending_review" when only three statuses exist.

Each of these is a crash or, worse, bad data written to your database. The fix is to treat LLM output exactly like untrusted user input: parse it, validate it, and reject what doesn't fit.

Designing a Schema with Pydantic

Let's extract structured data from inbound support emails.

Python
from enum import Enum
from pydantic import BaseModel, Field

class Priority(str, Enum):
    low = "low"
    normal = "normal"
    urgent = "urgent"

class Category(str, Enum):
    billing = "billing"
    bug = "bug"
    feature_request = "feature_request"
    account = "account"
    other = "other"

class TicketTriage(BaseModel):
    """Structured triage of a customer support email."""

    summary: str = Field(description="One-sentence summary of the customer's issue", max_length=200)
    category: Category
    priority: Priority = Field(description="urgent only if the customer is blocked or losing money")
    customer_sentiment: float = Field(ge=-1, le=1, description="-1 very negative, 1 very positive")
    order_ids: list[str] = Field(default_factory=list, description="Order IDs mentioned, e.g. ORD-1234")
    needs_human: bool = Field(description="True if the reply requires judgement or a refund")

A few schema design habits make a big difference:

  • Use enums for anything categorical. The model can't invent a fifth category if validation rejects it.
  • Write field descriptions for the model, not for you. They end up in the JSON Schema and act as inline instructions.
  • Add constraints. ge, le, max_length and regex pattern catch nonsense early.
  • Keep it flat where you can. Deeply nested schemas increase errors. Split complex extraction into two calls if needed.

You can see exactly what the model will be told with TicketTriage.model_json_schema().

Approach 1: JSON Mode Plus Validation

Most LLM APIs offer a JSON mode that guarantees syntactically valid JSON, though not your schema. Combine it with the schema in the prompt and Pydantic validation:

Python
import json
import os
from openai import AsyncOpenAI
from pydantic import ValidationError

client = AsyncOpenAI()
MODEL = os.getenv("LLM_MODEL", "gpt-4o-mini")

SYSTEM = """You triage customer support emails.
Respond with a single JSON object that matches this JSON Schema exactly:
{schema}
Do not include any text outside the JSON object."""

async def triage_email(email_body: str) -> TicketTriage:
    response = await client.chat.completions.create(
        model=MODEL,
        temperature=0,
        response_format={"type": "json_object"},
        messages=[
            {"role": "system", "content": SYSTEM.format(
                schema=json.dumps(TicketTriage.model_json_schema())
            )},
            {"role": "user", "content": email_body},
        ],
    )
    raw = response.choices[0].message.content
    return TicketTriage.model_validate_json(raw)

model_validate_json parses and validates in one step, and raises a ValidationError that describes exactly what went wrong.

Approach 2: Native Structured Outputs

Many providers now support schema-constrained decoding: you pass the JSON Schema and the model is constrained to produce output that matches it. When it's available, use it. It removes most validation failures at the source.

The exact parameter names differ between providers and SDK versions, so check your provider's docs. The pattern is the same everywhere:

  1. Generate the schema with Model.model_json_schema().
  2. Pass it in the request as the response format.
  3. Still validate the result with Pydantic.

Step 3 isn't paranoia. Constrained decoding guarantees structure, but it can't enforce cross-field rules or business logic like "an urgent ticket must have an order ID". Pydantic validators can.

Adding Business Rules with Validators

Python
from pydantic import model_validator

class TicketTriage(BaseModel):
    # ... fields from above ...

    @model_validator(mode="after")
    def urgent_billing_needs_order(self) -> "TicketTriage":
        if (
            self.category == Category.billing
            and self.priority == Priority.urgent
            and not self.order_ids
        ):
            raise ValueError("urgent billing tickets must reference at least one order_id")
        return self

Self-Healing: Retry with the Validation Error

When validation fails, the most effective fix is to show the model its own mistake. Pydantic's error messages are precise enough that a second attempt almost always succeeds.

Python
import logging

logger = logging.getLogger(__name__)

async def triage_with_retries(email_body: str, max_attempts: int = 3) -> TicketTriage:
    messages = [
        {"role": "system", "content": SYSTEM.format(
            schema=json.dumps(TicketTriage.model_json_schema())
        )},
        {"role": "user", "content": email_body},
    ]

    for attempt in range(1, max_attempts + 1):
        response = await client.chat.completions.create(
            model=MODEL,
            temperature=0,
            response_format={"type": "json_object"},
            messages=messages,
        )
        raw = response.choices[0].message.content

        try:
            return TicketTriage.model_validate_json(raw)
        except ValidationError as exc:
            logger.warning("Triage validation failed (attempt %d): %s", attempt, exc)
            messages += [
                {"role": "assistant", "content": raw},
                {"role": "user", "content": (
                    "Your response failed validation:\n"
                    f"{exc}\n"
                    "Return a corrected JSON object only."
                )},
            ]

    raise RuntimeError(f"Could not get valid triage after {max_attempts} attempts")

Track how often retries happen. A rising retry rate is an early warning that a prompt change, model update or new kind of input is causing trouble. The monitoring and observability guide shows how to export metrics like this.

Tip: Libraries such as Instructor wrap this retry loop for you and support many providers. It's worth understanding the loop yourself first, so you know what the library is doing when something goes wrong.

Exposing It Through FastAPI

FastAPI and Pydantic fit together naturally. The same model validates the LLM output and documents your API response.

Python
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field

app = FastAPI()

class TriageRequest(BaseModel):
    email_body: str = Field(min_length=10, max_length=20_000)

@app.post("/triage", response_model=TicketTriage)
async def triage(req: TriageRequest) -> TicketTriage:
    try:
        return await triage_with_retries(req.email_body)
    except RuntimeError:
        raise HTTPException(status_code=502, detail="Model returned invalid output")

Your OpenAPI docs now show the exact triage schema, and any client can generate types from it. If you're new to FastAPI patterns, start with building RESTful APIs with FastAPI.

Extracting Lists and Partial Data

Two variations come up constantly.

Extracting many items

Wrap lists in an object. Top-level arrays are awkward in JSON mode, and a wrapper gives you room for metadata later.

Python
class LineItem(BaseModel):
    description: str
    quantity: int = Field(ge=1)
    unit_price: float = Field(ge=0)

class Invoice(BaseModel):
    vendor: str
    currency: str = Field(pattern=r"^[A-Z]{3}$")
    items: list[LineItem]

Allowing "I don't know"

If a value might not be in the source text, make that explicit with None. Otherwise the model will guess.

Python
class ContactInfo(BaseModel):
    name: str
    email: str | None = Field(default=None, description="null if no email is present")
    phone: str | None = Field(default=None, description="null if no phone is present")

Testing Structured Output Code

Don't call the real model in unit tests. Test the parts you own:

Python
import pytest
from pydantic import ValidationError

def test_rejects_unknown_category():
    with pytest.raises(ValidationError):
        TicketTriage.model_validate_json(
            '{"summary": "x", "category": "spam", "priority": "low",'
            ' "customer_sentiment": 0, "needs_human": false}'
        )

def test_urgent_billing_requires_order_id():
    with pytest.raises(ValidationError, match="order_id"):
        TicketTriage.model_validate({
            "summary": "Charged twice", "category": "billing", "priority": "urgent",
            "customer_sentiment": -0.8, "needs_human": True,
        })

Then test prompt quality separately with a small evaluation set of real emails and expected outputs. I cover that in how to evaluate LLM applications. For general API testing setup, see testing APIs in Django and FastAPI.

Production Gotchas (and What to Do About Them)

Ambiguous dates and locales

03/04/2025 means different things in different countries, and the model can't know which one your supplier meant. Ask for ISO 8601 (YYYY-MM-DD), keep the raw string next to the parsed value, and reject dates outside a sane window:

Python
from datetime import date, timedelta
from pydantic import BaseModel, field_validator

class InvoiceHeader(BaseModel):
    invoice_date: date
    invoice_date_raw: str  # exactly as printed, for audits

    @field_validator("invoice_date")
    @classmethod
    def plausible_date(cls, v: date) -> date:
        if not (date.today() - timedelta(days=365 * 2) <= v <= date.today() + timedelta(days=31)):
            raise ValueError("invoice_date is outside the expected range")
        return v

Money is not a float

Use Decimal, and normalize common formatting before validation instead of failing on it:

Python
from decimal import Decimal
from pydantic import field_validator

class Totals(BaseModel):
    total: Decimal

    @field_validator("total", mode="before")
    @classmethod
    def strip_currency(cls, v):
        if isinstance(v, str):
            v = v.replace(",", "").replace("$", "").strip()
        return v

Models fill required fields with guesses

If a field is required, the model will put something there, even when the source doesn't contain it. Make genuinely optional data Optional, and for high-stakes fields ask for evidence: the exact text the value came from. Then check that the evidence actually appears in the source:

Python
class ExtractedTotal(BaseModel):
    total: Decimal | None
    evidence: str | None  # verbatim snippet from the document

def verify_evidence(doc_text: str, item: ExtractedTotal) -> bool:
    if item.total is None:
        return True
    return bool(item.evidence) and item.evidence.strip() in doc_text

When verification fails, send the document to a human review queue instead of the accounting system.

Truncated output

If the response hits the token limit, you get half a JSON object. Check why generation stopped before parsing, and treat truncation as its own error:

Python
choice = response.choices[0]
if choice.finish_reason == "length":
    raise RuntimeError("Output truncated; raise max_tokens or split the document")

Long documents with many line items are the usual cause. Split them into pages or sections and merge the results in code.

Schema changes break old assumptions

Adding a new enum value or renaming a field changes what the model produces and what downstream code expects. Version your schemas (TicketTriageV2), log the version with every stored result, and re-run your evaluation set before switching.

Retries are not free

Every retry is another paid call and more latency. Cap attempts, log retry counts as a metric, and make sure nothing with side effects happens until validation has passed.

Conclusion

Structured outputs turn an LLM from a text generator into a dependable component. Define the shape with Pydantic, use native structured outputs or JSON mode, validate every response, and feed validation errors back to the model when something slips through.

Once you work this way, LLM output stops being a string you hope is right and becomes typed data your code can rely on.


Resources:

Related Articles: