Search⌘ K
AI Features

Validating with Pydantic

Explore how to apply Pydantic models to validate and enforce structured AI output within backend services. Understand defining field types, constraints, enums for fixed categories, and defaults to eliminate manual checks. Gain skills to catch invalid responses early and maintain robust downstream processing.

The previous lesson ended with a specific failure: a dictionary that parsed successfully but contained an invalid type in a field that downstream code depended on. We could keep writing manual if checks for every field, type, and allowed value, but that quickly becomes difficult to maintain, and individual validation checks can be missed as the schema grows. Pydantic provides a cleaner way to handle this validation: define the expected fields, types, and constraints in a model, then validate incoming data against those rules instead of scattering manual checks throughout the codebase.

A Pydantic model is a written contract, enforced automatically

Let's define the exact shape we want the model's output to match: the same severity and reason fields from the last two lessons, but this time as a real, enforced schema instead of a plain dictionary we hope is correct.

Python
from pydantic import BaseModel, Field, ValidationError
class SeverityAssessment(BaseModel):
severity: int = Field(ge=1, le=5)
reason: str
raw_json = '{"severity": 4, "reason": "Affects checkout for many users."}'
assessment = SeverityAssessment.model_validate_json(raw_json)
print("Parsed and validated:", assessment)
print("Type of severity:", type(assessment.severity).__name__)
  • Lines 4–6: SeverityAssessment is a class, not a dictionary shape described in a comment, severity and reason are declared with real Python types, and Field(ge=1, le=5) adds a constraint directly onto severity: it must be an integer greater than or equal to 1 and less than or equal to ...