Pydantic to OpenAI Strict Mode
Pydantic is the most popular Python library for data validation. Learn how to convert Pydantic models to OpenAI Structured Outputs compatible JSON Schema.
Why Pydantic for OpenAI?
Pydantic provides a clean, Pythonic way to define data structures. When working with OpenAI's Structured Outputs, you can:
- Define response schemas using familiar Python type hints
- Validate AI responses automatically
- Get IDE autocomplete and type checking
- Use
model_json_schema()to generate JSON Schema
The Strict Mode Challenge
However, Pydantic's default model_json_schema() output is NOT compatible with OpenAI's strict mode because it lacks:
❌ Missing additionalProperties
Pydantic doesn't add additionalProperties: false by default.
❌ Optional Required Arrays
Properties with default values are not included in the required array.
Solution: ConfigDict
Use Pydantic v2's ConfigDict with extra='forbid' to enforce strict mode:
from pydantic import BaseModel, ConfigDict
class MyResponse(BaseModel):
model_config = ConfigDict(extra='forbid')
name: str
age: int
active: boolUsing with OpenAI SDK
from openai import OpenAI
from pydantic import BaseModel, ConfigDict
class UserInfo(BaseModel):
model_config = ConfigDict(extra='forbid')
name: str
email: str
age: int
client = OpenAI()
response = client.chat.completions.create(
model="gpt-4o-2024-08-06",
messages=[{"role": "user", "content": "..."}],
response_format={
"type": "json_schema",
"json_schema": {
"name": "UserInfo",
"strict": True,
"schema": UserInfo.model_json_schema()
}
}
)Generate Pydantic Models
Our tool can generate Pydantic models from JSON samples automatically.
Try the Generator →