Back to Tutorials
LLM Application Development
Intermediate

Validate LLM Output with Pydantic: Valid Isn’t Right

Validate a real model’s JSON as you type, against a Pydantic model with business rules, then see what happens when its errors are sent back for a second try.

9 minInteractive: drag, click and try things as you read


Getting a language model to return JSON is the easy part. The hard part is trusting what’s inside: a quantity written as “two dozen”, a date that has already passed, a field that’s missing. Pydantic, the most widely used data-validation library in Python, turns a description of the data you expect into a checker that fails loudly when an answer doesn’t fit. Here you’ll validate a real model’s answers, send its mistakes back to it, and see what validation can’t catch. Validation tells you an answer has the right shape, not that it’s right.

Describe the data you expect#

In Pydantic you describe the data as a Python class, a model, with a type for every field. Bean There, a made-up café, takes catering orders by message, and wants each one as:

from datetime import date
from pydantic import BaseModel, Field, field_validator

class Item(BaseModel):
    item: str = Field(min_length=1)
    quantity: int = Field(ge=1)              # at least 1

class Order(BaseModel):
    name: str = Field(min_length=1)
    items: list[Item] = Field(min_length=1)  # at least one item
    date: date | None                        # None when the message gives no date
    delivery: bool

    @field_validator("date")
    @classmethod
    def after_today(cls, v):                 # a business rule: no orders for today or the past
        if v is not None and v <= date(2026, 10, 10):
            raise ValueError("must be after today, Saturday 10 October 2026")
        return v

Order.model_validate_json(answer) either returns an Order your code can use, or raises a ValidationError listing every problem. By default Pydantic is forgiving about harmless differences: the text “24” becomes the number 24, “yes” becomes True, and fields it doesn’t know are dropped. It is strict about everything else.

Predict first

The model writes the quantity as the text "24" instead of the number 24. What does Pydantic do?

Try it
Your browser runs a JavaScript copy of this Pydantic model as you type. We checked it against real Pydantic on every answer in this explainer and a set of awkward cases, and it gives the same errors (for text that isn’t JSON at all, Pydantic also says where it stopped reading). The model’s answers come from Qwen3-1.7B, a small open model, run offline.

Each error names the exact place and the reason: items.0.quantity, “unable to parse string as an integer”. That precision pays off twice: your code gets a clear reason to log, and, as the next section shows, you can hand the same message back to the model. Now turn the business rules off. Today’s date passes, and so does an order with no items: both are perfectly good values of the right type. Types catch the wrong shape; rules catch what doesn’t make sense for your business.

When it fails, send the errors back#

A validation error is also a very good instruction. The usual pattern: if the answer fails, send the model its own answer plus Pydantic’s error messages, and ask for a corrected version. Retry once or twice, then give up and hand the message to a person.

Try it
All 30 orders, with real first answers, real Pydantic errors, and the model’s real second answer after seeing them. Tap an order to read the exchange. “Right” means every field matches what the message asked for.

29 of the 30 first answers were valid. The one that wasn’t, order 5, turned “a week today” into today’s date. Sent back with Pydantic’s message, the model returned a valid answer by leaving the date empty, which passes every rule and is still wrong. That’s the limit of the retry pattern: the model fixes what the error describes, not necessarily the real mistake.

In all, 15 of the 30 orders came out right in every field, against 8 of 30 in the JSON explainer, whose schema forced a date. Allowing an empty date changed the mistakes rather than ending them: the 11 wrong dates are all empty now, where before they were invented, and an empty date is something your code can catch and ask the customer about. The other common mistake, 9 collections marked as deliveries, passes every check, because no schema can know which one the customer meant.

In code#

The whole loop, with the same small model, free and local (pip install pydantic transformers torch), on order 5:

from datetime import date
from pydantic import BaseModel, Field, ValidationError, field_validator
from transformers import AutoModelForCausalLM, AutoTokenizer

class Item(BaseModel):
    item: str = Field(min_length=1)
    quantity: int = Field(ge=1)

class Order(BaseModel):
    name: str = Field(min_length=1)
    items: list[Item] = Field(min_length=1)
    date: date | None
    delivery: bool

    @field_validator("date")
    @classmethod
    def after_today(cls, v):
        if v is not None and v <= date(2026, 10, 10):
            raise ValueError("must be after today, Saturday 10 October 2026")
        return v

name = "Qwen/Qwen3-1.7B"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name)

def ask(messages):
    prompt = tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True, enable_thinking=False)
    inputs = tok(prompt, return_tensors="pt")
    out = model.generate(**inputs, max_new_tokens=140, do_sample=False)
    return tok.decode(out[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)

def extract(message, retries=1):
    schema = ('{"name": string, "items": [{"item": string, "quantity": integer}], '
              '"date": "YYYY-MM-DD" or null if the message gives no date, "delivery": boolean}')
    messages = [
        {"role": "system", "content": "You take catering orders for Bean There, a café. Today is Saturday 10 October 2026."},
        {"role": "user", "content": f"Extract the order from this message. Return ONLY valid JSON matching this schema, "
                                    f"with no markdown and no commentary:\n{schema}\n\nMessage: {message}"},
    ]
    for attempt in range(retries + 1):
        answer = ask(messages)
        try:
            return Order.model_validate_json(answer)
        except ValidationError as e:
            errors = "\n".join(f"{'.'.join(map(str, err['loc']))}: {err['msg']}" for err in e.errors())
            print(f"attempt {attempt + 1} failed:\n{errors}")
            messages += [{"role": "assistant", "content": answer},
                         {"role": "user", "content": f"That JSON failed validation:\n{errors}\nReply with the corrected JSON only."}]
    return None  # still invalid: hand it to a person

print(extract("Hi, Jordan Blake. I need 40 sandwiches and 20 pastries for a meeting a week today. We can collect."))
# attempt 1 failed:
# date: Value error, must be after today, Saturday 10 October 2026
# name='Jordan Blake' items=[Item(item='sandwiches', quantity=40), Item(item='pastries', quantity=20)] date=None delivery=True

The retry passes, and the order is still wrong twice over: no date where the customer said “a week today”, and a delivery where they said they’d collect. Validation got the answer into a shape your code can trust; whether it’s the right order is a separate check, against the message itself or by a person.

What to remember

  • A Pydantic model turns a description of your data into a checker: you get a typed object, or a clear list of everything that’s wrong.
  • Send the errors back for one retry: here it fixed the only invalid answer, but by emptying the date, so a valid retry can still be wrong.
  • Validation checks shape and rules, not truth: test the values against real examples, and send what fails to a person.

Keep going

Sign in to save your place and keep a learning streak. Free, with Google.