Skip to content
AgenticAIWiki
  1. Learn
  2. Part 0
  3. 1. Engineering prerequisites for AI apps
  4. 1.2

Lesson 1.2 · 2 of 7 · 7 min read · Reviewed 24 Nov 2026

Pydantic models and runtime validation

By the end, you can

  • Define a Pydantic model for data a model returns and validate it at runtime.
  • Decide what to do when validation fails: retry, repair or reject.

Python type hints are promises nobody checks. Write total: float and Python will still happily store the string "forty" there. That is fine for code you control. It is not fine for text that a model, a user or another service sent you.

Runtime validation means checking real data against a declared shape at the moment it arrives. Pydantic is the most widely used Python library for this. (In TypeScript, Zod plays the same role.)

A worked example

You ask a model to extract an invoice as JSON. Declare the shape once:

from pydantic import BaseModel, Field, ValidationError

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

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

Then validate what came back:

try:
    invoice = Invoice.model_validate_json(reply_text)
except ValidationError as err:
    print(err)

If the reply had "quantity": 0 and "currency": "euros", the error lists both problems, each with the path to the field (items.0.quantity, currency) and the rule it broke. After a successful call you have a real object: invoice.items[0].unit_price is a float, and your editor knows it.

What Pydantic does for you

Feature Why it matters for AI apps
Type checking and coercion "3" becomes 3 for an int field by default; "three" fails
Constraints (ge, max_length, pattern) Catches values that parse but make no sense
Nested models and lists Real extraction outputs are rarely flat
Clear error paths You can feed them straight back to the model
model_json_schema() Generates the JSON Schema for a tool or structured output

That last row is the quiet win. Use the same class to tell the model what shape you want and to check what it sent. One source of truth.

When validation fails

A bad reply is normal, not exceptional. Plan for three outcomes:

  1. Retry with feedback. Append the model’s reply and a short user message: “Your JSON failed validation: items.0.quantity must be at least 1. Return corrected JSON only.” Cap it at one or two retries.
  2. Repair in code. Trim whitespace, strip a stray code fence, normalise "eur" to "EUR". Only for fixes you are sure are safe.
  3. Reject and escalateEscalation: Handing a case from an agent to a person, with the context needed to continue.. Log it, return an error to the caller or send it to a person. Never pass half-valid data on.

Structured outputStructured outputs: Making a model return data that matches a defined schema, such as JSON with required fields and types. features that constrain the model to a schema (chapter 14) reduce failures a lot, but keep validating: constraints such as “quantity at least 1” or business rules are still your job.

Common mistakes

  • Validating with json.loads alone. It checks syntax, not shape.
  • Making every field optional so validation “passes”. You have moved the bug downstream.
  • Retrying forever. Two failed retries usually mean the prompt or schema needs fixing.
  • Catching ValidationError and continuing with the raw dict.

Key points

  • Type hints are not checked when the program runs. A Pydantic model checks real data against them and raises a clear error when it does not fit.
  • Validate everything that crosses a boundary: model output, tool inputs, HTTP bodies and config.
  • A validation error is useful feedback. Send the error text back to the model and ask for a corrected reply, with a retry cap.
  • Pydantic can export a JSON Schema from the same model, so the shape you ask for and the shape you check never drift apart.
Hands-on labRuns in the Playground

Validate model JSON and retry once

Check a model's JSON reply field by field, collect every error, and send them back for a corrected reply.

You will have: A validator that lists every failing field with its rule, and a retry loop that ends with a valid Invoice or a rejection.

Steps

  1. Write a check for each field: a non-empty id, a 3-letter currency, an integer quantity of at least 1, a price of at least 0.
  2. Report missing fields as "field required".
  3. Run it on the first fake reply and read both errors.
  4. Loop up to two retries, sending the error text back as feedback, and stop on the first valid reply.

Done when

  • The first attempt reports both the currency and the quantity errors.
  • The second attempt builds a valid Invoice object.
  • No invalid data is used after a failed validation.

Open in the Playground No API key needed.

Starter code (Python)
import json
import re
from dataclasses import dataclass

# The Playground has no Pydantic, so you will write the same checks by hand.
@dataclass
class Invoice:
    invoice_id: str
    currency: str
    quantity: int
    unit_price: float

def validate(text):
    data = json.loads(text)
    errors = []
    # TODO: check invoice_id is a non-empty string
    # TODO: check currency matches ^[A-Z]{3}$
    # TODO: check quantity is an integer of at least 1, unit_price a number of at least 0
    # TODO: add "field: field required" for any missing field
    return (Invoice(**data) if not errors else None), errors

def fake_model(feedback=None):
    """First reply has two mistakes; given the error text, it corrects them."""
    if feedback is None:
        return '{"invoice_id": "INV-105", "currency": "euros", "quantity": 0, "unit_price": 12.5}'
    return '{"invoice_id": "INV-105", "currency": "EUR", "quantity": 1, "unit_price": 12.5}'

invoice, errors = validate(fake_model())
print("valid:", invoice, "| errors:", errors)
# TODO: loop up to 2 retries: on errors, build a feedback message from them and call fake_model(feedback)
Show a solution
import json
import re
from dataclasses import dataclass

# The Playground has no Pydantic, so this small validator does the same job by hand:
# check every field, collect every error with its path, and only then build the object.
@dataclass
class Invoice:
    invoice_id: str
    currency: str
    quantity: int
    unit_price: float

RULES = {
    "invoice_id": lambda v: None if isinstance(v, str) and v else "must be a non-empty string",
    "currency": lambda v: None if isinstance(v, str) and re.fullmatch(r"[A-Z]{3}", v) else "must match ^[A-Z]{3}$",
    "quantity": lambda v: ("must be an integer" if not isinstance(v, int) or isinstance(v, bool)
                           else None if v >= 1 else "must be at least 1"),
    "unit_price": lambda v: ("must be a number" if not isinstance(v, (int, float))
                             else None if v >= 0 else "must be at least 0"),
}

def validate(text):
    try:
        data = json.loads(text)
    except json.JSONDecodeError:
        return None, ["(root): not valid JSON"]
    errors = [f"{k}: field required" if k not in data else f"{k}: {msg}"
              for k, check in RULES.items() if k not in data or (msg := check(data[k]))]
    return (Invoice(**{k: data[k] for k in RULES}) if not errors else None), errors

def fake_model(feedback=None):
    """First reply has two mistakes; given the error text, it corrects them."""
    if feedback is None:
        return '{"invoice_id": "INV-105", "currency": "euros", "quantity": 0, "unit_price": 12.5}'
    return '{"invoice_id": "INV-105", "currency": "EUR", "quantity": 1, "unit_price": 12.5}'

MAX_RETRIES = 2
feedback = None
for attempt in range(MAX_RETRIES + 1):
    invoice, errors = validate(fake_model(feedback))
    if invoice:
        print(f"attempt {attempt + 1}: valid -> {invoice}")
        break
    print(f"attempt {attempt + 1}: errors: " + "; ".join(errors))
    feedback = "Your JSON failed validation: " + "; ".join(errors) + ". Return corrected JSON only."
else:
    print("rejected after retries")
Quick checkThe model returns {"total": "forty"} for a field typed as float. What does model_validate do?
How sure are you?
Pick an answer and how sure you are