Pydantic validation

LLMs return unstructured text, but your application needs structured data. Pydantic validation enforces type safety on LLM outputs. If the model returns invalid data (wrong types, missing fields, out-of-range values), validation catches it before it reaches your application logic.

LLM output validation loop

How Pydantic validates LLM output and retries on failure

patterns/22_pydantic_validation.py
python
from pydantic import BaseModel, field_validator

class UserProfile(BaseModel):
    name: str
    email: str
    age: int
    interests: list[str]

    @field_validator("email")
    @classmethod
    def validate_email(cls, v):
        if "@" not in v:
            raise ValueError("Invalid email format")
        return v

    @field_validator("age")
    @classmethod
    def validate_age(cls, v):
        if not 0 <= v <= 120:
            raise ValueError("Age must be between 0 and 120")
        return v

class ValidationAgent:
    def generate_structured_response(self, prompt):
        response = self.llm.generate(prompt).content
        try:
            parsed = json.loads(response)
            validated = UserProfile(**parsed)
            return validated
        except (json.JSONDecodeError, ValidationError) as e:
            # Retry or fallback
            return self._handle_validation_error(e, prompt)

Define Pydantic models with validators and use them to validate LLM output.

Fill in the blanks: Complete the Pydantic model

Loading practice…

Quiz: Quiz

Loading practice…

Matching exercise: Match Pydantic concepts

Loading practice…

Flashcards: Flashcards

Loading practice…

Manual JSON parsing gives you a dict with no guarantees. Pydantic gives you typed objects with automatic validation, default values, and clear error messages when the AI returns something unexpected. It catches bad data before it causes problems downstream.

You now know how to validate AI outputs with Pydantic models. That wraps up safety, quality, and validation patterns.

Checkpoint: Safety & quality checkpoint

Loading practice…