Sub topic 3
Defining the schema as Pydantic models
This chapter assumes you know Python classes, type hints, and exceptions, and that you have read the previous chapter on JSON Schema. You should also be able to call an LLM API. Pydantic v2 and Python 3.10 or newer are assumed. Install it with pip install pydantic.
Why define the schema in code
The last chapter described the shape you want as a JSON Schema document. You could keep that document as a string and validate replies with a generic library. That leaves you with two artifacts to keep in sync: the schema you send to the model and the Python objects your program uses.
Pydantic removes the duplication. You write one class. From it you get:
- a JSON Schema to send to the provider or paste into a prompt
- a validator that checks the model's reply
- a typed Python object, so your editor and type checker know that
ticket.priorityis anint
The class is the single source of truth. When you add a field, the prompt schema, the validation, and the object all change together.
A first model
Here is the ticket-triage model from the tutorial's running example.
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(TicketTriage.model_json_schema())Each construct maps to a JSON Schema keyword:
Literal[...]becomes anenum.ge=1, le=3becomesminimumandmaximum.max_length=200becomesmaxLength.descriptionis copied through. Models read it, so it works as an instruction.
The printed result is a dictionary with type: object, a properties entry per field, and required listing all three fields. Pydantic also adds title keys. They are harmless, and you can ignore them or strip them if a provider complains.
To send the schema as text, serialize it with json.dumps(TicketTriage.model_json_schema(), indent=2).
How Python types map to schema
Knowing the mapping lets you predict what the model sees.
| Python / Pydantic | JSON Schema result | Note | Column |
|---|---|---|---|
| `str`, `int`, `float`, `bool` | `string`, `integer`, `number`, `boolean` | Basic types | |
| `Literal["a", "b"]` | `enum: ["a", "b"]` | Best way to limit choices | |
| `Field(ge=1, le=3)` | `minimum`, `maximum` | Some providers ignore or reject these | |
| `Field(max_length=200)` | `maxLength` | Same caveat | |
| `list[Item]` | `array` with `items` | Add `min_length` or `max_length` to bound it | |
| A nested model | `$defs` plus `$ref` | Some providers want references inlined | |
| `str \ | None` | `anyOf` with `null` | Still required if it has no default |
| A field with a default | Removed from `required` | Strict modes often need every field required | |
| `ConfigDict(extra="forbid")` | `additionalProperties: false` | Rejects unknown keys |
Which keywords a provider enforces during generation varies, and the list changes over time. Check your provider's documentation. The next chapters on schema-constrained outputs cover this in detail. Here the rule is simple: Pydantic can express more than a provider may accept, so keep a validation step on your side no matter what.
Building a realistic model
Real extraction tasks need nested objects, lists, and optional values. This version extends the triage model.
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field, field_validator
class Entity(BaseModel):
"""A person, company, or product named in the ticket."""
model_config = ConfigDict(extra="forbid")
name: str = Field(description="Name exactly as written in the ticket")
kind: Literal["person", "company", "product"]
class TicketTriage(BaseModel):
"""Structured triage result for one support ticket."""
model_config = ConfigDict(extra="forbid")
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")
customer_email: str | None = Field(
description="Email address in the ticket, or null if none is present"
)
entities: list[Entity] = Field(
max_length=10, description="Named entities in the ticket, empty list if none"
)
@field_validator("summary")
@classmethod
def summary_not_blank(cls, value: str) -> str:
value = value.strip()
if not value:
raise ValueError("summary must not be blank")
return valueSeveral choices in this model are deliberate.
extra="forbid". By default Pydantic silently ignores unknown keys. For model output you usually want the opposite. An extra key often means the model misread the schema, and you want to see that. The setting also adds additionalProperties: false to the schema, which strict provider modes commonly require.
str | None with no default. customer_email is required but may be null. The model must make an explicit decision for every field. If you wrote = None, the field would drop out of required, and some providers' strict modes would reject the schema. A model that may skip a field also tends to skip it too often.
Descriptions on every field. The description of customer_email says what null means. Without it, one model returns null and another returns an empty string.
Docstrings. Pydantic puts the class docstring into the schema as the object's description. Treat it as prompt text.
field_validator. The validator runs when you validate the reply. It does not appear in the JSON Schema, because arbitrary Python cannot be expressed in the schema. The model never sees this rule and the provider cannot enforce it. Use validators for checks that run only on your side, and move rules that the model should know about into the types or descriptions.
Validating a reply
Pydantic v2 has two entry points. model_validate_json(text) takes the raw JSON string and parses and validates in one step. model_validate(data) takes an already-parsed dictionary. With model output, prefer the JSON version. It reports malformed JSON as a ValidationError too, so you handle one exception type for both problems.
from pydantic import ValidationError
raw = '{"category": "refund", "priority": 5, "summary": "Charged twice"}'
try:
ticket = TicketTriage.model_validate_json(raw)
except ValidationError as err:
for problem in err.errors():
print(problem["loc"], problem["type"], problem["msg"])This prints one line for each invalid field, such as the category value that is not in the enum and the priority that is above 3. The missing customer_email and entities keys are reported too. Each entry in err.errors() carries a loc (the path to the field), a type (a stable machine-readable code), and a msg (readable text). str(err) gives the full formatted report. The retry chapter feeds that text back to the model.
On success you get a TicketTriage instance. Use ticket.priority directly, and ticket.model_dump() to get a plain dictionary for storage or logging.
Lax and strict mode
Pydantic coerces by default. The JSON "2" is accepted for an int field and becomes 2. That is called lax mode. It is usually helpful, because models sometimes quote numbers. It can also hide a model that is drifting from the schema. To refuse coercion, set ConfigDict(strict=True) on the model, or pass strict=True to model_validate_json. Choose one policy deliberately and note it in your code. If you coerce, log how often it happens.
Keeping the schema model-friendly
A Pydantic class is also a prompt. These habits make the generated schema work better for the model.
- Name fields for meaning.
prioritywith a description beatsp. The model reads the names. - Prefer
Literalor anEnumover free strings whenever the set of values is closed. With anEnum, Pydantic puts the values in$defs. ALiteralstays inline, which is simpler for providers that dislike references. - Bound lists and strings with
max_lengthso a runaway reply fails validation instead of filling your database. - Keep nesting shallow. Deeply nested or recursive models are harder for the model to fill in and harder for providers to constrain.
- Do not mix concerns. Keep this class for the model's output. Your database model or API response may need different fields, such as IDs and timestamps that the model should never produce.
A later chapter covers schema design in more depth. This list is enough to start.
Common errors
Passing the class instead of the schema. APIs expect a dictionary or JSON string. Call model_json_schema(), or use the provider SDK's helper that accepts a Pydantic class. Some SDKs do accept the class directly, so check yours.
Assuming the provider enforced your limits. If le=3 is silently dropped by a provider, the model can return 5. Only your own model_validate_json call guarantees the limit.
Forgetting required semantics. A field with a default is optional in the schema. A model may then omit it, and you get the default without noticing.
Using Pydantic v1 names. In older code you will see .schema(), .parse_raw(), and @validator. In v2 these are model_json_schema(), model_validate_json(), and @field_validator. The old names still exist in v2 but are deprecated.
Validating a code-fenced reply. If the model wraps its JSON in a Markdown fence, model_validate_json fails on the backticks. That is a prompting issue, covered in the next chapters.
Summary
- One Pydantic class gives you the schema, the validator, and a typed object.
Literal,Fieldlimits, anddescriptionbecome schema keywords. Validators stay on your side.- Use
extra="forbid"and avoid defaults when you want every field filled in explicitly. - Validate with
model_validate_json, and handleValidationErroras a normal outcome.
Exercise
A teammate adds urgency: str = "normal" to a Pydantic model used for LLM output, and @field_validator("urgency") that rejects any value other than "low", "normal", or "high". Two problems appear: the model often omits the field, and it sometimes returns "medium". Name the cause of each problem and describe one change that fixes both.
Show answer
The field is omitted because a field with a default is not in required in the generated schema, so the model may skip it. The model returns "medium" because the validator's allowed values are not in the schema, so the model never sees them. Both are fixed by changing the field to urgency: Literal["low", "normal", "high"] = Field(description="...") with no default. The Literal puts an enum in the schema, and the missing default makes the field required.
Exercise
Using the extended TicketTriage model, what does TicketTriage.model_validate_json('{"category": "bug", "priority": "2", "summary": "App crashes", "customer_email": null, "entities": []}') return in default (lax) mode, and what changes if the model uses ConfigDict(strict=True)?
Show answer
In lax mode it returns a valid TicketTriage with priority equal to the integer 2, because the string "2" is coerced. With strict=True it raises a ValidationError for priority, because a string is not accepted for an int field.