Debug Fix easy · 3 min read

Fix Instructor validation error

Quick answer
The Instructor validation error occurs when the response_model parameter is missing or incorrectly specified in the client.chat.completions.create call. Fix it by defining a Pydantic model and passing it explicitly as response_model=YourModel to ensure proper structured output parsing.
ERROR TYPE code_error
⚡ QUICK FIX
Define a Pydantic model and pass it as response_model=YourModel in the client.chat.completions.create call to fix validation errors.

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.

python
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
output
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.
Verified 2026-04 · gpt-4o-mini
Verify ↗