Pydantic validation

Pydantic is Python's most popular data validation library. You define a model (a class) that describes the shape of your data, and Pydantic enforces it. If the AI returns a phone number where an email should be, Pydantic catches it instantly.

Quiz: Quiz

Loading practice…

Pydantic validation gate

How Pydantic validates raw LLM output into typed data

Optional[str] means the field can be a string or None (missing). It comes from Python's typing module. When the AI extracts data, some fields might not be present, and Optional lets Pydantic accept None for those fields instead of raising an error.

03-structured-outputs.ipynb
python
from pydantic import BaseModel
from typing import Optional

class Contact(BaseModel):
    name: str
    email: str
    phone: Optional[str] = None  # Can be missing
    company: Optional[str] = None
    city: Optional[str] = None

# Extract from AI and validate in one step
contact_data = extract_json(prompt, temperature=0.3)
contact = Contact(**contact_data)  # Pydantic validates!

print(contact.name)     # "Sarah Chen"
print(contact.email)    # "[email protected]"
print(contact.phone)    # "(415) 555-0123" or None

Contact(**data) validates every field. If "email" is missing or not a string, Pydantic raises a ValidationError immediately.

Flashcards: Flashcards

Loading practice…

03-structured-outputs.ipynb
python
class Product(BaseModel):
    product_name: str
    quantity: int
    price: float

class Order(BaseModel):
    products: list[Product]
    total: float

order_text = """
I'd like to order:
- 2 Buddha Bowls at $12.99 each
- 1 Green Smoothie for $6.50
- 3 Avocado Toasts at $9.99 each
"""

prompt = f"Extract order as JSON: {order_text}"
order_data = extract_json(prompt)
order = Order(**order_data)

# Verify AI's math!
calculated = sum(p.quantity * p.price for p in order.products)
print(f"AI total: ${order.total}")
print(f"Verified: ${calculated:.2f}")

Nested Pydantic models: Order contains a list of Products. Always verify AI calculations against your own math.

Always verify AI calculations. AI models are language models, not calculators. They can make arithmetic errors. In the example above, we independently calculated the total and compared it to the AI's answer. For financial data, this is critical.

Fill in the blanks: Complete the Pydantic model

Loading practice…

You now know how to define Pydantic models for type-safe AI outputs. Next, we will tackle complex nested structures like resumes and invoices with models inside models.