Validating LLM JSON output with Pydantic and a repair retry

Treat model output as untrusted input: define a Pydantic schema, validate the JSON an LLM returns, and feed validation errors back for one bounded repair attempt.

3 min read

Contents
  1. The problem
  2. Define the contract first
  3. Clean up the obvious noise
  4. Validate, then repair once
  5. Decide what failure means
  6. Test it without a model
  7. Takeaways

The problem

Asking a language model to “answer in JSON” works most of the time. The trouble is the rest of the time. You get a Markdown code fence around the object, a trailing comment, a missing field, a number written as a string, or an enum value the model invented. If your code passes that straight into a database or a business rule, the failure shows up far away from its cause.

The fix is the same one you use for any external input: define the shape you expect, validate against it at the boundary, and decide explicitly what happens when validation fails. In Python, Pydantic does the validation part well, and its error messages are precise enough to hand back to the model for a repair attempt.

Define the contract first

Say we extract structured data from support emails. Write the schema as a Pydantic model, with constraints that reflect real business rules rather than just types:

from enum import Enum
from pydantic import BaseModel, Field, ConfigDict


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


class Ticket(BaseModel):
    model_config = ConfigDict(extra="forbid")

    customer_email: str = Field(pattern=r"^[^@\s]+@[^@\s]+$")
    summary: str = Field(min_length=10, max_length=200)
    priority: Priority
    order_id: int | None = Field(default=None, gt=0)

extra="forbid" matters: without it, a model that adds fields you never asked for passes silently, and you never notice the prompt and schema drifting apart.

The same model gives you a JSON Schema to put in the prompt, so the instructions and the validator come from one source:

import json

schema_text = json.dumps(Ticket.model_json_schema(), indent=2)

Many model APIs also accept a JSON Schema directly as a “structured output” or “response format” option. Use it when your provider supports it, but keep the Pydantic check anyway. It costs microseconds, it catches anything the provider feature does not enforce (such as cross-field rules), and it keeps your code independent of one vendor.

Clean up the obvious noise

Models often wrap JSON in a code fence even when told not to. Strip that before parsing, and do nothing cleverer than that. Trying to “fix” broken JSON with regular expressions tends to produce valid-looking data that means something else.

def strip_fences(text: str) -> str:
    text = text.strip()
    if text.startswith("```"):
        text = text.split("\n", 1)[1] if "\n" in text else ""
        if text.rstrip().endswith("```"):
            text = text.rstrip()[:-3]
    return text.strip()

Validate, then repair once

Here is the core loop. call_llm stands for whatever client you use; it takes a list of chat messages and returns the reply text.

from pydantic import ValidationError

SYSTEM = (
    "Extract a support ticket from the email. "
    "Reply with a single JSON object that matches this JSON Schema, "
    "and nothing else:\n" + schema_text
)


def extract_ticket(email_body: str, call_llm, max_repairs: int = 1) -> Ticket:
    messages = [
        {"role": "system", "content": SYSTEM},
        {"role": "user", "content": email_body},
    ]
    for attempt in range(max_repairs + 1):
        raw = call_llm(messages)
        try:
            return Ticket.model_validate_json(strip_fences(raw))
        except ValidationError as exc:
            if attempt == max_repairs:
                raise
            messages += [
                {"role": "assistant", "content": raw},
                {
                    "role": "user",
                    "content": (
                        "That JSON did not pass validation:\n"
                        + exc.json(include_url=False)
                        + "\nReturn the corrected JSON object only."
                    ),
                },
            ]
    raise RuntimeError("unreachable")

A few deliberate choices in this code:

  • model_validate_json parses and validates in one step. Invalid JSON syntax also raises ValidationError, so one except covers both cases.
  • The error goes back verbatim. Pydantic errors name the field location, the rule that failed and the input value, for example that priority must be one of low, normal or high. That is far more useful to the model than “please try again”.
  • The previous answer stays in the conversation. The model then edits its own output instead of starting from scratch, which usually changes less.
  • Repairs are bounded. One repair is a sensible default. If the second answer still fails, the problem is usually the prompt, the schema or the input itself, and more retries mostly add latency and cost.

Decide what failure means

When the final attempt raises, do not swallow the exception and return a half-filled object. Pick one behaviour on purpose:

  • put the input on a review queue for a human,
  • fall back to a safe default that downstream code already handles, or
  • fail the request with a clear error.

Whichever you choose, log the raw model output together with the validation errors. Those logs are your best material for improving the prompt, and they show which fields fail most.

Test it without a model

Because call_llm is injected, the retry path is easy to test with a fake:

import pytest


def fake_llm(replies):
    it = iter(replies)
    return lambda messages: next(it)


def test_repairs_bad_enum():
    good = '{"customer_email": "a@b.de", "summary": "Parcel never arrived", "priority": "high"}'
    bad = good.replace('"high"', '"urgent"')
    ticket = extract_ticket("...", fake_llm([bad, good]))
    assert ticket.priority is Priority.high


def test_gives_up_after_one_repair():
    with pytest.raises(ValidationError):
        extract_ticket("...", fake_llm(["not json", "still not json"]))

These tests run in milliseconds and pin down behaviour that is otherwise hard to observe, such as how many calls a bad input costs you.

Takeaways

  • Treat LLM output as untrusted input and validate it at the boundary.
  • Generate the prompt’s schema from the same Pydantic model you validate with.
  • Forbid extra fields so drift becomes visible.
  • Feed exact validation errors back for a single, bounded repair.
  • Make the final failure path explicit, and log raw output for later analysis.