01B.6 Data Validation with Pydantic

FoundationsLesson 6 of 1113,580 words7 parts
Module 01B · 0 of 11 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11

Somewhere between your code and the outside world, data stops being trustworthy. A JSON payload arrives from an API with a field missing; a user types "42" where you expected a number; an LLM returns a reply that is almost the JSON shape you asked for; a settings file has a typo in a key. Python won't stop any of it: a dict can hold anything, and a type hint is only a note to readers and type checkers, not a gatekeeper. Pydantic is the library that closes that gap: you describe the shape data must have once, as a Python class, and Pydantic checks every piece of incoming data against it — coercing what it safely can, rejecting what it can't, and telling you exactly which field failed and why. It is the most-used data-validation library in the Python AI ecosystem: every major provider SDK returns Pydantic objects, every structured-output feature takes a Pydantic model as its schema, FastAPI is built on it, and the configuration lessons in this module already lean on it. This lesson teaches Pydantic v2 completely: models, field types and constraints, aliases, the three ways to validate input, lax versus strict mode, custom validators, discriminated unions, serialisation, JSON Schema generation, and the failure modes that bite in production — all on the module's neutral ticket-and-fake-backend examples, with no API key and no model calls.

What you'll learn

  • Why validation matters, and the difference between type hints and runtime validation
  • BaseModel in depth: every field type you'll meet, defaults versus default_factory, and the required / optional / nullable trap
  • Constraints with Field(...) and reusable types with Annotated, aliases, and model_config (ConfigDict)
  • The three doors data comes through: Model(**data), model_validate(), model_validate_json(), model_validate_strings(), and TypeAdapter
  • Lax versus strict mode: the coercion table, Strict* types, and custom error messages
  • ValidationError anatomy: errors(), loc, msg, type, input, json() — and turning errors into a readable message or an LLM "repair prompt"
  • Custom validation: @field_validator and @model_validator in every mode, Annotated validators, normalisation, PydanticCustomError, validation context, discriminated unions, recursive models, generics, forward references and @validate_call for function arguments
  • Serialisation: model_dump(), model_dump_json(), serializers, and model_json_schema() — how a Python class becomes the JSON Schema providers enforce
  • RootModel, and how Pydantic models compare with dataclasses, TypedDict and pydantic.dataclasses
  • Performance and production gotchas: model_construct, TypeAdapter reuse, mutable defaults, extra="forbid", circular models
  • Pydantic inside the AI stack: SDK response objects, validating LLM-shaped output without an LLM, streaming/partial validation, and the module's aitoolkit/models.py deliverable

What you don't need

  • Any API key, provider account, or model. Everything here runs on plain Python data; the LLM-shaped examples use canned strings you write yourself.
  • Deep Pydantic experience — if you've ever written class Foo(BaseModel), skim Part 2 and go straight to Part 4.
  • The provider API details of structured output and tool calling. This lesson owns Pydantic; lesson 03.4 and lesson 03.5 own what providers do with your models.

Setup

The samples need Python 3.11+ and Pydantic v2. If you haven't set up the module's aitoolkit project yet, create it first (see lesson 01B.1):

bash
uv init aitoolkit --package --python 3.13 && cd aitoolkit
uv add pydantic
# Only if you want EmailStr/NameEmail validation (they need the email-validator package):
uv add 'pydantic[email]'
# or, without uv: pip install pydantic 'pydantic[email]'

The samples were checked against Pydantic 2.14 as of November 2026. An unversioned install gives you the newest release, so a later 2.x minor version may deprecate or change something; check the Pydantic changelog if a sample does not match. pydantic-settings comes along in lesson 01B.2 for configuration; this lesson uses plain BaseModel, so you only need pydantic. No API key needed.


What you must be able to do after this lesson#

  • Explain the difference between type hints and runtime validation
  • Define a Pydantic model with typed fields, defaults and Field constraints
  • Validate data with model_validate and model_validate_json
  • Read a ValidationError and turn it into a clear message
  • Write a field_validator and a model_validator
  • Export a model with model_dump and model_json_schema
  • Validate LLM-shaped output with Pydantic

Why this matters for an AI engineer#

Pydantic is the connective tissue of the whole path. Nearly every place your code touches data that came from somewhere else, a model is the boundary:

You'll hear... You'll understand it after...
"The SDK response is just a Pydantic model." 7.1 SDK response objects
"Define the output schema as a Pydantic model." 5.3 model_json_schema()
"The strict-mode schema rejected my Optional field." 2.2 Required, optional and nullable and 03.4 §2.4
"Validate the tool arguments before you run the function." 4.5 Discriminated unions and 08A.6
"The API returned 422 — what does that body mean?" 3.5 ValidationError anatomy (FastAPI renders it for you in 01B.7)
"Feed the validation errors back to the model and ask it to fix the JSON." 3.5 ValidationError anatomy and 03.4 Part 7
"Store metadata as a typed record, not a free-form dict." 05.8
"The judge must return JSON matching this schema." 10A.4
"Settings should fail fast when an env var is missing." 01B.2 (pydantic-settings is BaseSettings, a BaseModel)

Part 1: Why validate at all#

1.1 The data you can't trust#

Your Python code sits in the middle of a pipeline. Data flows in from many directions, and every one of them can lie — not maliciously, just sloppily:

flowchart LR
    subgraph outside ["The outside world (untrusted)"]
        A["JSON from an API<br/>(missing keys, nulls, surprises)"]
        B["User input<br/>(strings where ints were expected)"]
        C["LLM output<br/>(almost-JSON, wrong types, extra prose)"]
        D["Files and databases<br/>(old formats, typos, drift)"]
    end
    subgraph boundary ["The validation boundary (this lesson)"]
        V["Pydantic models<br/>coerce or reject, once"]
    end
    subgraph inside ["Your application (trusted)"]
        E["Typed model instances<br/>fields guaranteed by contract"]
        F["Business logic, APIs, storage"]
    end
    A --> V
    B --> V
    C --> V
    D --> V
    V -->|"valid"| E
    V -->|"invalid: collect every error"| G["Errors → logs,<br/>a 422 response,<br/>or a repair prompt"]
    E --> F

A realistic example: your fake ticket API returns ticket records as JSON. Somewhere in the pipeline a ticket looks like this:

json
{"id": "T-1042", "title": "Login fails on Safari", "priority": "ASAP", "tags": "urgent,billing", "votes": "17"}

Look at what a naive dict consumer gets wrong, one field at a time:

  • priority is "ASAP" — you expected one of low / normal / high / urgent. Nothing in Python stops you comparing it to "high" and silently getting False forever.
  • tags is a single comma-joined string, not a list — a for tag in ticket["tags"] loop iterates over characters.
  • votes is the string "17", not the integer 17 — votes + 1 raises TypeError, or worse, somewhere downstream votes == 17 is silently False.
  • created_at might be missing entirely, or be null, or be "2026-11-01" (a date) when the rest of the system expects a full timestamp.
  • The payload might contain a key you never declared — a renamed field from a newer API version, a "internal_debug" block, or a typo like "titel" that means your title logic never runs.

None of these are exotic. They are Tuesday. The fix is not to sprinkle isinstance checks through your code — it is to validate once, at the boundary, and let everything downstream assume the contract holds.

1.2 Type hints are not validation#

If you came through Module 01A, you know Python's type hints: def get_ticket(t: Ticket) -> str. They are excellent documentation, they power your IDE's autocomplete, and static checkers like mypy read them. But at run time they do nothing:

python
def show(ticket: Ticket) -> str:
    return f"{ticket.id}: {ticket.priority}"

# The hint says Ticket. Python does not check. This runs fine:
show({"id": "T-1", "priority": "ASAP"})   # ...until ticket.id blows up elsewhere

The annotation is a promise the caller is supposed to keep; nothing enforces it. A function annotated -> int can happily return "not a number", and list[Ticket] doesn't stop a list[dict] from being passed. Pydantic closes exactly this gap: the same type-hint syntax you already write becomes a runtime contract.

1.3 Where Pydantic sits in the AI stack#

You will meet Pydantic in almost every later module, always at a boundary:

Place What the model does there Lesson that goes deep
Provider SDK responses response.output, response.usage are Pydantic objects; .model_dump() serialises them 03.1 §8.3
Structured outputs Your BaseModel becomes the JSON Schema the provider constrains decoding to 03.4
Tool definitions Tool parameters schemas are generated from Pydantic models; input_schema validates arguments 03.5, 08A.6
Configuration BaseSettings (a BaseModel subclass) parses env vars and .env once, typed 01B.2
APIs you build FastAPI validates request bodies and serialises responses through your models 01B.7
Data pipelines Metadata records, chunk records and eval cases are stored as validated models 05.8, 10A.2
LLM output you parse yourself Extract JSON, validate it, feed errors back for a repair attempt 03.4 Part 7
Guardrails Output validation: schema checks before model output reaches users or tools 12.5

One library, one mental model, everywhere data crosses a boundary. That is why this lesson goes deep on the library itself rather than only on the AI use cases.

1.4 Pydantic v1 versus v2#

Throughout this lesson "Pydantic" means v2 (Pydantic 2.14.3 was released on 5 November 2026 and was the newest 2.14.x patch on PyPI as of November 2026; any 2.14.x works). If you see from pydantic import BaseModel plus class Config: or @validator, you are looking at v1 code.

1.5 Your first model#

Here is the smallest useful model in the lesson — a support ticket as your fake API might return it. Everything here is standard Pydantic v2:

python
# ticket_model.py — needs: pydantic
from pydantic import BaseModel


class Ticket(BaseModel):
    id: str
    title: str
    priority: str = "normal"      # optional: has a default


t = Ticket(id="T-1042", title="Login fails on Safari", priority="ASAP")
print(t)
print(type(t.priority), t.priority)
Example output · illustrative2 lines
id='T-1042' title='Login fails on Safari' priority='ASAP'
<class 'str'> ASAP

Two things already happened that a plain dict never does for you:

  1. The instance is typed. t.priority is guaranteed to be a str; your editor autocompletes t.title, and a type checker knows the shape.
  2. Defaults fill gaps. If priority had been omitted, "normal" would be used — and t.model_fields_set would still tell you the caller didn't supply it (useful when "absent" and "explicitly default" mean different things).

Note that priority="ASAP" passed: str accepts any string. Constraints — allowed values, lengths, ranges — are what Part 2 adds. Validation isn't just "is it a string"; it's "is it a string we can act on".


Part 2: Models and fields#

2.1 BaseModel and the field-type catalogue#

A model is a class that inherits from pydantic.BaseModel and declares fields as annotated attributes. The annotation is the schema: id: int means "an integer named id, required". Pydantic reads those annotations at class-creation time and builds a validator for the whole class.

python
# fields_demo.py — needs: pydantic
from datetime import date, datetime
from decimal import Decimal
from enum import Enum
from pathlib import Path
from typing import Literal
from uuid import UUID

from pydantic import BaseModel, HttpUrl, SecretStr


class Priority(str, Enum):
    LOW = "low"
    NORMAL = "normal"
    HIGH = "high"
    URGENT = "urgent"


class Ticket(BaseModel):
    id: str                                  # required
    title: str                               # required
    description: str | None = None           # optional AND nullable
    priority: Priority = Priority.NORMAL     # enum with a default
    votes: int = 0
    score: float | None = None
    labels: list[str] = []                   # safe: Pydantic copies the default
    metadata: dict[str, str] = {}
    due: date | None = None                  # ISO date string "2026-11-30" -> date
    created_at: datetime | None = None       # ISO timestamp -> datetime
    reference: UUID | None = None            # "3f6b1c9e-..." -> UUID object
    price: Decimal | None = None             # exact decimal, never float
    attachment: Path | None = None           # path-like string -> pathlib.Path
    homepage: HttpUrl | None = None          # must be a valid http(s) URL
    api_token: SecretStr | None = None       # never appears in repr/logs
    channel: Literal["email", "chat", "api"] | None = None


t = Ticket(
    id="T-1042",
    title="Login fails on Safari",
    priority="urgent",            # string coerced to the Priority enum
    votes="17",                   # lax mode: string coerced to int
    labels=["billing", "auth"],
    due="2026-11-30",
    reference="3f6b1c9e-2a4d-4e8b-9c1f-0a2b3c4d5e6f",
    price="19.99",
    homepage="https://example.com/status",
    api_token="sk-...",
)
print(t)
print("votes:", t.votes, type(t.votes).__name__)
print("due:", t.due, type(t.due).__name__)
print("price:", t.price, type(t.price).__name__)
print("token repr:", repr(t.api_token))
Example output · illustrative5 lines
id='T-1042' title='Login fails on Safari' description=None priority=<Priority.URGENT: 'urgent'> votes=17 score=None labels=['billing', 'auth'] metadata={} due=datetime.date(2026, 11, 30) created_at=None reference=UUID('3f6b1c9e-2a4d-4e8b-9c1f-0a2b3c4d5e6f') price=Decimal('19.99') attachment=None homepage=HttpUrl('https://example.com/status') api_token=SecretStr('**********') channel=None
votes: 17 int
due: 2026-11-30 date
price: 19.99 Decimal
token repr: SecretStr('**********')

Read that output closely — it is the whole point of the library:

  • "urgent" became Priority.URGENT; "17" became 17; "2026-11-30" became a date; the UUID string became a UUID; "19.99" became a Decimal (exact, unlike float); the URL string became an HttpUrl object.
  • api_token prints as SecretStr('**********') — the whole model's repr, str and model_dump() hide it. (Serialising it to JSON on purpose still needs get_secret_value() — see 5.2.)
  • labels: list[str] = [] looks like the mutable-default bug you learned about in 01A.6 — but Pydantic deep-copies defaults per instance, so two tickets never share one list. See 6.3 for why this is safe here and still a smell elsewhere.
  • tuple and set aren't in the demo but work the same way: coords: tuple[float, float] accepts any 2-sequence ([1.5, 2.0] → (1.5, 2.0)), and tags: set[str] deduplicates its input (["a", "b", "a"] → {"a", "b"}) — reach for a set when order doesn't matter and duplicates should collapse.

2.2 Required, optional and nullable: the three-way trap#

This is the single most-misunderstood corner of Pydantic, and it matters enormously for LLM structured output (03.4 §2.4 builds a whole section on it). Three different states are easy to confuse:

Declaration Must the key be present? May the value be null/None? JSON Schema shape
name: str ✅ yes ❌ no {"type": "string"} in required
name: str | None (no default) ✅ yes ✅ yes in required, anyOf [string, null]
name: str | None = None ❌ no ✅ yes not in required, anyOf [string, null]
name: str = "x" ❌ no ❌ no (default is a string) not in required, {"type": "string"}

The trap: in Pydantic v1, Optional[str] implied = None, so "optional" meant "may be absent". In v2 that changed: str | None without a default is required but nullable — the key must be sent, though its value may be null. This trips up everyone porting v1 code, and it is exactly the shape strict structured-output modes want: the model must always answer the field, but may answer "I don't know" with null.

python
# optional_trap.py — needs: pydantic
from pydantic import BaseModel, ValidationError


class Reply(BaseModel):
    text: str
    confidence: float | None            # required-but-nullable
    note: str | None = None             # truly optional


print(Reply.model_validate({"text": "ok", "confidence": None}).model_dump())
#> {'text': 'ok', 'confidence': None, 'note': None}

try:
    Reply.model_validate({"text": "ok"})          # confidence key missing entirely
except ValidationError as e:
    print(e.errors()[0]["loc"], "->", e.errors()[0]["msg"])
Example output · illustrative2 lines
{'text': 'ok', 'confidence': None, 'note': None}
('confidence',) -> Field required

Rule of thumb: X | None alone = "must be present, may be null"; X | None = None = "may be absent or null"; X = default = "may be absent, never null". Choose deliberately — for LLM-facing schemas, "must answer, may say null" (X | None, no default) is usually the right contract because it forces the model to make a decision instead of silently omitting the field.

2.3 Defaults and default_factory#

A field with a default becomes optional to provide. Two ways to supply one:

  • = value — a plain default. Fine for immutables (str, int, None, enums, frozen datetimes).
  • Field(default_factory=callable) — called fresh for every instance. Required whenever the default is mutable (list, dict, set) or expensive. Pydantic is smart enough to copy even plain mutable defaults, but default_factory is the idiom everyone recognises — and the only option for things like datetime.now where you want each instance's time, not the class-definition time.
python
# defaults_demo.py — needs: pydantic
from datetime import datetime, timezone
from pydantic import BaseModel, Field


class AuditEvent(BaseModel):
    kind: str
    tags: list[str] = Field(default_factory=list)     # fresh list per event
    payload: dict = Field(default_factory=dict)
    at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))


a = AuditEvent(kind="created")
b = AuditEvent(kind="updated")
a.tags.append("first")
print(a.tags, b.tags)          # b is untouched: each got its own list
print(a.at <= b.at)            # each timestamp is its own
Example output · illustrative2 lines
['first'] []
True

2.4 Constraints: Field(...) and Annotated#

Types say what a field is; constraints say what values are acceptable. Field() carries them:

python
# constraints_demo.py — needs: pydantic
from typing import Annotated

from pydantic import BaseModel, ConfigDict, Field, StringConstraints, ValidationError

# A reusable constrained type: "a short slug, lowercase letters/digits/dashes"
Slug = Annotated[str, StringConstraints(pattern=r"^[a-z0-9]+(-[a-z0-9]+)*$", min_length=2, max_length=64)]


class TicketIn(BaseModel):               # the shape a client POSTs to create a ticket
    model_config = ConfigDict(extra="forbid")

    title: Annotated[str, StringConstraints(strip_whitespace=True, min_length=3, max_length=200)]
    description: str = ""
    priority: str = Field(default="normal", pattern="^(low|normal|high|urgent)$")
    votes: int = Field(default=0, ge=0, le=100_000)
    score: float = Field(ge=0.0, le=1.0)
    tags: list[Slug] = Field(default_factory=list, max_length=10)
    ref: str = Field(min_length=4, max_length=32, description="Caller-supplied idempotency key")


good = TicketIn(title="  Login fails on Safari  ", priority="high",
                votes=3, score=0.8, tags=["auth-bug"], ref="req-001")
print(good.title)                        # whitespace stripped: "Login fails on Safari"

for bad in ({"title": "hi", "priority": "ASAP", "votes": -1, "score": 2.0,
             "tags": ["Bad Slug!"], "ref": "x"},
            {"title": "ok title", "priority": "normal", "votes": 0, "score": 0.5,
             "tags": [], "ref": "req-ok", "surprise": 1}):
    try:
        TicketIn.model_validate(bad)
    except ValidationError as e:
        print(f"--- {len(e.errors())} error(s) ---")
        for err in e.errors():
            print(" ", ".".join(map(str, err["loc"])), "->", err["msg"])
Example output · illustrative10 lines
Login fails on Safari
--- 6 error(s) ---
  title -> String should have at least 3 characters
  priority -> String should match pattern '^(low|normal|high|urgent)$'
  votes -> Input should be greater than or equal to 0
  score -> Input should be less than or equal to 1
  tags.0 -> String should match pattern '^[a-z0-9]+(-[a-z0-9]+)*$'
  ref -> String should have at least 4 characters
--- 1 error(s) ---
  surprise -> Extra inputs are not permitted

The second block's Extra inputs are not permitted only appears because the model sets extra="forbid" — by default Pydantic ignores unknown keys. That default is convenient and dangerous; 2.6 shows how to flip it. TicketIn sets extra="forbid" explicitly — do the same whenever a schema is a contract (APIs, tool args, stored records), and leave "ignore" only for genuinely open payloads.

Notes on the mechanics:

  • Annotated[type, constraint] stacks rules onto a type without new classes — this is the modern, recommended style (01A.10 introduced Annotated). StringConstraints, plus annotated_types helpers like Ge, Le, Len, Predicate, compose freely: Annotated[int, Ge(0), Le(100)].
  • Field(...) and Annotated compose: Field also accepts the same constraint kwargs (min_length, ge, pattern...) as shorthand, and description/examples feed the JSON Schema (and therefore the prompt the provider model sees — write them for the model, not just for humans; 08A.6 §1.4).
  • Constraints are checked after type coercion: votes="17" still becomes 17 then the ge/le check runs.
  • strip_whitespace=True in StringConstraints normalises input — the kind of "accept messy, store clean" rule you'll write constantly for LLM-produced text.

2.5 Aliases: when the wire name isn't the Python name#

Real APIs are inconsistent: JSON keys are often snake_case, camelCase, or legacy names ("e-mail"), while Python attributes should be snake_case. Aliases decouple the two directions:

python
# aliases_demo.py — needs: pydantic
from pydantic import BaseModel, ConfigDict, Field


class UserIn(BaseModel):
    model_config = ConfigDict(validate_by_name=True, validate_by_alias=True)   # accept BOTH alias and field name

    full_name: str = Field(alias="fullName", description="The user's display name")
    email_address: str = Field(validation_alias="email", serialization_alias="emailAddress")
    age: int


u = UserIn.model_validate({"fullName": "Ada Lovelace", "email": "ada@example.com", "age": 36})
print(u.full_name, u.email_address)
print(u.model_dump(by_alias=True))
print(u.model_dump())                                  # python names by default
Example output · illustrative3 lines
Ada Lovelace ada@example.com
{'fullName': 'Ada Lovelace', 'emailAddress': 'ada@example.com', 'age': 36}
{'full_name': 'Ada Lovelace', 'email_address': 'ada@example.com', 'age': 36}
  • alias= sets both the validation and serialisation alias (and implies the field can't be populated by its Python name unless validate_by_name=True).
  • validation_alias= / serialization_alias= split the two directions — use them when inbound and outbound names differ (rare but real: an API that reads email but writes emailAddress).
  • validate_by_name=True together with validate_by_alias=True (the default for the second) accepts the Python attribute name as well as the alias — almost always what you want during migration, since it keeps old payloads working. Older code and tutorials spell this populate_by_name=True; Pydantic's own docs mark that spelling as not recommended from v2.11 and due for deprecation in v3, so prefer the validate_by_* pair (as of November 2026). validate_by_alias=False does the opposite — accept only the Python names — and at least one of the two must stay True.
  • Aliases matter for JSON Schema: model_json_schema() emits the alias as the property name by default, which is what providers enforce on LLM output. If your field is full_name with alias "fullName", the model is asked for fullName. (5.3 shows the generated schema.)

2.6 model_config and ConfigDict#

Class-level behaviour lives in model_config = ConfigDict(...). These are the options you will actually use:

python
# config_demo.py — needs: pydantic
from enum import Enum
from pydantic import BaseModel, ConfigDict, ValidationError


class Channel(str, Enum):
    EMAIL = "email"
    CHAT = "chat"


class StrictTicket(BaseModel):
    model_config = ConfigDict(
        extra="forbid",               # unknown keys -> error ("ignore" default, "allow" keeps them in model_extra)
        frozen=True,                 # instances immutable -> hashable, safe as dict keys / in sets
        str_strip_whitespace=True,   # every str field stripped before other checks
        validate_assignment=True,    # t.priority = "bogus" raises instead of silently storing it
        use_enum_values=True,        # store Channel.EMAIL's *value* "email", not the enum member
        validate_by_name=True,       # aliases: accept the python name too (see 2.5)
        # from_attributes=True,      # needed to validate ORM objects / arbitrary objects, not dicts (6.2)
        # strict=True,               # whole-model strict mode (3.4)
    )

    id: str
    channel: Channel
    note: str = ""


t = StrictTicket(id=" T-1 ", channel="chat")
print(t.id, t.channel, type(t.channel).__name__)
try:
    t.id = "T-2"
except ValidationError as e:
    print("frozen:", e.errors()[0]["type"])
Example output · illustrative2 lines
T-1 email str
frozen: frozen_instance
Option Default What it does When you want it
extra "ignore" Unknown keys dropped silently "forbid" for contracts (APIs, tool args, stored data — a typo'd key should fail loudly); "allow" keeps them in model_extra (forward-compat with newer payloads)
frozen False Instances immutable after creation Value objects, cache keys, anything hashed or shared; also makes the model __hash__-able
str_strip_whitespace False Strip str fields before validation User/LLM text input — almost always yes
validate_assignment False Re-validate on obj.field = x Anything long-lived where fields get mutated; costs a little speed
use_enum_values False Store enum.value, not the member When you serialise constantly and don't need enum methods; know you lose the enum type
validate_by_name / validate_by_alias False / True Accept the field name, the alias, or both (replaces the older populate_by_name) Aliased models (2.5)
from_attributes False Validate object attributes, not just mappings ORM rows, SDK objects, dataclasses → model (6.2)
strict False Whole-model strict validation Wire formats where "1" must not become 1 (3.4)
ser_json_* / val_json_* various Fine-grained JSON-mode tweaks Rarely; know they exist
defer_build False Defer schema build for recursive/generic models Advanced recursive models (4.6)

2.7 The special types, quickly#

You met most of these in the 2.1 example. The ones that need a sentence each:

  • EmailStr / NameEmail — real email validation, but they need the optional dependency: uv add 'pydantic[email]' (pulls in email-validator). Without it, defining the model raises ImportError at class-creation time — a classic "works on my machine" bug. (AnyUrl/HttpUrl/FileUrl/PostgresDsn and friends need no extra.)
  • SecretStr / SecretBytes — wrap secrets; repr, str, model_dump() all show **********. You must call .get_secret_value() to use the real value — which is the point: it can't leak into logs by accident. Never put a real key in a model you model_dump() to a log.
  • bytes — in JSON mode, bytes are base64-encoded strings; in Python mode, raw bytes. Handy for small binary payloads; don't put megabytes in a model.
  • Decimal vs float — money and any value where 0.1 + 0.2 != 0.3 matters. Decimal("19.99") is exact; float is binary approximation. JSON Schema emits number/string accordingly, and providers handle Decimal fields (as strings in strict mode — 03.4 §2.8 tests exactly this).
  • datetime / date / time / timedelta — parse ISO 8601 strings (and Unix timestamps for datetime/date in lax mode). Always store aware datetimes (timezone.utc); naive ones serialise without offset and cause ordering bugs across timezones.
  • UUID, Path, Enum/IntEnum/StrEnum, Literal — covered above; Literal["a","b"] is the lightweight alternative to an Enum when you don't need methods, and it maps cleanly to JSON Schema enum (which providers love).
  • Json[...] — a field that is JSON: payload: Json[list[int]] validates the embedded JSON and gives you the parsed object. Niche but real for webhook payloads.
  • AnyUrl family — AnyUrl accepts any scheme; HttpUrl/AnyHttpUrl restrict to http(s) with a host and sane length. In v2 these are classes (AnyUrl("https://...")), not constr-style strings — access .host, .scheme, .path on them.

2.8 Nested models#

Models compose: a field can itself be a model, a list of models, or a dict of models. Validation recurses automatically, and errors carry the full path:

python
# nested_demo.py — needs: pydantic
from pydantic import BaseModel, ValidationError


class Customer(BaseModel):
    id: str
    name: str
    vip: bool = False


class LineItem(BaseModel):
    sku: str
    qty: int
    price: float


class Order(BaseModel):
    order_id: str
    customer: Customer                  # nested model
    lines: list[LineItem]               # list of models
    by_sku: dict[str, LineItem] = {}    # dict of models


o = Order.model_validate({
    "order_id": "SO-1001",
    "customer": {"id": "C-7", "name": "Ada", "vip": "yes"},   # "yes" -> True (lax bool)
    "lines": [{"sku": "A-1", "qty": "2", "price": 9.99}],
    "by_sku": {"B-2": {"sku": "B-2", "qty": 1, "price": 4.5}},
})
print(o.customer.name, o.lines[0].qty, o.by_sku["B-2"].price)

bad = {"order_id": "SO-1002", "customer": {"id": "C-8"},          # name missing
       "lines": [{"sku": "A-1", "qty": "two", "price": 9.99}]}
try:
    Order.model_validate(bad)
except ValidationError as e:
    for err in e.errors():
        print(".", err["loc"], "->", err["msg"])
Example output · illustrative3 lines
Ada 2 4.5
. ('customer', 'name') -> Field required
. ('lines', 0, 'qty') -> Input should be a valid integer, unable to parse string as an integer

The loc tuples — ('customer', 'name'), ('lines', 0, 'qty') — are gold for error reporting: they tell you exactly which nested field broke, which is what a repair prompt or a 422 response needs (3.5).

2.9 The rest of the model API, in one pass#

  • @computed_field — a read-only property that appears in model_dump()/model_dump_json() and in the serialization JSON schema (model_json_schema(mode="serialization"), emitted as "readOnly": true) as if it were a real field: @computed_field @property def display_name(self) -> str: return f"{self.first} {self.last}". It is deliberately absent from the input/validation schema — derived values you want serialised but never accepted as input.
  • Private attributes — names starting with _ (_cache: dict = PrivateAttr(default_factory=dict)) are not fields: not validated, not serialised, not in the schema. Real internal state.
  • model_fields — the class's field definitions (dict[str, FieldInfo]); access it on the class (Ticket.model_fields), not the instance (instance access is deprecated). Useful for introspection, form generation, and generic code.
  • model_fields_set — which fields the caller actually supplied (vs defaulted). Invaluable for PATCH semantics and "did the LLM omit this or send null?".
  • model_copy(update={...}) — shallow copy with some fields replaced; does not validate the update. Fine for trusted internal tweaks; never for untrusted input.
  • Equality and hashing — two models are equal when their field values are equal (Ticket(...) == Ticket(...)); models are unhashable by default, but frozen=True makes them hashable (safe dict keys/set members).
  • model_extra — with extra="allow", undeclared keys land here (same mechanism SDKs use — 7.1).

Part 3: Getting data in — the three doors#

3.1 Model(**data) versus model_validate()#

There are two ways to build a model from a mapping, and they differ in one important way:

python
# doors_demo.py — needs: pydantic
from pydantic import BaseModel


class Ticket(BaseModel):
    id: str
    votes: int = 0


data = {"id": "T-1", "votes": "3"}

a = Ticket(**data)                          # door 1: unpack kwargs
b = Ticket.model_validate(data)             # door 2: pass the mapping
c = Ticket(id="T-2", votes=4)               # door 3: keyword args, as usual
print(a, b, c, sep="\n")
Example output · illustrative3 lines
id='T-1' votes=3
id='T-1' votes=3
id='T-2' votes=4
  • Ticket(**data) works when data is a dict with string keys — the normal case for response.json() results. Non-string keys raise TypeError: keywords must be strings; non-identifier string keys like "a-b" are accepted silently and land as (usually ignored) extra fields — which is exactly why model_validate is the safer canonical entry point.
  • Ticket.model_validate(data) is the canonical entry point: it accepts the mapping as-is, and it's what generic code (FastAPI, SDK internals, your own helpers) calls. Prefer it in libraries and anywhere the input might not be a plain dict of identifiers.
  • Both run the same validation; Model(...) is sugar. There is also model_validate_strings() — the third input mode, for "everything arrived as text" payloads (form posts, CSV-ish dicts, env-var-style config). It takes a (potentially nested) dict with string keys and string values and validates it in JSON mode, so the strings are coerced into the field types ("3" becomes 3, "true" becomes True; the exact string forms accepted for each type are in the docs' conversion table, and the docs' own examples cover an integer id and an ISO datetime). The docs do not say what happens with lists; the validator source (pydantic-core as shipped with Pydantic 2.14.3, read on 11 November 2026) answers it: every value must be a string or a nested dict, so a Python list inside the dict is rejected with a string_type error, and a field annotated list[...], tuple[...] or set[...] fails with list_type, tuple_type or set_type even when the string looks like a list. Treat it as a door for flat or nested dicts of text; it is not meant for a whole JSON list sitting inside one string, so for JSON text use model_validate_json instead.

3.2 model_validate_json() — the right door for JSON text#

When your input is a JSON string (an LLM reply, a file, a webhook body), don't json.loads it first and then model_validate the dict — call model_validate_json() directly:

python
# json_door.py — needs: pydantic
from pydantic import BaseModel


class Ticket(BaseModel):
    id: str
    votes: int = 0


raw = '{"id": "T-9", "votes": "12", "extra": "dropped by default"}'
t = Ticket.model_validate_json(raw)         # parses AND validates in one pass
print(t, "| votes type:", type(t.votes).__name__)

# It also accepts bytes and bytearray — handy for response.content:
t2 = Ticket.model_validate_json(raw.encode())
print(t2.id)
Example output · illustrative2 lines
id='T-9' votes=12 | votes type: int
T-9

Why prefer it (the docs say it is "generally considered faster" for JSON payloads):

  • One pass, in Rust. model_validate_json hands the raw text to pydantic-core's JSON parser, which validates while parsing — no intermediate Python dict, no second traversal. For large payloads the difference is real.
  • Malformed JSON fails at parse time — with positions. Trailing commas, single quotes, unquoted keys and bad tokens raise a ValidationError of type json_invalid whose message says where (Invalid JSON: trailing comma at line 1 column 9), before any field validation runs. json.loads rejects the same inputs but with a bare JSONDecodeError you have to reconcile with your model errors yourself. Two leniencies it shares with json.loads, worth knowing: a duplicated object key keeps the last value, and the underlying jiter parser accepts NaN/Infinity — neither is valid strict JSON, so don't emit them toward consumers that parse strictly.
  • JSON mode. It validates in JSON mode, whose coercion rules differ subtly from Python mode (e.g., bytes come from base64 strings, tuples arrive as lists) — usually what you want for wire data. 03.4 uses exactly this door for provider replies.

3.3 TypeAdapter — validating anything that isn't a model#

Model.model_validate only works for that model. TypeAdapter validates any type expression: a bare list[Ticket], a union, a primitive, a dict[str, list[int]]:

python
# type_adapter_demo.py — needs: pydantic
from typing import Union
from pydantic import BaseModel, TypeAdapter, ValidationError


class Ticket(BaseModel):
    id: str
    votes: int = 0


class Error(BaseModel):
    message: str


# Reuse these — building a TypeAdapter compiles a validator; don't build one per call.
tickets_adapter = TypeAdapter(list[Ticket])
result_adapter = TypeAdapter(Union[Ticket, Error])   # "smart" union: tries each, picks best fit
count_adapter = TypeAdapter(int)

print(tickets_adapter.validate_python([{"id": "a"}, {"id": "b", "votes": "4"}]))
print(result_adapter.validate_python({"message": "boom"}))
print(count_adapter.validate_json('"17"'))           # JSON mode: "17" -> 17

try:
    tickets_adapter.validate_python([{"id": "a"}, {"votes": 3}])
except ValidationError as e:
    print("loc:", e.errors()[0]["loc"])
Example output · illustrative4 lines
[Ticket(id='a', votes=0), Ticket(id='b', votes=4)]
message='boom'
17
loc: (1, 'id')

Use TypeAdapter when the shape isn't a single named model: webhook payloads that are "a list of events", provider responses that are "one of several shapes" (a smart union tries all members and picks the best match — see 4.5 for when a tagged union beats it), config values, CLI arguments. Reuse the adapter — each TypeAdapter(...) construction compiles validators, so build it once at module level (6.3).

3.4 Lax versus strict: coercion#

Pydantic's default lax mode coerces input it can safely convert. Strict mode accepts only the exact type. You can mix them per-field, per-model, or per-call.

The lax-mode coercion table (the cases that matter; the full matrix is in the docs' "Conversion Table"):

Field type Accepted in lax mode (examples) Rejected even in lax mode
str str, bytes (UTF-8), Enum members int, float, bool, None — v2 does not stringify numbers (a famous v1→v2 change)
int int, numeric strings "17", whole floats 17.0, bool→0/1 "17.5", 17.5, "abc", None
float float, int, numeric strings non-numeric strings
bool bool, 0/1, strings true/false/on/off/yes/no/y/n/t/f (any case) other strings, 2
list[T] list, tuple, set, frozenset, generators dict, str (a string is not a list of strings!)
dict[K,V] dict (keys/values validated too) list of pairs
datetime/date ISO 8601 strings, Unix timestamps (int/float) garbage strings, out-of-range
Decimal Decimal, int, numeric strings, float non-numeric
bytes bytes, UTF-8 str —
Literal[...]/Enum the exact values (strings coerce to enum values) anything else
model / nested mapping (dict) with the right keys wrong types, missing required keys

Two consequences worth memorising:

  1. str fields reject numbers. {"votes": 17} into a str field fails — 17 is not a string and v2 won't guess you wanted "17". This is safer (catches type confusion) but surprises people porting v1 code.
  2. bool is the slipperiest coercion. "false" → False, but the string "False" is truthy in plain Python — Pydantic parses it correctly, plain if payload["flag"]: does not. Always validate before branching on booleans.

Strict mode, three granularities:

python
# strict_demo.py — needs: pydantic
from typing import Annotated
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, ValidationError


class Loose(BaseModel):
    n: int


class StrictAll(BaseModel):
    model_config = ConfigDict(strict=True)
    n: int


class Mixed(BaseModel):
    a: StrictInt                                    # strict type, per-field
    b: int                                          # still lax
    c: Annotated[int, Field(strict=True)]           # strict via Field metadata


# Each class is probed only with payloads it can actually parse — the point is
# *which field* rejects the string, not how many errors a mismatched payload makes.
probes = [
    (Loose, {"n": "5"}),                            # lax: coerces "5" -> 5
    (Loose, {"n": 5}),
    (StrictAll, {"n": "5"}),                        # strict model: rejects
    (StrictAll, {"n": 5}),
    (Mixed, {"a": "5", "b": "5", "c": 5}),          # strict `a` rejects; lax `b` would coerce
    (Mixed, {"a": 5, "b": "5", "c": "5"}),          # strict `c` rejects; lax `b` coerced fine
    (Mixed, {"a": 5, "b": "5", "c": 5}),            # everything valid
]

for cls, payload in probes:
    try:
        m = cls.model_validate(payload)
        print(cls.__name__, payload, "-> OK", m.model_dump())
    except ValidationError as e:
        print(cls.__name__, payload, "-> ValidationError at", [err["loc"] for err in e.errors()])
Example output · illustrative7 lines
Loose {'n': '5'} -> OK {'n': 5}
Loose {'n': 5} -> OK {'n': 5}
StrictAll {'n': '5'} -> ValidationError at [('n',)]
StrictAll {'n': 5} -> OK {'n': 5}
Mixed {'a': '5', 'b': '5', 'c': 5} -> ValidationError at [('a',)]
Mixed {'a': 5, 'b': '5', 'c': '5'} -> ValidationError at [('c',)]
Mixed {'a': 5, 'b': '5', 'c': 5} -> OK {'a': 5, 'b': 5, 'c': 5}

When to be strict: money/IDs/enums crossing a trust boundary you control end-to-end (you know the producer sends real JSON types); internal APIs where "1" silently becoming 1 has burned you. When to stay lax: third-party APIs, form data, LLM output — the real world sends strings. Lax by default, strict where coercion lies. For LLM structured output the providers' strict modes constrain the schema, but your own validation still chooses its mode — 03.4 shows the interplay.

3.5 ValidationError anatomy#

Every failed validation raises pydantic.ValidationError (technically pydantic_core._pydantic_core.ValidationError, re-exported). It is not one error — it collects every problem it found, which is exactly what you want for reporting and for repair prompts.

python
# error_anatomy.py — needs: pydantic
import json
from typing import Literal
from pydantic import BaseModel, ValidationError


class Ticket(BaseModel):
    id: str
    votes: int = 0
    priority: Literal["low", "normal", "high", "urgent"] = "normal"


try:
    Ticket.model_validate({"id": 123, "votes": "many", "priority": "ASAP", "extra": 1})
except ValidationError as e:
    print("count:", e.error_count())
    print("--- errors() ---")
    for err in e.errors():
        print(json.dumps({k: err[k] for k in ("type", "loc", "msg", "input")}, default=str))
    print("--- str(e) ---")
    print(str(e))
    print("--- e.json() ---")
    print(e.json()[:120], "...")
Example output · illustrative18 lines
count: 3
--- errors() ---
{"type": "string_type", "loc": ["id"], "msg": "Input should be a valid string", "input": 123}
{"type": "int_parsing", "loc": ["votes"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "many"}
{"type": "literal_error", "loc": ["priority"], "msg": "Input should be 'low', 'normal', 'high' or 'urgent'", "input": "ASAP"}
--- str(e) ---
3 validation errors for Ticket
id
  Input should be a valid string [type=string_type, input_value=123, input_type=int]
    For further information visit https://errors.pydantic.dev/2.14/v/string_type
votes
  Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='many', input_type=str]
    For further information visit https://errors.pydantic.dev/2.14/v/int_parsing
priority
  Input should be 'low', 'normal', 'high' or 'urgent' [type=literal_error, input_value='ASAP', input_type=str]
    For further information visit https://errors.pydantic.dev/2.14/v/literal_error
--- e.json() ---
[{"type":"string_type","loc":["id"],"msg":"Input should be a valid string","input":123,"url":"https://errors.pydantic.dev/2.14/v/stri ...

Anatomy of one error dict:

Key Meaning
type Machine-readable code (missing, int_parsing, string_type, literal_error, value_error, extra_forbidden, your custom codes...)
loc Tuple path to the bad value: ("lines", 0, "price") — field names and list indices
msg Human-readable message
input The offending value (careful: may contain PII/secrets — see below)
url Link to docs for that error type (omit with include_url=False)
ctx Extra context (expected values, limits) when present

str(e) gives the pretty multi-line form FastAPI renders in its 422 responses; e.json() serialises the whole list for APIs and logs; e.errors() gives the dicts for programmatic use — each one an ErrorDetails TypedDict (type, loc, msg, input, url, optional ctx). Useful extras: e.error_count(), e.title (just the model name, 'Ticket' — str(e) composes the full N validation errors for Ticket header from it), e.errors(include_url=False, include_context=False, include_input=False).

From errors to a repair prompt. When an LLM produced the bad JSON, the highest-value thing you can send back is a specific, minimal description of what failed — not the whole model dump. A common pattern (used by 03.4 Part 7) is to render each error as one line: field 'votes': Input should be a valid integer (got 'many'), join them, and append "Fix the JSON and return only the corrected object." Because loc gives you nested paths and msg gives you the rule, the model gets an actionable diff instead of a wall of text. Keep the original (bad) payload out of the prompt if it contains sensitive data — the error lines alone are usually enough.


Part 4: Custom validation#

Built-in types and constraints cover most cases. When they don't — cross-field rules, normalisation, domain checks — you write validators. Pydantic gives you two decorator families (@field_validator, @model_validator) and four Annotated-friendly function wrappers (BeforeValidator, AfterValidator, PlainValidator, WrapValidator). They all do the same three jobs: check (raise on bad input), normalise (clean what you accept), and derive (compute what you store).

4.1 @field_validator and its four modes#

A field validator is a classmethod that receives the field's value and must return it (possibly changed). mode= decides when it runs:

Mode Runs Receives Use for
"after" (default) After Pydantic's own type/constraint checks The parsed value (correct type) Checks and normalisation on clean data — the safe default
"before" Before any parsing The raw input (Any) Pre-processing messy input (strip a "$" before Decimal parses it)
"wrap" Around the whole field validation (value, handler) — call handler(value) to continue Short-circuiting, caching, or wrapping errors
"plain" Instead of all other validation The raw input You take over the field completely (rare)
python
# field_validators.py — needs: pydantic
from pydantic import BaseModel, Field, ValidationError, ValidationInfo, field_validator


class TicketIn(BaseModel):
    title: str = Field(min_length=3, max_length=200)
    priority: str = "normal"
    tags: list[str] = Field(default_factory=list)

    @field_validator("title", "priority")          # one validator, several fields
    @classmethod
    def normalise_text(cls, value: str) -> str:
        return " ".join(value.split()).lower()      # collapse whitespace, lowercase

    @field_validator("priority", mode="after")
    @classmethod
    def check_priority(cls, value: str, info: ValidationInfo) -> str:
        allowed = {"low", "normal", "high", "urgent"}
        if value not in allowed:
            raise ValueError(f"priority must be one of {sorted(allowed)}, got {value!r}")
        return value

    @field_validator("tags", mode="before")
    @classmethod
    def split_tag_string(cls, value):               # raw input: could be a string or a list
        if isinstance(value, str):
            return [t.strip() for t in value.split(",") if t.strip()]
        return value


print(TicketIn(title="  Login   FAILS ", priority="HIGH",
               tags="auth, safari , billing").model_dump())
try:
    TicketIn(title="fine title", priority="ASAP")
except ValidationError as e:
    print(e.errors()[0]["msg"])
Example output · illustrative2 lines
{'title': 'login fails', 'priority': 'high', 'tags': ['auth', 'safari', 'billing']}
Value error, priority must be one of ['high', 'low', 'normal', 'urgent'], got 'asap'

(title="fine title" is long enough to pass min_length=3, so the priority error is the only one — and note got 'asap': normalise_text lowercased "ASAP" before check_priority saw it.) Validators on the same field run before validators first, then Pydantic's own type/constraint checks, then after validators in definition order — so normalise_text (defined first) cleaned the string before check_priority ran. That ordering is a feature: define your normaliser first, your checker second. (If order ever matters ambiguously, split them across before/after modes — before always precedes after.)

ValidationInfo (the optional third parameter, conventionally info) gives you .data (fields already validated — order matters, earlier fields only), .field_name, and .context (whatever you passed to model_validate(..., context=...) — 4.4).

4.2 @model_validator — rules that span fields#

Some rules can't live on one field: "end date after start date", "total must equal the sum of lines", "if kind=refund then amount must be negative". @model_validator sees the whole model:

python
# model_validators.py — needs: pydantic
from pydantic import BaseModel, ValidationError, model_validator


class PriceList(BaseModel):
    currency: str
    items: dict[str, float]
    total: float

    @model_validator(mode="after")
    def check_total(self):
        computed = round(sum(self.items.values()), 2)
        if abs(computed - self.total) > 0.01:
            raise ValueError(f"total {self.total} != sum of items {computed}")
        return self


class DateRange(BaseModel):
    start: str
    end: str

    @model_validator(mode="before")
    @classmethod
    def swap_if_reversed(cls, data):               # raw dict, before field parsing
        if isinstance(data, dict) and data.get("start") and data.get("end"):
            if str(data["end"]) < str(data["start"]):   # ISO dates compare as strings
                # return a fixed COPY: mutating `data` would change the caller's dict
                return {**data, "start": data["end"], "end": data["start"]}
        return data


ok = PriceList(currency="USD", items={"a": 1.5, "b": 2.25}, total=3.75)
print(ok.total)
try:
    PriceList(currency="USD", items={"a": 1.5}, total=9.99)
except ValidationError as e:
    print(e.errors()[0]["msg"])
print(DateRange(start="2026-12-01", end="2026-11-01"))   # silently corrected
Example output · illustrative3 lines
3.75
Value error, total 9.99 != sum of items 1.5
start='2026-11-01' end='2026-12-01'

Modes: mode="after" (default) receives the constructed self — all fields parsed, raise ValueError to fail; you may also return a modified self. mode="before" receives the raw input mapping — use it to fix or reject shapes Pydantic can't express (like the date swap). mode="wrap" wraps the whole validation with a handler. Prefer after: it runs on typed data, so your rule reads cleanly. Use before only when the fix must happen before field parsing (or the input might not be a dict at all — always isinstance check first).

4.3 Annotated validators — reusable rules without a class#

The decorator style lives on the model; the Annotated style attaches the same functions to a type, so you can reuse them anywhere — including inside TypeAdapter and other people's models:

python
# annotated_validators.py — needs: pydantic
from typing import Annotated
from pydantic import AfterValidator, BaseModel, BeforeValidator, PlainValidator, ValidationError


def lower_and_strip(value: str) -> str:
    return value.strip().lower()


def is_reasonable_age(value: int) -> int:
    if not 0 <= value <= 130:
        raise ValueError("age out of range")
    return value


def coerce_csv_to_list(value):                     # BeforeValidator sees raw input
    if isinstance(value, str):
        return [v.strip() for v in value.split(",") if v.strip()]
    return value


Slug = Annotated[str, AfterValidator(lower_and_strip)]
Age = Annotated[int, AfterValidator(is_reasonable_age)]
CsvList = Annotated[list[str], BeforeValidator(coerce_csv_to_list)]
StrictlyInt = Annotated[int, PlainValidator(lambda v: int(v))]   # terminates: no further checks


class Signup(BaseModel):
    username: Slug
    age: Age
    interests: CsvList


s = Signup(username="  Ada_Lovelace ", age="36", interests="math, poetry")
print(s.model_dump())
try:
    Signup(username="x", age=200, interests=[])
except ValidationError as e:
    for err in e.errors():
        print(".", err["loc"], "->", err["msg"])
Example output · illustrative2 lines
{'username': 'ada_lovelace', 'age': 36, 'interests': ['math', 'poetry']}
. ('age',) -> Value error, age out of range

(username="x" passed because Slug has no length constraint — add StringConstraints(min_length=3) to Slug if you want one; validators compose, they don't replace each other.)

Rules of thumb: AfterValidator for checks/normalisation on the parsed value (type-safe, preferred); BeforeValidator for fixing raw input; PlainValidator when you want total control and to skip Pydantic's own checks for that field (you then own coercion and constraints); WrapValidator for the rare wrap-and-continue case. The function must return the value; raising ValueError produces a value_error.

4.4 Errors, context and PydanticCustomError#

Inside any validator:

  • raise ValueError("msg") → error type="value_error", msg="Value error, msg". Simple, always works, and renders fine in 422s and repair prompts.
  • raise AssertionError also works but is meant for "this should never happen" invariants — don't use it for user-facing validation.
  • PydanticCustomError gives you a stable machine code and a templated message — the right choice when your API or frontend switches on error types:
python
# custom_error.py — needs: pydantic
from pydantic import BaseModel, ValidationError, ValidationInfo, field_validator
from pydantic_core import PydanticCustomError   # lives in pydantic_core, not pydantic —
                                              # a common stumble, since every other
                                              # name in this lesson comes from `pydantic`


class Order(BaseModel):
    sku: str
    qty: int

    @field_validator("qty")
    @classmethod
    def check_qty(cls, v: int, info: ValidationInfo) -> int:
        limit = (info.context or {}).get("max_qty", 100)
        if v > limit:
            raise PydanticCustomError(
                "qty_over_limit",
                "quantity {qty} exceeds the limit of {limit}",
                {"qty": v, "limit": limit},
            )
        return v


try:
    Order.model_validate({"sku": "A-1", "qty": 500}, context={"max_qty": 50})
except ValidationError as e:
    err = e.errors()[0]
    print(err["type"], "|", err["msg"], "|", err.get("ctx"))
Example output · illustrative1 line
qty_over_limit | quantity 500 exceeds the limit of 50 | {'qty': 500, 'limit': 50}

info.context is how you pass per-call configuration into validators: model_validate(data, context={...}), model_validate_json(json_str, context={...}), or TypeAdapter(...).validate_python(data, context={...}). Use it for things that vary per request — tenant limits, feature flags, the current user — instead of hard-coding or mutating the model. info.data holds the fields validated so far (fields are validated in definition order), which covers many "cross-field" needs without a model_validator.

4.5 Discriminated unions: tagged data#

Union[A, B] (smart union) tries each member and picks the best match — clever, but it can pick wrong when shapes overlap, and its errors are a wall of nested per-member failures. When your data has a tag field — "kind": "email" | "sms" | "push" — a discriminated union is faster, stricter and produces better errors:

python
# discriminated.py — needs: pydantic
from typing import Annotated, Literal, Union
from pydantic import BaseModel, Field, TypeAdapter, ValidationError


class EmailNotice(BaseModel):
    kind: Literal["email"]
    to: str
    subject: str


class SmsNotice(BaseModel):
    kind: Literal["sms"]
    to: str
    body: str


class PushNotice(BaseModel):
    kind: Literal["push"]
    to: str
    title: str
    deep_link: str | None = None


Notice = Annotated[Union[EmailNotice, SmsNotice, PushNotice], Field(discriminator="kind")]
adapter = TypeAdapter(Notice)

for payload in ({"kind": "sms", "to": "+1555", "body": "hi"},
                {"kind": "push", "to": "dev-1", "title": "Deploy done"},
                {"kind": "fax", "to": "123"}):
    try:
        n = adapter.validate_python(payload)
        print(type(n).__name__, "->", n.model_dump())
    except ValidationError as e:
        print("error:", e.errors()[0]["type"], "-", e.errors()[0]["msg"])
Example output · illustrative3 lines
SmsNotice -> {'kind': 'sms', 'to': '+1555', 'body': 'hi'}
PushNotice -> {'kind': 'push', 'to': 'dev-1', 'title': 'Deploy done', 'deep_link': None}
error: union_tag_invalid - Input tag 'fax' found using 'kind' does not match any of the expected tags: 'email', 'sms', 'push'

This is the shape of provider SDK unions: OpenAI Responses output items (message vs function_call vs reasoning), Anthropic content blocks (text vs tool_use vs thinking), and tool-call payloads are all discriminated unions under the hood (03.1 §8, 03.5). When you design tool outputs or multi-shape responses, use the same pattern — and note that Pydantic emits oneOf + discriminator in JSON Schema, which not every provider's grammar accepts (03.4 §2.6).

4.6 Recursive models, generics and forward references#

Three advanced shapes you'll meet in SDKs and bigger schemas:

  • Recursive models — a model containing itself: class Node(BaseModel): name: str; children: list["Node"] = []. The string "Node" is a forward reference resolved when the class is complete; usually automatic, but Node.model_rebuild() forces it (needed when the class is defined inside a function or references names not yet defined). For deeply recursive or self-referential schemas also know model_config = ConfigDict(defer_build=True).
  • Generics — class Page(BaseModel, Generic[T]): items: list[T]; total: int. Then IntPage = Page[int] validates items as ints. Providers' paginated responses are exactly this shape.
  • model_rebuild() — call it after defining a model whose annotations couldn't be resolved at class-creation (forward refs to classes defined later, TYPE_CHECKING imports). If you see PydanticUserError: ... is not fully defined, this is the fix.
python
# recursive_generic.py — needs: pydantic
from typing import Generic, TypeVar
from pydantic import BaseModel

T = TypeVar("T")


class TreeNode(BaseModel):
    name: str
    children: list["TreeNode"] = []


class Page(BaseModel, Generic[T]):
    items: list[T]
    total: int


IntPage = Page[int]
print(TreeNode.model_validate(
    {"name": "root", "children": [{"name": "leaf", "children": []}]}))
print(IntPage(items=[1, 2], total=2))
try:
    IntPage(items=[1, "x"], total=2)
except Exception as e:
    print("bad item rejected")
Example output · illustrative3 lines
name='root' children=[TreeNode(name='leaf', children=[])]
items=[1, 2] total=2
bad item rejected

4.7 @validate_call: validating a function's arguments#

Models guard data; the @validate_call decorator applies the same machinery to a plain function's arguments. The annotations (and any Field(...) or Annotated constraints) become the contract, the call is coerced in lax mode, and a bad call raises the same ValidationError you already know:

python
# validate_call_demo.py — needs: pydantic
from typing import Annotated

from pydantic import Field, ValidationError, validate_call


@validate_call
def top_up(account_id: str, amount: Annotated[float, Field(gt=0, le=10_000)], note: str = "") -> str:
    return f"{account_id}: +{amount:.2f} {note}".strip()


print(top_up("acc-1", "25.5"))             # "25.5" is coerced to the float 25.5
try:
    top_up("acc-1", -5)
except ValidationError as e:
    print(e.errors()[0]["msg"])
Example output · illustrative2 lines
acc-1: +25.50
Input should be greater than 0

Three facts to keep. The function body only ever sees coerced, checked values (amount is a real float inside it). Only the arguments are validated unless you ask for more: @validate_call(validate_return=True) also validates what the function returns. And the check runs on every call, so put it on boundary functions (an entry point, a tool handler), not on a hot inner loop. It works on async def functions too.

Why an AI engineer cares: the functions you expose to a model as tools are called with arguments the model wrote. Decorating the handler with @validate_call and calling it as handler(**arguments) turns a wrong type or a missing argument into a precise ValidationError, which you can render into the error message you send back to the model (3.5, 08A.6 §4.6). Generating the JSON Schema for the tool definition is a separate job, owned by 03.5 and 08A.6; a BaseModel of the arguments remains the better source of truth when the schema is the main product.


Part 5: Getting data out — serialisation and JSON Schema#

5.1 model_dump() and model_dump_json()#

Validation gets data in; serialisation gets it out — to a dict for a database, to a JSON string for an HTTP response, to a log line. The v2 methods (v1's .dict()/.json() are deprecated aliases):

python
# serialise_demo.py — needs: pydantic
from datetime import datetime, timezone
from decimal import Decimal
from pydantic import BaseModel, Field, SecretStr


class Ticket(BaseModel):
    id: str = Field(serialization_alias="ticketId")   # wire name differs; validation still uses `id`
    title: str
    votes: int = 0
    note: str | None = None
    token: SecretStr | None = None
    updated_at: datetime = Field(default_factory=lambda: datetime(2026, 11, 1, 12, 0, tzinfo=timezone.utc))
    price: Decimal = Decimal("9.99")


t = Ticket(id="T-1", title="Hi", token="sk-...", price=Decimal("19.99"))
print(t.model_dump())
print(t.model_dump(mode="json"))
print(t.model_dump(exclude_none=True, exclude={"token"}))
print(t.model_dump_json(exclude_unset=True))
print(t.model_dump(by_alias=True))   # `id` serialises as "ticketId" — see 2.5
Example output · illustrative5 lines
{'id': 'T-1', 'title': 'Hi', 'votes': 0, 'note': None, 'token': SecretStr('**********'), 'updated_at': datetime.datetime(2026, 11, 1, 12, 0, tzinfo=datetime.timezone.utc), 'price': Decimal('19.99')}
{'id': 'T-1', 'title': 'Hi', 'votes': 0, 'note': None, 'token': '**********', 'updated_at': '2026-11-01T12:00:00Z', 'price': '19.99'}
{'id': 'T-1', 'title': 'Hi', 'votes': 0, 'updated_at': datetime.datetime(2026, 11, 1, 12, 0, tzinfo=datetime.timezone.utc), 'price': Decimal('19.99')}
{"id":"T-1","title":"Hi","token":"**********","price":"19.99"}
{'ticketId': 'T-1', 'title': 'Hi', 'votes': 0, 'note': None, 'token': SecretStr('**********'), 'updated_at': datetime.datetime(2026, 11, 1, 12, 0, tzinfo=datetime.timezone.utc), 'price': Decimal('19.99')}

The mode argument is the key distinction:

  • mode="python" (default): Python objects stay Python objects — datetime stays datetime, Decimal stays Decimal, SecretStr stays masked; nested models become plain dicts but leaf values keep their Python types. Use for internal passing, ORMs, dataclasses.asdict-style flows.
  • mode="json": everything becomes JSON-safe — datetime→ISO string, Decimal→string (exactness preserved!), SecretStr→the masked ********** (still safe!), bytes→base64 string, Url→string, Enum→its value. model_dump_json() is model_dump(mode="json") + json.dumps in one step.

The filter arguments work in both modes: exclude, include (sets of field names or paths), exclude_none (drop Nones — smaller payloads), exclude_unset (only what the caller sent — perfect for PATCH responses and "echo back what changed"), exclude_defaults, by_alias (use alias names — needed when the consumer expects wire names), warnings control. Compose them: model_dump(mode="json", by_alias=True, exclude_none=True).

5.2 Serialisers and custom JSON types#

When a field's JSON form isn't the default — a datetime you want as "01/11/2026", a custom type, a computed representation — use @field_serializer (one field) or @model_serializer (the whole model, returning any JSON-able structure):

python
# serializers.py — needs: pydantic
from datetime import date
from typing import Any
from pydantic import BaseModel, field_serializer, model_serializer


class Report(BaseModel):
    title: str
    period_start: date
    period_end: date
    rows: int

    @field_serializer("period_start", "period_end")
    def fmt_date(self, v: date) -> str:
        return v.strftime("%d/%m/%Y")

    @model_serializer
    def slim(self) -> dict[str, Any]:                # takes over ALL serialisation
        return {"title": self.title, "rows": self.rows}


r = Report(title="Q3", period_start=date(2026, 7, 1), period_end=date(2026, 9, 30), rows=42)
print(r.model_dump(mode="json"))
print(r.model_dump_json())
Example output · illustrative2 lines
{'title': 'Q3', 'rows': 42}
{"title":"Q3","rows":42}

(model_serializer wins over field_serializer — it replaces the whole dump. If you want the field serializer to run, don't define a model serializer, or call handler(self) inside a mode="wrap" model serializer.) Serialisers affect model_dump/model_dump_json and the JSON Schema's declared format hints — but they do not change what model_validate accepts on the way in; that's validators' job. Keep the two directions symmetric or document the asymmetry.

5.3 model_json_schema() and the JSON Schema you send#

Model.model_json_schema() generates the JSON Schema document describing the model — the same document you could write by hand, produced from your Python class:

python
# schema_demo.py — needs: pydantic
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field


class TicketOut(BaseModel):
    model_config = ConfigDict(extra="forbid")   # "additionalProperties": false below

    id: str = Field(description="The ticket's public id, e.g. T-1042")
    title: str = Field(min_length=3, max_length=200, examples=["Login fails on Safari"])
    priority: Literal["low", "normal", "high", "urgent"] = "normal"
    resolved: bool = False
    assignee: str | None = Field(default=None, description="Agent username, or null if unassigned")


import json
print(json.dumps(TicketOut.model_json_schema(), indent=2))
Example output · illustrative13 lines
{
  "additionalProperties": false,
  "properties": {
    "id": {"description": "The ticket's public id, e.g. T-1042", "title": "Id", "type": "string"},
    "title": {"examples": ["Login fails on Safari"], "maxLength": 200, "minLength": 3, "title": "Title", "type": "string"},
    "priority": {"default": "normal", "enum": ["low", "normal", "high", "urgent"], "title": "Priority", "type": "string"},
    "resolved": {"default": false, "title": "Resolved", "type": "boolean"},
    "assignee": {"anyOf": [{"type": "string"}, {"type": "null"}], "default": null, "description": "Agent username, or null if unassigned", "title": "Assignee"}
  },
  "required": ["id", "title"],
  "title": "TicketOut",
  "type": "object"
}

Read it like a contract:

  • required lists only fields without defaults — id, title. priority, resolved, assignee are omittable. This is the JSON-Schema shadow of the required/optional/nullable trap from 2.2: a field that is str | None with no default would appear in required and allow null via anyOf — "must answer, may say null".
  • additionalProperties: false appears because the model sets extra="forbid" — Pydantic mirrors your extra policy into the schema, so the wire contract matches what your validator enforces. With the default "ignore", the schema says nothing about extra keys (providers' strict modes usually require false anyway — 03.4 covers that).
  • $defs/$ref — nested models and reused types are defined once under $defs and referenced by {"$ref": "#/$defs/LineItem"}. This is standard JSON Schema; providers' grammars handle it (within their subsets — 03.4 Part 4).
  • description, examples, title, minLength/maxLength, enum, anyOf, default — all flow from your Field(...) declarations straight into the schema the provider sees. This is why description is "prompt engineering" (08A.6 §1.4) and why 03.4 and 03.5 treat your Pydantic model as the source of truth for what the model must produce.

Provider caveat, briefly: each provider accepts only a subset of JSON Schema and transforms your schema before sending it (OpenAI strict mode requires every property in required with nullable anyOf for optionality; Anthropic moves numeric bounds into descriptions; Gemini ignores some keywords). 03.4 owns that comparison — your job here is to write good models; its job is to teach you what survives the wire.

5.4 RootModel — validating a bare list or scalar#

Sometimes the top-level JSON isn't an object: a webhook that's just [ {...}, {...} ], a model reply that's a bare string or number. RootModel wraps a single root value:

python
# root_model.py — needs: pydantic
from pydantic import RootModel, TypeAdapter


class TicketList(RootModel[list[dict]]):
    pass


class Score(RootModel[float]):
    pass


print(TicketList.model_validate([{"id": "a"}, {"id": "b"}]).root)
print(Score.model_validate_json("0.87").root)
# Or without a named class at all:
print(TypeAdapter(list[int]).validate_json("[1, 2, 3]"))
Example output · illustrative3 lines
[{'id': 'a'}, {'id': 'b'}]
0.87
[1, 2, 3]

RootModel matters for JSON Schema too: its schema describes the root shape (an array, a string) rather than an object with properties — which is what you send when the API expects a top-level array. For one-off shapes, TypeAdapter (3.3) does the same job without a class.


Part 6: Pydantic versus the alternatives — and the gotchas#

Deep-dive

6.1 BaseModel versus dataclass versus TypedDict versus pydantic.dataclasses#

You met dataclasses in 01A.6 and TypedDict in 01A.10. Here's the honest comparison:

dataclass TypedDict BaseModel pydantic.dataclasses
What it is A class with auto-generated __init__/__repr__/__eq__ A dict with known keys (typing only) A validated model class A stdlib dataclass + Pydantic validation
Runtime validation ❌ none ❌ none (it's still a dict) ✅ full ✅ full
Coercion ("3"→3) ❌ ❌ ✅ lax/strict ✅
JSON Schema generation ❌ (needs dataclasses-json etc.) ⚠️ partial via typing introspection ✅ model_json_schema() ✅ via TypeAdapter
Serialisation control manual (asdict, custom encoders) n/a (already a dict) ✅ model_dump* ✅ via TypeAdapter
Custom validators __post_init__ (manual) ❌ ✅ rich ✅ same as BaseModel
Speed fastest (pure Python) n/a fast (Rust core) fast
Best for Internal data you construct yourself JSON-shaped dicts you pass around opaquely Anything crossing a trust boundary When you need dataclass semantics + validation

Decision rule: data you create and control → dataclass; data that arrives as a dict and must be checked → BaseModel; data that's just a dict shape for typing → TypedDict; you need a dataclass but with validation → pydantic.dataclasses.dataclass. In AI work the answer is almost always BaseModel, because everything interesting — API responses, LLM output, tool args, config — crosses a boundary. (pydantic.dataclasses is the escape hatch when a library demands a real dataclass; validate a dict with TypeAdapter(YourDataclass).validate_python(data); the dataclass decorator itself also validates on construction.)

6.2 from_attributes and ORMs#

By default models validate mappings (dicts). ConfigDict(from_attributes=True) lets them validate objects by reading attributes — essential for ORM rows (SQLAlchemy/Django), dataclasses, namedtuples, SDK objects:

python
# from_attributes_demo.py — needs: pydantic
from dataclasses import dataclass
from pydantic import BaseModel, ConfigDict, Field


@dataclass
class DbRow:                       # stands in for an ORM row
    ticket_id: str
    votes: int


class TicketModel(BaseModel):
    model_config = ConfigDict(from_attributes=True)
    id: str = Field(validation_alias="ticket_id")   # or alias="ticket_id"
    votes: int


row = DbRow(ticket_id="T-1", votes=7)
t = TicketModel.model_validate(row)         # reads .ticket_id, .votes
print(t)
Example output · illustrative1 line
id='T-1' votes=7

from_attributes also enables populating from other models: TicketModel.model_validate(other_model) copies field-by-field through attributes — the standard way to map between layers (DB row → API schema → response schema) without dict round-trips. It's how FastAPI's response_model re-validates ORM objects.

6.3 Performance and the gotchas that bite#

Pydantic v2 is fast (Rust core), but production code still hits these:

  • model_construct() skips validation entirely — it builds an instance without checking anything. Legitimate uses: deserialising data you know is valid (a cache you wrote yourself), constructing defaults internally, performance-critical paths you've profiled. Dangerous: Model.model_construct(**untrusted_dict) gives you a "model" full of wrong types that will explode later, far from the cause. Never use it on external input. The docs themselves note validation is now fast enough that model_construct is rarely needed for speed.
  • Reuse TypeAdapters and compiled validators. TypeAdapter(X) and even Model.model_json_schema() compile machinery; build them once at module level, not per request.
  • Mutable defaults are safe but don't be clever. Pydantic deep-copies defaults per instance (unlike dataclasses' field(default_factory=...) requirement), so labels: list[str] = [] works — but default_factory is clearer and required for computed defaults anyway.
  • Optional without default is required in v2 — the 2.2 trap again; it breaks ported v1 code silently.
  • extra="forbid" for contracts. Already covered — the typo-hiding default.
  • Field ordering matters for info.data and model_validator(mode="before"). Fields validate in definition order; a validator can only see earlier fields via info.data. Put dependencies first.
  • frozen=True for value objects — immutability gives you hashing, safe sharing, and validate_assignment semantics for free.
  • Big lists cost linearly. Validating list[Model] over 10k items is fine but not free; for huge payloads validate once at the boundary and pass models, not re-validate per use. TypeAdapter(list[Model]) is the tool.
  • Datetime timezones: always store aware datetimes; comparing naive and aware raises TypeError. Parse with datetime.now(timezone.utc), never datetime.now().
  • float vs Decimal: money → Decimal; ML-ish scores → float is fine but know it's approximate. JSON Schema emits Decimal as string or number depending on config — check what providers accept (03.4 §2.8).
  • Circular models: model_rebuild() and defer_build (4.6) — infinite recursion in data is still your problem to bound.
  • Very large integers: JSON has arbitrary precision but many consumers (JS!) cap at 2^53. If your IDs exceed that, send them as strings.

6.4 Edge cases that bite#

A rapid-fire list of the small print:

  • bool coercion: "false"→False in lax, but plain-Python truthiness of the string "False" is True — validate before if.
  • str rejects numbers in v2 — {"code": 404} into str fails; coerce explicitly if you must.
  • Enum validation: Priority("urgent") works; "URGENT" fails unless your enum values are uppercase — match the wire format, not Python naming.
  • use_enum_values=True stores the raw value (a str), losing enum methods — convenient for JSON, surprising for isinstance checks.
  • model_copy(update=...) doesn't validate — internal use only.
  • model_fields on the class, not instance — instance access is deprecated.
  • Validators run on defaults too? By default validate_default=False: defaults are not validated unless you set it — so priority: Priority = "bogus" wouldn't be caught. Set validate_default=True in Field(...) or config when defaults matter.
  • frozen + validate_assignment: frozen models reject any assignment (the frozen_instance error you saw in 2.6); validate_assignment without frozen re-validates on set.
  • Union order: Union[int, str] in lax mode — Pydantic's "smart union" picks the best match, not the first; but exact-type matches win, so Union[bool, int] can surprise (True is an int too). When it matters, use Strict* types or a discriminated union.

The failures this lesson exists to prevent, as symptom → cause → fix:

Failure What you see Fix
Trusting dict shapes TypeError far from the cause; for c in ticket["tags"] iterates characters; votes + 1 explodes on "17" Validate once at the boundary into a model (1.1)
Optional confusion str | None with no default is required-but-nullable — {"text": "ok"} fails Field required on confidence = None for omittable; bare | None for "must answer, may say null" (2.2)
Silent coercion "17"→17, "false"→False — usually right, occasionally a bug ("007"→7, "yes"→True) Strict* types / strict=True where coercion lies (3.4)
extra="ignore" hiding typos {"titel": ..., "vote": 5} validates cleanly and the typos vanish extra="forbid" on contracts; "allow" + model_extra for forward-compat (2.6)
Validators with side effects A validator that logs/writes/calls an API fires on every model_validate — including SDK parses and model_copy Keep validators pure; do I/O after validation (4.2)
model_construct misuse Model.model_construct(votes="many") builds a "model" full of wrong types that explodes later, far from the cause Never on untrusted input — model_validate is fast enough (6.3)

Six of them, as they actually surface:

Trusting dict shapes — pure stdlib, run it:

python
ticket = {"id": "T-1", "tags": "urgent,billing", "votes": "17"}
print("tags iterated:", list(ticket["tags"])[:8], "...")
try:
    ticket["votes"] + 1
except TypeError as e:
    print("TypeError:", e)
Output · Python 3.14.6, stdlib only — deterministic2 lines
tags iterated: ['u', 'r', 'g', 'e', 'n', 't', ',', 'b'] ...
TypeError: can only concatenate str (not "int") to str

Optional confusion — str | None without a default is required:

python
# optional_confusion.py — needs: pydantic
from pydantic import BaseModel, ValidationError


class Reply(BaseModel):
    text: str
    confidence: float | None          # required-but-nullable: the key must be sent


try:
    Reply.model_validate({"text": "ok"})
except ValidationError as e:
    print(str(e))
Example output · illustrative4 lines
1 validation error for Reply
confidence
  Field required [type=missing, input_value={'text': 'ok'}, input_type=dict]
    For further information visit https://errors.pydantic.dev/2.14/v/missing

Silent coercion — lax mode at work:

python
# silent_coercion.py — needs: pydantic
from pydantic import BaseModel


class M(BaseModel):
    votes: int
    flag: bool


m = M.model_validate({"votes": "17", "flag": "false"})
print(m.model_dump())
Example output · illustrative1 line
{'votes': 17, 'flag': False}

"17" became 17 and "false" became False — usually what you want, but the same laxness turns "007" into 7 and "yes" into True. Where the distinction matters (IDs, enum-like codes, money), tighten with strict mode (3.4).

extra="ignore" hiding typos — the default drops unknown keys silently:

python
# extra_ignore.py — needs: pydantic
from pydantic import BaseModel


class T(BaseModel):
    title: str
    votes: int = 0


t = T.model_validate({"titel": "Refund", "title": "Refund", "vote": 5})
print(t.model_dump(), "| extras:", t.model_extra)
Example output · illustrative1 line
{'title': 'Refund', 'votes': 0} | extras: None

titel and vote (typos for title and votes) vanished without a trace — extra="forbid" would have failed loudly on both.

Validators with side effects — they run on every validation:

python
# validator_side_effects.py — needs: pydantic
from pydantic import BaseModel, field_validator

calls = []


class W(BaseModel):
    x: int

    @field_validator("x")
    @classmethod
    def track(cls, v):
        calls.append(v)                  # side effect: fires on EVERY validation
        return v


W.model_validate({"x": 1})
W.model_validate({"x": 2})
print("validator ran", len(calls), "times:", calls)
Example output · illustrative1 line
validator ran 2 times: [1, 2]

And it would also fire inside model_copy, FastAPI request handling and SDK response parsing — a validator that did I/O would turn every parse into a network call. Keep them pure; do side effects after validation (4.2).

model_construct misuse — skips validation entirely:

python
# model_construct_misuse.py — needs: pydantic
from pydantic import BaseModel


class C(BaseModel):
    votes: int


bad = C.model_construct(votes="many")       # no validation: "many" stored as-is
print("constructed:", bad)
try:
    bad.votes + 1
except TypeError as e:
    print("TypeError later:", e)
Example output · illustrative2 lines
constructed: votes='many'
TypeError later: can only concatenate str (not "int") to str

The "model" holds a str where an int was promised — the failure surfaces far from the cause, in unrelated code. model_construct is for data you know is valid (a cache you wrote yourself); everything external goes through model_validate.


Part 7: Pydantic inside the AI stack#

7.1 SDK response objects are Pydantic models#

Every major provider SDK builds its response objects with Pydantic — openai's Response, anthropic's Message, google-genai's response types are all BaseModel subclasses (03.1 §8.3 shows them). That means everything in this lesson applies directly:

  • response.model_dump() / .model_dump_json() — turn the SDK object into plain dicts/JSON for storage, logging or re-validation. exclude_none=True drops the sparse fields providers omit. Some SDKs also expose .to_dict() convenience methods on their objects — verify per SDK before relying on one; model_dump() is the documented Pydantic way.
  • response.model_extra — fields the server sent that the SDK doesn't declare are kept here rather than rejected. This is deliberate forward-compatibility: a provider can add usage.cost_details before the SDK knows about it, and getattr-style access still works ((resp.usage.model_extra or {}).get("cost") — 03.1 §6.7). It also means SDK objects tolerate unknown fields — the opposite of extra="forbid" — because they sit on the receiving side of a contract the provider owns.
  • Model.model_validate(data) — build an SDK object from a dict: exactly how 03.1 §8.4 constructs fake responses for tests, and how you rehydrate stored responses.
  • Your own models interoperate — pass response.output_parsed (already a Pydantic model when you use structured output) straight into your code; or validate response.model_dump() against your stricter model when the SDK's is lenient.

The mental model to keep: the SDK's models describe what the provider might send (lenient, extra-tolerant); your models describe what your code requires (strict, contract-shaped). Both are Pydantic; they just sit on opposite sides of the trust boundary.

7.2 Validating LLM-shaped output without an LLM#

Structured-output features (03.4) constrain the model at decode time — but you still validate, because (a) not every provider/path supports it, (b) "schema-valid" isn't "correct", and (c) prompt-plus-parse (rung 1 of 03.4) is still common. Here is the complete, provider-agnostic pipeline: extract → parse → validate → repair.

Step 1, extraction. An LLM reply is prose around JSON: fences, preamble, trailing commentary. json.JSONDecoder().raw_decode parses one JSON value starting at a position and reports where it ended — so scanning for {/[ and trying each opener finds every top-level object or array, immune to braces inside strings:

python
# s7_2_extract_json.py — STDLIB ONLY, run it: python3 s7_2_extract_json.py
import json
from collections.abc import Iterator

_decoder = json.JSONDecoder()


def iter_json_values(text: str) -> Iterator[object]:
    """Yield each top-level JSON object or array in `text`, left to right."""
    pos = 0
    while True:
        starts = [i for i in (text.find("{", pos), text.find("[", pos)) if i != -1]
        if not starts:
            return
        pos = min(starts)
        try:
            value, end = _decoder.raw_decode(text, pos)
        except json.JSONDecodeError:
            pos += 1                       # not JSON from here: try the next opener
            continue
        if isinstance(value, (dict, list)):
            yield value
        pos = end                         # skip past this value entirely


def extract_json(text: str) -> object | None:
    """Return the first top-level JSON object or array in `text`, or None."""
    return next(iter_json_values(text), None)


REPLIES = {
    "clean": '{"name": "Priya", "age": 29}',
    "fenced": 'Sure! Here you go:\n```json\n{"name": "Tom", "age": 41}\n```\nHope that helps!',
    "prose after": '{"name": "Ana", "age": 35}\nLet me know {if you need more}.',
    "brace in string": 'Result: {"name": "Kenji {KJ}", "age": 52} done',
    "two objects": 'First try: {"name": "Fatima"} Corrected: {"name": "Fatima", "age": 23}',
    "array": 'Here are the people: [{"name": "A"}, {"name": "B"}] — done',
    "single quotes": "{'name': 'Lukas', 'age': 38}",
    "truncated": '{"name": "Lukas", "age": 3',
    "empty": "I cannot help with that.",
}

for label, reply in REPLIES.items():
    print(f"{label:14} -> {extract_json(reply)!r}")
Output · Python 3.14.6, stdlib only — deterministic9 lines
clean          -> {'name': 'Priya', 'age': 29}
fenced         -> {'name': 'Tom', 'age': 41}
prose after    -> {'name': 'Ana', 'age': 35}
brace in string -> {'name': 'Kenji {KJ}', 'age': 52}
two objects    -> {'name': 'Fatima'}
array          -> [{'name': 'A'}, {'name': 'B'}]
single quotes  -> None
truncated      -> None
empty          -> None

Read the rows: fences and trailing prose are skipped, a } inside a string doesn't end the object early, the first of two objects wins (for "first try / corrected" replies you'd iterate iter_json_values and keep the first that validates — 03.4 §1.2 does exactly that), and single-quoted/truncated/non-JSON replies correctly return None — never "repaired" by guessing.

Step 2, validate. Feed the extracted object to your model — model_validate for a dict, model_validate_json if you kept the raw substring:

python
# validate_reply.py — needs: pydantic (uses extract_json from s7_2_extract_json.py)
from pydantic import BaseModel, ValidationError
from s7_2_extract_json import iter_json_values


class Person(BaseModel):
    name: str
    age: int


def parse_person_reply(text: str) -> Person:
    """First JSON object in `text` that validates as Person."""
    for value in iter_json_values(text):
        try:
            return Person.model_validate(value)
        except ValidationError:
            continue
    raise ValueError("no valid Person JSON found in reply")


for reply in ('{"name": "Priya", "age": 29}',
              '{"name": "Fatima"} {"name": "Fatima", "age": 23}',
              'Sorry, {"name": "Bo"} is not enough info'):
    try:
        print(parse_person_reply(reply))
    except ValueError as e:
        print("ValueError:", e)
Example output · illustrative3 lines
name='Priya' age=29
name='Fatima' age=23
ValueError: no valid Person JSON found in reply

Step 3, repair. On ValidationError, render the errors (3.5) into a follow-up prompt — "these fields failed: ... return corrected JSON only" — and retry bounded times. That loop is 03.4 Part 7's job; your part is producing clean errors and clean input. 04.8 uses the same extract-then-validate shape for document extraction patterns.

7.3 Partial and streaming validation#

When a model streams JSON (03.3), you may want to validate the prefix before the reply finishes — to show partial results or abort early. Two Pydantic features exist, both worth knowing and neither to build production logic on casually:

  • pydantic_core.from_json(text, allow_partial=True) (since v2.7): parses the valid prefix of incomplete JSON into Python objects — '{"a": 1, "b": [1,2' → {"a": 1, "b": [1, 2]}. It's a parser feature, not validation.
  • TypeAdapter(...).validate_json(text, experimental_allow_partial=True) (since v2.10, experimental): validates and parses incomplete input — pass experimental_allow_partial="trailing-strings" to also accept a half-typed final string. The docs warn it "should be considered a proof of concept" with limitations (fields without defaults complicate it; check the current docs before relying on it).

The production-safe pattern for streamed structured output is the one 03.3 §6.3 teaches: accumulate the text, parse settled fields conservatively, and run full validation only on the completed reply. Use experimental_allow_partial for previews and prototyping; validate the final string with model_validate_json before trusting anything.

7.4 The aitoolkit/models.py deliverable#

Here is the module's shared models file — the shapes every later lesson (01B.5's HTTP client, 01B.7's FastAPI service, 01B.8's tests, 01B.10's packaging) builds on. It defines the fake ticket API's records and the fake backend's request/response:

python
# src/aitoolkit/models.py — needs: pydantic
"""Shared Pydantic models for the aitoolkit examples.

These are the contracts used across Module 01B: the fake ticket API
(01B.5), the FastAPI service (01B.7) and the fake LLM backend (01B.3).
Keep field names stable — later lessons import these exact models.
"""
from datetime import datetime
from enum import Enum
from typing import Literal

from pydantic import AliasChoices, BaseModel, ConfigDict, Field


class Priority(str, Enum):
    LOW = "low"
    NORMAL = "normal"
    HIGH = "high"
    URGENT = "urgent"


class Status(str, Enum):
    OPEN = "open"
    IN_PROGRESS = "in_progress"
    RESOLVED = "resolved"
    CLOSED = "closed"


class Ticket(BaseModel):
    """A ticket as returned by the fake ticket API (read side)."""

    model_config = ConfigDict(extra="forbid")

    id: int | str = 0      # the API uses ints; tests also build "T-1042"-style ids — 0 = unassigned
    subject: str = Field(validation_alias=AliasChoices("subject", "title"),
                         description="One-line summary of the problem")
    description: str = ""
    priority: Priority = Priority.NORMAL
    status: Status = Status.OPEN
    requester: str | None = None        # the API fills it from the caller's key
    tags: list[str] = Field(default_factory=list, max_length=10)
    votes: int = Field(default=0, ge=0)
    created_at: datetime | None = None
    updated_at: datetime | None = None


class TicketIn(BaseModel):
    """The shape a client POSTs to create a ticket (write side).

    Separate from Ticket: no id/status/votes — the server assigns those.
    extra="forbid" so a typo'd key fails loudly instead of vanishing.
    """

    model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)

    subject: str = Field(validation_alias=AliasChoices("subject", "title"),
                        min_length=3, max_length=200)
    description: str = Field(default="", max_length=10_000)
    priority: Priority = Priority.NORMAL
    requester: str | None = Field(default=None, max_length=120)
    tags: list[str] = Field(default_factory=list, max_length=10)


class CompletionRequest(BaseModel):
    """Request body for the fake backend's /complete endpoint."""

    model_config = ConfigDict(extra="forbid")

    prompt: str = Field(min_length=1, max_length=32_000)
    model: str = "fake-tiny"             # model name is config, not validated against a list
    max_tokens: int = Field(default=256, ge=1, le=8_192)
    temperature: float = Field(default=1.0, ge=0.0, le=2.0)


class Usage(BaseModel):
    """Token accounting — same field names as the backend's dataclass (01B.3)."""

    input_tokens: int = Field(default=0, ge=0)
    output_tokens: int = Field(default=0, ge=0)

    @property
    def total_tokens(self) -> int:
        return self.input_tokens + self.output_tokens


class Completion(BaseModel):
    """Response body for /complete: one canned completion from ScriptedBackend.

    The backend's own dataclass (01B.3) is the internal shape; this is the
    wire shape service.py maps onto — `text` is the reply string.
    """

    model_config = ConfigDict(extra="forbid")

    text: str                              # the canned reply text
    model: str = "fake-tiny"
    usage: Usage = Field(default_factory=Usage)
    finish_reason: Literal["stop", "length"] = "stop"

Design notes worth copying:

  • Ticket vs TicketIn — read and write shapes differ (server-assigned fields aren't client input). This input/output-model split is the same discipline FastAPI's response_model enforces in 01B.7 and that APIs use everywhere.
  • subject with a title alias, and int | str ids — the fake ticket API's wire format calls the field subject and uses integer ids ({"id": 42, "subject": "Cannot log in", ...}), while tests and fixtures spell it title and use "T-1042"-style strings. AliasChoices("subject", "title") accepts both spellings on the way in; int | str accepts both id shapes. Aliases and unions are how you evolve a contract without breaking callers — the same tools §2.5 and §4.5 teach.
  • extra="forbid" on all of them — these are contracts; a typo must fail loudly.
  • Usage.total_tokens as a plain @property — it's derived, not a field, so it stays out of the schema and validation. (Use @computed_field instead if you want it serialised — 2.9.)
  • Completion.text matches ScriptedBackend.complete() — the backend's own dataclass (01B.3) is the internal shape; this Pydantic model is the wire shape service.py maps onto. Two representations of the same data at different layers is normal — internal code stays stdlib-simple, the boundary stays validated.
  • Literal["stop", "length"] for finish_reason — closed sets as Literal, matching how providers report termination (03.1).
  • No secrets, no I/O in validators — models here are pure data; behaviour lives in service.py/http.py.

Common misconceptions#

Misconception Reality
"Type hints validate my data." Hints are erased at run time; def f(x: int) accepts "abc". Only Pydantic (or manual checks) enforces types at run time.
"Optional[str] means the field can be omitted." In v2, str | None with no default is required but nullable — the key must be present, may be null. Add = None to make it omittable (2.2).
"Pydantic only checks types." It coerces ("17"→17), constrains (lengths, ranges, patterns), normalises and derives — types are just the start.
"Lax mode means sloppy." Lax is the right default for real-world input; strict mode is for boundaries you control end-to-end. The danger isn't lax — it's unnoticed coercion of values where "1" and 1 mean different things.
"extra keys are always ignored." Only with the default extra="ignore". "forbid" errors on them; "allow" keeps them in model_extra. Choose per contract.
"model_dump() gives me JSON." It gives Python objects (datetime, Decimal, models→dicts). mode="json" or model_dump_json() gives JSON-safe values.
"Validators can do anything." They must be pure — no I/O, no side effects. They run on every validation, including inside SDK parsing and FastAPI.
"model_construct is a fast model_validate." It skips validation entirely — a loaded gun for untrusted input. Use it only for data you know is valid.
"A schema-valid LLM reply is correct." Validation guarantees shape, not truth. A model can return perfectly-typed nonsense — semantic checks and business rules are separate layers (12.5).
"Pydantic v1 and v2 code are interchangeable." Validators, .dict()/.json(), Optional defaults and several coercion rules all changed. Check pydantic.__version__ and the migration guide before copying old snippets.
"I need json.loads before model_validate_json." Never — model_validate_json parses and validates in one Rust pass, faster, with positioned json_invalid errors for malformed input.

Key takeaways#

  • Validate once, at the boundary. Every external source — APIs, users, files, LLM output — is untyped and untrusted. A BaseModel turns "hope the shape is right" into "guaranteed or a precise error".
  • Type hints document; Pydantic enforces. The same annotation syntax becomes a runtime contract — that is why every SDK, FastAPI and structured-output feature is built on it.
  • Three doors, pick by input: Model(**data)/model_validate for mappings, model_validate_json/model_validate_strings for JSON/text payloads, TypeAdapter for non-model shapes (lists, unions, primitives). Reuse adapters — they compile validators.
  • Required ≠ optional ≠ nullable. X required; X | None required-but-nullable; X | None = None omittable-and-nullable; X = default omittable. This drives JSON Schema required/anyOf and provider strict modes.
  • Lax coerces, strict doesn't. Know the coercion table — especially that v2 str rejects numbers and lax bool parses "false" correctly where plain Python wouldn't.
  • ValidationError is a report, not a failure. errors() gives type/loc/msg/input per problem — render it for 422s, logs, or an LLM repair prompt. Beware input leaking secrets/PII.
  • Validators check, normalise, derive — purely. field_validator (before/after/wrap/plain), model_validator (before/after/wrap), Annotated + AfterValidator/BeforeValidator/PlainValidator/WrapValidator. Raise ValueError or PydanticCustomError; pass per-call config via context.
  • Discriminated unions beat smart unions for tagged data — the shape provider SDKs use for tool calls and content blocks.
  • Serialise deliberately: model_dump(mode="json") for wire-safe output, exclude_none/exclude_unset/by_alias to shape payloads, model_json_schema() to emit the contract providers enforce.
  • Pydantic sits everywhere in the AI stack: SDK response objects (lenient, model_extra), your own contracts (strict, extra="forbid"), structured-output schemas, tool arguments, settings, metadata records, eval cases, judge outputs, guardrail checks.
  • For LLM output you parse yourself: extract with raw_decode (run for real in 7.2), validate with your model, feed errors back bounded times — the extract→validate→repair loop.

Where you'll use this in the AI path#

Later lesson What it takes from this one
03.1 §8.3-8.4 SDK response objects are Pydantic models — model_dump, model_extra, model_validate for tests
03.4 Your BaseModel becomes the JSON Schema providers constrain decoding to; §2.4 is this lesson's 2.2 trap applied; Part 6 is validation in layers; Part 7 is the repair loop
03.5 Tool parameters schemas come from Pydantic models; arguments are validated against them (Part 2)
03.3 §6.3 Partial/streamed JSON validation — the cautious version of 7.3
04.8 Extraction patterns that end in schema-validated output
05.8 Chunk/document metadata as validated models — the mirror image of validating LLM output
08A.6 Tool-argument validation and injection safety; §1.7 on strict schemas
10A.2 The eval-case schema is a Pydantic model
10A.4 Judge outputs parsed and validated tolerantly
12.5 Output guardrails: structural validation is the first wall
01B.2 / 01B.7 pydantic-settings builds on BaseModel; FastAPI request/response validation and its 422 bodies are ValidationError rendered

Terms introduced in this lesson#

Term Meaning
Validation Checking untrusted input against a declared shape and producing typed objects or precise errors — Pydantic's core job.
Coercion Converting a value to the expected type ("17"→17); happens in lax mode before constraint checks.
Lax mode Pydantic's default: safe conversions accepted (numeric strings→numbers, ISO strings→dates).
Strict mode Validation that accepts only exact types; per-field (StrictInt), per-model (strict=True) or per-call.
BaseModel The class you subclass to define a validated model; fields are annotated attributes.
model_validate / model_validate_json / model_validate_strings The three doors: Python mapping, JSON text, (potentially nested) dict of strings, validated in JSON mode — same validation, different input modes.
TypeAdapter Validates any type expression (list[Ticket], unions, primitives); reuse instances — they compile validators.
Field(...) Per-field metadata: constraints (ge, min_length, pattern), default/default_factory, description, examples, aliases.
ConfigDict / model_config Class-level options: extra, frozen, strict, str_strip_whitespace, validate_assignment, from_attributes, use_enum_values, validate_by_name/validate_by_alias (the older populate_by_name spelling is still seen).
Required / optional / nullable The three-way field contract: must-be-present, may-be-absent, may-be-null — distinct in v2.
default_factory Callable producing a fresh default per instance (for mutable or computed defaults).
Alias A different name for a field on the wire: alias, validation_alias, serialization_alias, validate_by_name.
@field_validator Decorator for per-field checks/normalisation; modes before/after/wrap/plain.
@model_validator Decorator for cross-field rules; modes before (raw data) and after (parsed model).
Annotated validators AfterValidator/BeforeValidator/PlainValidator/WrapValidator — reusable rules attached to a type.
ValidationInfo Validator context object: .data (earlier fields), .field_name, .context (per-call config).
PydanticCustomError Raising a validation error with a stable code and templated message.
@validate_call Decorator that validates (and coerces) a function's arguments against its annotations, raising ValidationError; validate_return=True also checks the result.
ValidationError The exception collecting all failures; errors() → type/loc/msg/input/url/ctx.
Discriminated union Union[...] + Field(discriminator="kind") — variants told apart by a tag field.
Smart union Pydantic's default union behaviour: tries members, picks best match — vs a tagged union's explicit dispatch.
model_dump / model_dump_json Serialisation to dict/JSON; mode, exclude*, include, by_alias control the shape.
model_json_schema() Generates the JSON Schema document for a model — the contract sent to providers.
RootModel A model whose entire content is one root value (bare list, scalar) — for non-object JSON.
SecretStr A string wrapper that masks itself in repr/str/model_dump; unwrap via get_secret_value().
EmailStr Email-validated string; requires the pydantic[email] extra (email-validator).
model_extra Dict of undeclared keys kept when extra="allow" — how SDKs tolerate new provider fields.
from_attributes Config letting models validate objects by attribute (ORM rows, dataclasses, other models).
computed_field A property serialised like a field (derived values in dumps and schema).
Partial validation Experimental experimental_allow_partial on TypeAdapter.validate_* — validates incomplete JSON prefixes (v2.10+, proof of concept).

All terms are also collected in the glossary.


Exercises#

Work through these in order — they build the aitoolkit/models.py habits into muscle memory. Solutions assume Pydantic 2.14 unless noted.

  1. The three-way trap (2.2): Write a class Range(BaseModel) with low: float, high: float | None (no default), and note: str | None = None. Predict which of {"low": 1}, {"low": 1, "high": None}, and {"low": 1, "note": "x"} validate. Check with model_json_schema() — which keys are in required?
  2. Coercion audit (3.4): For a model class M(BaseModel): s: str; i: int; b: bool, predict the result of M(s="x", i="3.0", b="off"), then M(s=42, i=3, b=True). Which fails and why? Fix the second call so it validates without changing the model.
  3. Strict boundaries (3.4): Add model_config = ConfigDict(strict=True) to the TicketIn model from 2.4. Which of these now fail that passed before: votes="17", score=0.8, tags=["ab"]? Explain which strict rule each hits.
  4. Validator ordering (4.1): In TicketIn, swap the definition order of normalise_text and check_priority. Does priority="HIGH" still validate? Explain the ordering rule, then make the behaviour order-independent.
  5. Cross-field rule (4.2): Add a model_validator(mode="after") to a Trip(BaseModel) with depart: str, arrive: str that raises ValueError when arrive <= depart. Write the test payload that triggers it and the errors()[0]["msg"] you'd see.
  6. Discriminated union (4.5): Define class Refund(BaseModel): kind: Literal["refund"]; amount: float and class Charge(BaseModel): kind: Literal["charge"]; amount: float; method: str. Build TypeAdapter(Annotated[Union[Refund, Charge], Field(discriminator="kind")]) and validate {"kind": "refund", "amount": -5} — what type do you get? What does {"kind": "refund", "amount": 5, "method": "card"} produce (hint: extra policy)?
  7. JSON Schema reading (5.3): Generate TicketOut.model_json_schema() from 5.3. Without running it, predict: is assignee in required? Does priority have an enum? What does anyOf on assignee contain? Then run it and compare.
  8. Serialisation shape (5.1): Given t = Ticket(id="T-1", title="Hi", note=None), predict t.model_dump(exclude_none=True) versus t.model_dump_json(exclude_unset=True). Which drops note? Which drops votes if it was defaulted? Explain exclude_unset vs exclude_none vs exclude_defaults.
  9. extract_json for real (7.2): The script s7_2_extract_json.py is stdlib-only — run it (python3 s7_2_extract_json.py). Then add a reply 'Sure! {"name": "X"} and also {"name": "Y", "age": 1}' and predict extract_json's output before running. Why does it return the first object?
  10. Build the deliverable (7.4): Write src/aitoolkit/models.py from 7.4 (or import it). Add a TicketUpdate(BaseModel) for PATCH semantics: every field optional except keep extra="forbid". Which fields can be None vs absent? Validate {"title": "New title"} and {"votes": -1} — predict the errors.
  11. SDK interop (7.1): A provider response dict has {"id": "r1", "usage": {"input_tokens": 10, "output_tokens": 5, "cost": 0.001}}. Validate usage against aitoolkit.models.Usage — does cost survive? Where does it land? Now validate the whole thing against a model with extra="forbid" — what breaks?
  12. Repair prompt (3.5, 7.2): Take the ValidationError from TicketIn.model_validate({"title": "hi", "priority": "ASAP", "votes": -1, "score": 2.0, "tags": ["Bad!"], "ref": "x"}). Write a function format_errors(e) -> str that renders one line per error as field 'path': message (got input). Paste your function's output for that payload (label it illustrative if you can't run Pydantic).
  13. Validating a tool handler (4.7): Decorate def refund(order_id: str, amount: float) -> str with @validate_call and call it as refund(**{"order_id": "SO-1", "amount": "12.5"}) and as refund(**{"order_id": "SO-1"}). What does the function see in the first call? What is the type of the error in the second, and how would you turn it into a message for the model?
Solutions
  1. {"low": 1} fails (high is required-but-nullable — must be present). {"low": 1, "high": None} validates. {"low": 1, "note": "x"} fails (high missing). In the schema, required is ["low", "high"]; high has anyOf [number, null]; note is not required.
  2. M(s="x", i="3.0", b="off") validates cleanly — lax int parses the numeric string "3.0", sees a zero fractional part and stores 3; b="off" becomes False. What actually fails is a fractional value: i="3.5" or i=3.5 raises int_parsing/int_from_float. M(s=42, i=3, b=True) fails: v2 str rejects ints (string_type). Fix the second call by passing s="42".
  3. Only votes="17" fails: strict mode refuses to turn the string "17" into an int (int_type). score=0.8 is already a float and tags=["ab"] is already a list[str], so both still pass (use tags=["ab"], not ["a"]: a one-character tag already fails the Slug minimum length of 2 with or without strict mode). Strict mode bans coercion, not valid values; even a strict float field still accepts an int such as score=1, because the docs' conversion table lists int-to-float as allowed in strict mode.
  4. Yes — check_priority sees "HIGH" before normalise_text lowercases it, so it raises. Make it order-independent by putting normalisation in mode="before" (always runs first) or merging both checks into one validator.
  5. Trip(depart="2026-12-01", arrive="2026-11-01") raises; e.errors()[0]["msg"] is "Value error, arrive date must be after depart date" (or your message). loc is () — model-level errors have an empty location tuple.
  6. You get a Refund instance (tag dispatch picks the class directly). {"kind": "refund", ..., "method": "card"} — method is an extra key; with default extra="ignore" it's silently dropped. Set extra="forbid" on both variants if you want it rejected.
  7. assignee is not in required (it has = None). priority has "enum": ["low","normal","high","urgent"]. assignee's anyOf is [{"type": "string"}, {"type": "null"}] plus "default": null.
  8. t.model_dump(exclude_none=True) drops note (its value is None) and keeps votes=0. t.model_dump_json(exclude_unset=True) keeps note — it was passed explicitly, even though it is None — but drops votes, which the caller never passed. exclude_defaults would drop both note and votes, because each equals its default, even if explicitly set. Use exclude_unset for PATCH echoes ("what the caller sent"), exclude_none for compact payloads, exclude_defaults for "only what differs from the default".
  9. Run it: all nine rows print as shown in 7.2. extract_json returns {'name': 'X'} — raw_decode succeeds at the first { and pos = end skips past the whole first object, so the second is never considered. To get the validating one, iterate iter_json_values and try Person.model_validate on each (that's what parse_person_reply does).
  10. TicketUpdate fields all X | None = None-style but omittable: title: str | None = None, etc. — except keep non-nullable types where None is meaningless. {"title": "New title"} validates. {"votes": -1} fails ge=0 if you kept the constraint. {"unknown": 1} fails extra="forbid".
  11. Usage.model_validate({"input_tokens": 10, "output_tokens": 5, "cost": 0.001}) succeeds — cost is ignored (default) or kept in model_extra (with extra="allow"). Against extra="forbid" the whole validation fails with Extra inputs are not permitted at loc ('cost',) — which is why SDK models use "allow"-style tolerance and your contracts use "forbid".
  12. python
    def format_errors(e: ValidationError) -> str:
        lines = []
        for err in e.errors(include_url=False):
            loc = ".".join(str(p) for p in err["loc"]) or "(model)"
            lines.append(f"field '{loc}': {err['msg']} (got {err['input']!r})")
        return "\n".join(lines)
    Output for that payload (illustrative — error types/messages as in 3.5):
    text
    field 'title': String should have at least 3 characters (got 'hi')
    field 'priority': String should match pattern '^(low|normal|high|urgent)$' (got 'ASAP')
    field 'votes': Input should be greater than or equal to 0 (got -1)
    field 'score': Input should be less than or equal to 1 (got 2.0)
    field 'tags.0': String should match pattern ... (got 'Bad!')
    field 'ref': String should have at least 4 characters (got 'x')
  13. First call: amount arrives as the float 12.5 (lax coercion from the string). Second call: a ValidationError whose single error has type missing_argument and the message Missing required argument, with the argument named in loc. Render it with the same format_errors idea as exercise 12 (field 'amount': Missing required argument) and send that line back to the model as the tool result, so it can retry with a complete argument set.

Check yourself#

  1. Why can't a type hint like def f(x: int) protect you from bad data at run time?
  2. What are the three field states (required / optional / nullable) and how do you write each in Pydantic v2?
  3. What's the difference between model_validate and model_validate_json, and when is the latter the better door for a JSON payload?
  4. In lax mode, what happens to "17" for an int field, 17 for a str field, and "false" for a bool field?
  5. What does extra="forbid" do, why is it the right default for API contracts, and when is "ignore" or "allow" kinder?
  6. Name the four @field_validator modes and what each receives.
  7. What's the difference between @model_validator(mode="before") and mode="after", and which should you prefer?
  8. How do you make a union "discriminated", and why is it better than a smart union for tagged data like {"kind": "email"} vs {"kind": "sms"}?
  9. What's in a ValidationError.errors() dict, and why is loc the most useful field?
  10. How do model_dump(mode="python") and model_dump(mode="json") differ for a datetime and a Decimal field?
  11. What is model_extra, and why do provider SDKs tolerate unknown fields while your own models shouldn't?
  12. What are the two Pydantic features for partial JSON validation, and why does the lesson recommend validating the completed reply instead?
  13. Why must validators be free of side effects, and where should I/O happen instead?
  14. Your TicketIn model has tags: list[str] = Field(default_factory=list). Why default_factory and not = []? (Pydantic would actually survive = [] — so what's the real reason?)
  15. A colleague validates an LLM reply with json.loads(text[text.find("{"):text.rfind("}")+1]). Name two ways it breaks that extract_json + model_validate handles.

Further resources#

  • Pydantic docs (the authoritative reference; check your installed version's docs match — pydantic.__version__):
    • Models — BaseModel, the model_* API, validation modes
    • Fields — Field(), constraints, the Annotated pattern
    • Validators — every validator mode and ValidationInfo
    • Types — the full type catalogue (EmailStr, URLs, SecretStr, Decimal...)
    • JSON Schema — model_json_schema(), $defs/$ref, schema modes
    • Strict mode and the conversion table — lax vs strict per type
    • JSON — model_validate_json, pydantic_core.from_json, partial parsing
    • Experimental features — experimental_allow_partial
    • Dataclasses and Configuration — ConfigDict reference
    • V1 docs and the V1→V2 migration guide in the docs — for porting legacy code
  • PyPI: pydantic — current version, changelog, optional extras (pydantic[email])
  • JSON Schema — the specification your model_json_schema() output implements
  • annotated-types (PyPI) — the Ge/Le/Len/Predicate constraint helpers used with Annotated

← 01B.5 — HTTP Clients with httpx | Module 01B overview | 01B.7 — FastAPI Basics: Building a Small API →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close