Schema Generation for Prompts
You'll learn: How to automatically generate JSON schemas from your Pydantic models and embed them directly in prompts so the LLM knows exactly what output structure you expect.
Why Generate Schemas?
You've already defined beautiful Pydantic models with types, constraints, and validators. Now you need to tell the LLM what format to follow. Rather than manually writing out schema descriptions, you can extract the JSON schema directly from your Pydantic model and include it in your prompt.
How It Works
Pydantic models have a built-in method called .model_json_schema() that generates a complete JSON Schema representation of your model. This schema describes every field, its type, whether it's required, any constraints, and nested structures.
from pydantic import BaseModel, Field
class MovieReview(BaseModel):
title: str = Field(description="Movie title")
rating: int = Field(ge=1, le=5, description="Rating from 1-5")
summary: str
# Generate the schema
schema = MovieReview.model_json_schema()
# Returns a dictionary with all type information, constraints, and descriptions
You can then convert this schema to a string and inject it into your system prompt:
import json
schema_str = json.dumps(schema, indent=2)
prompt = f"Extract movie review information. Return JSON matching this schema:\n{schema_str}"
The Benefit
The LLM receives precise, machine-readable specifications. It knows rating must be an integer between 1 and 5, title is required, and the exact nesting structure. This dramatically reduces format errors.
Key Takeaway: Use .model_json_schema() to automatically generate JSON schemas from Pydantic models and embed them in prompts, ensuring the LLM understands your exact output requirements without manual documentation.