Pydantic Schema Validation
Define your output as a Pydantic BaseModel, validate the JSON, and catch malformed responses early.
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] = []