Sub topic 3
Defining the schema as Pydantic models
This chapter assumes you know basic Python classes and exceptions, can read JSON, and have read the previous chapter on JSON Schema. You will define the shape of your output once, as a Python class, and use that class for two jobs: describing the shape to the model and checking the model's reply.
Why define the schema in code
Writing JSON Schema by hand works, but it creates a second copy of your data shape. Your program also needs that shape: field names, types, and allowed values. Two copies drift apart, and then the schema sent to the model no longer matches the code that reads the reply.
Pydantic is a Python library that builds validated classes from type hints. A class that inherits from BaseModel gives you three things:
- A JSON Schema, from
model_json_schema(). - Parsing and validation of JSON text, from
model_validate_json(). - A typed Python object, so later code can write
ticket.priorityinstead ofdata["priority"].
The examples use Pydantic v2.
A first model
import json
from typing import Literal
from pydantic import BaseModel, Field
class TicketTriage(BaseModel):
category: Literal["billing", "bug", "feature_request", "other"]
priority: int = Field(ge=1, le=3, description="1 is most urgent, 3 is least urgent")
summary: str = Field(max_length=200, description="One-sentence summary of the ticket")
print(json.dumps(TicketTriage.model_json_schema(), indent=2))Each part of the class maps to a part of the schema:
| Python | JSON Schema effect |
|---|---|
| `Literal[...]` | An `enum` of the allowed strings |
| `int` | `"type": "integer"` |
| `ge=1, le=3` | `minimum` and `maximum` |
| `max_length=200` | `maxLength` |
| `description=...` | `description`, which the model can read |
| No default value | The field appears in `required` |
Validating a reply
model_validate_json parses the text and checks every rule in one step. It raises ValidationError if the text is not JSON or does not fit the model.
from pydantic import ValidationError
bad = '{"category": "refund", "priority": 5, "summary": "Charged twice"}'
try:
TicketTriage.model_validate_json(bad)
except ValidationError as err:
for problem in err.errors():
print(problem["loc"], problem["type"])This prints ('category',) literal_error and ('priority',) less_than_equal. Each error names the failing field and the rule it broke. A later chapter feeds this information back to the model in a retry loop.
Extra fields
By default Pydantic ignores fields it does not know. If the model returns an extra "confidence": 0.9, validation passes and the field is silently dropped. The hand-written schema from the previous chapter used additionalProperties: false to forbid extras. You can get the same effect with ConfigDict:
from pydantic import ConfigDict
class StrictTicketTriage(TicketTriage):
model_config = ConfigDict(extra="forbid")Use extra="forbid" when a surprise field means something went wrong. Some providers' schema-constrained modes also require additionalProperties: false, and this setting produces it.
Nested models and lists
Real outputs often contain lists or sub-objects. Compose models the same way you compose types:
class ActionItem(BaseModel):
owner: str
task: str
class MeetingNotes(BaseModel):
title: str
action_items: list[ActionItem]The schema for MeetingNotes places ActionItem under $defs and refers to it with $ref. Most providers accept this, but the next chapters on constrained decoding explain where support for such features varies.
Common mistakes
- Using
dictorAnyfor the whole output. This tells the model nothing and lets anything pass validation. Name the fields. - Giving fields defaults to be "safe". A field with a default is not listed as required. The model may then leave it out, and your code silently gets the default. Make a field required unless a missing value is genuinely acceptable.
- Skipping descriptions. The model reads them.
priority: intis ambiguous, while "1 is most urgent" is not. - Relying on bounds the provider ignores. Some constrained-decoding modes drop
minimum,maximum, andmaxLengthfrom the schema. Keep the limits in the model anyway, because validation on your side still enforces them.
Exercise
A model reply is {"category": "bug", "priority": 2, "summary": "Crash on login", "severity": "high"}. With the plain TicketTriage class this validates, but with extra="forbid" it fails. Why does the first case pass, and why might you prefer the second?
Show answer
By default Pydantic ignores fields it does not define, so severity is dropped without any error. With extra="forbid" the unexpected field raises a ValidationError. You may prefer that because an unexpected field often means the model misread the schema or your prompt, and silent dropping hides the problem.