Fix Instructor validation error
code_error Why this happens
The Instructor library requires a Pydantic BaseModel to validate and parse the AI response. If you omit the response_model parameter or pass an incorrect type, the validation fails, causing errors like ValidationError or unexpected attribute errors.
Typical broken code example:
from openai import OpenAI
from pydantic import BaseModel
import instructor
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
class User(BaseModel):
name: str
age: int
# Missing response_model parameter
user = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Extract: John is 30 years old"}]
)
print(user.name, user.age) # AttributeError or validation error
The fix
Define a Pydantic model for the expected response structure and pass it explicitly as response_model in the client.chat.completions.create call. This enables Instructor to parse and validate the response correctly.
import os
from openai import OpenAI
import instructor
from pydantic import BaseModel
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
class User(BaseModel):
name: str
age: int
user = client.chat.completions.create(
model="gpt-4o-mini",
response_model=User,
messages=[{"role": "user", "content": "Extract: John is 30 years old"}]
)
print(user.name, user.age) # Output: John 30 John 30
Preventing it in production
Always define explicit Pydantic models for structured extraction tasks and pass them as response_model to client.chat.completions.create. Implement validation error handling and retries to catch malformed responses. Use unit tests with sample prompts to verify model parsing before deployment.
Key Takeaways
- Always use a Pydantic model with response_model for structured extraction in Instructor.
- Pass response_model=YourModel explicitly in client.chat.completions.create calls.
- Validate and test your Pydantic models to prevent runtime validation errors.