Pydantic Schema Validation
Define your output as a Pydantic BaseModel, validate the JSON, and catch malformed responses early.
Pydantic Schema Validation is a free AI Agents lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Agents learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Pydantic?
Pydantic is the de-facto type-safety library for Python. It:
- Validates dicts against type-annotated classes
- Coerces or rejects on mismatch
- Auto-generates JSON Schema for the OpenAI API
- Plays nicely with FastAPI, LangChain, LlamaIndex
Defining a Schema
from pydantic import BaseModel, Field
class Product(BaseModel):
name: str
price: float = Field(gt=0, description='Positive price in USD')
in_stock: bool
tags: list[str] = []Validating a Dict
data = {'name': 'Mug', 'price': 9.99, 'in_stock': True, 'tags': ['kitchen']}
product = Product.model_validate(data)
print(product.price) # 9.99Validating JSON
json_str = '{"name":"Mug","price":9.99,"in_stock":true}'
product = Product.model_validate_json(json_str)Validation Errors
from pydantic import ValidationError
try:
Product.model_validate({'name': 'Mug', 'price': -1, 'in_stock': True})
except ValidationError as e:
print(e)
# [{'type': 'greater_than', 'loc': ('price',), 'msg': 'Input should be greater than 0', ...}]Field-Level Validators
from pydantic import field_validator
class User(BaseModel):
email: str
@field_validator('email')
@classmethod
def must_have_at(cls, v):
if '@' not in v:
raise ValueError('Invalid email')
return v.lower()Nested Models
class Address(BaseModel):
city: str
zip: str
class User(BaseModel):
name: str
address: Address
data = {'name': 'Alice', 'address': {'city': 'Berlin', 'zip': '10115'}}
user = User.model_validate(data)
print(user.address.city)Generating JSON Schema
schema = Product.model_json_schema()
# Pass straight to OpenAI tools or response_formatUsing With OpenAI SDK
from openai import OpenAI
client = OpenAI()
response = client.beta.chat.completions.parse(
model='gpt-4o-2024-08-06',
messages=[{'role': 'user', 'content': 'Give me a product.'}],
response_format=Product
)
product = response.choices[0].message.parsedOptional Fields
from typing import Optional
class Order(BaseModel):
id: int
note: Optional[str] = NoneDefaults
class Settings(BaseModel):
units: str = 'celsius'
notify: bool = TrueAliases
For mapping JSON snake_case to Python camelCase or vice versa:
class User(BaseModel):
user_id: int = Field(alias='userId')
u = User.model_validate({'userId': 42})
print(u.user_id) # 42Discriminated Unions
For polymorphic types, use Pydantic's discriminated union:
from typing import Literal, Union
from pydantic import Field
class TextMessage(BaseModel):
type: Literal['text']
content: str
class ImageMessage(BaseModel):
type: Literal['image']
url: str
Message = Annotated[Union[TextMessage, ImageMessage], Field(discriminator='type')]Validation Goal
Why use Pydantic on every tool output?
Recap
Pydantic is the contract layer between LLM outputs, tool outputs, and your code. Use it everywhere; combine with structured outputs for guaranteed validity.
Frequently asked questions
Is the “Pydantic Schema Validation” lesson free?
Yes — the full text of “Pydantic Schema Validation” is free to read here on the web, and the AI Agents course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Agents course, upgrade to CoddyKit PRO.
What will I learn in “Pydantic Schema Validation”?
Define your output as a Pydantic BaseModel, validate the JSON, and catch malformed responses early. You practise AI Agents with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start AI Agents?
No prior experience is required. AI Agents on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Pydantic Schema Validation” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this AI Agents lesson?
Yes. Every AI Agents lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.