Validated Structured Output with Instructor and Pydantic
You ask a model to pull a name, an age and a job title out of a paragraph. It returns JSON, mostly. Then one day the age is the string "thirty", or a required field is missing, and the KeyError shows up three functions away from the call that caused it. Asking nicely for JSON isn't a contract.
Instructor turns the contract into a Pydantic model. You pass the class you want back, Instructor gets the model to fill it, Pydantic validates it, and if validation fails the error goes back to the model for another try. You get a typed object or an exception, never half-valid data. Everything here follows the Instructor docs as of November 2026.
Install and the first call
The docs give pip install instructor (uv and Poetry work too) and say Python 3.10 or later is required. The library is MIT licensed.
The quickstart, as the docs show it:
import instructor
from pydantic import BaseModel
class Person(BaseModel):
name: str
age: int
occupation: str
client = instructor.from_provider("openai/gpt-6-luna")
person = client.create(
response_model=Person,
reasoning_effort="none",
messages=[{"role": "user", "content": "Extract: John is a 30-year-old software engineer"}],
)
print(person) # Person(name='John', age=30, occupation='software engineer')
Two things to notice. from_provider takes a "provider/model" string, which is how current Instructor picks the backend; if older code you find uses a different constructor, check it against the current docs before copying. And person is a real Person instance: your editor knows person.age is an int, and so does your type checker.
The docs list more than 15 providers, naming OpenAI, Anthropic, Google Gemini, Mistral, Cohere, Ollama, DeepSeek, Vertex AI, LiteLLM and llama-cpp-python among them. Switching is mostly a matter of changing the string, which makes it easy to test the same schema against a cheaper model. Pass async_client=True when you need the async client.
Validation is where it earns its keep
Type coercion alone is useful, but the real point is validators. Anything Pydantic can check, Instructor can make the model fix. The retrying docs use an age range check; here's the same idea:
import instructor
from pydantic import BaseModel, field_validator
class UserInfo(BaseModel):
name: str
age: int
@field_validator("age")
@classmethod
def age_in_range(cls, v: int) -> int:
if v < 0 or v > 150:
raise ValueError("age must be between 0 and 150")
return v
client = instructor.from_provider("openai/gpt-6-luna")
user = client.create(
response_model=UserInfo,
max_retries=3,
messages=[{"role": "user", "content": "Extract: Ada turned 36 last spring."}],
)
When the validator raises, Instructor doesn't just retry blindly. The retrying page says failed attempts are passed to its reask handlers, which put the validation error into the next request. The model sees "age must be between 0 and 150" and corrects that specific field. Write your ValueError messages for the model, not for a log file: say what's wrong and what a right answer looks like.
The homepage's larger example does the same with a Ticket model: an optional estimated_hours field constrained to more than 0 and at most 100, plus a validator that only accepts half-hour steps. That's a good illustration of the split. Field constraints (Field(gt=0, le=100)) handle ranges declaratively; a @field_validator handles rules that need code.
What max_retries actually counts
This trips people up, so it's worth being exact. From the retrying page:
max_retriesonclient.create(...)sets Instructor's validation retries after the first extraction attempt.max_retries=2means up to three calls in total. Negative values count as zero.- Your provider SDK has its own
max_retries, for transport failures. Those are separate. Instructor doesn't re-retry an SDK rate-limit, connection or server error that the SDK already gave up on. - When validation retries run out, you get
InstructorRetryExceptionfrominstructor.core.exceptions. It carriesn_attemptsandfailed_attempts, and each failed attempt has anattempt_numberand theexception.
So a production call looks like this:
from instructor.core.exceptions import InstructorRetryException
try:
user = client.create(response_model=UserInfo, max_retries=2, messages=msgs)
except InstructorRetryException as e:
log.warning("extraction failed after %s attempts", e.n_attempts)
for attempt in e.failed_attempts:
log.debug("attempt %s: %s", attempt.attempt_number, attempt.exception)
user = None
Each retry is a full model call, billed like any other. I'd keep max_retries at 2 or 3. If a schema regularly needs more than that, the schema or the prompt is the problem; more retries just make it expensive.
The page also shows passing a tenacity Retrying object as max_retries when you want backoff or to retry only on certain exception types. One gotcha it calls out: if you wrap the whole extraction in an outer @retry decorator, that decorator sees InstructorRetryException, not the underlying error, and each restart begins a fresh retry budget. Easy to multiply your costs by accident.
Designing schemas the model can fill
A few habits make the difference between a schema that validates first time and one that burns retries:
| Habit | Why |
|---|---|
Name fields for what they mean (invoice_total_eur, not amount) | The field name is part of the prompt |
Use Literal[...] or an Enum for categories | The model picks from a list instead of inventing labels |
Make genuinely optional things Optional[...] = None | Otherwise the model invents a value to satisfy "required" |
Add Field(description=...) for anything ambiguous | They become part of the JSON schema |
| Keep nesting shallow at first | Deep trees fail in more places at once |
The optional point is the one I'd underline. If a document might not contain a phone number and your schema says phone: str, you have asked the model to make one up. Validation will pass. That's worse than an error.
Instructor or native structured outputs
Most big providers now have their own JSON-schema modes; our post on structured outputs from LLMs covers how OpenAI, Claude and Gemini implement them. So why add a library?
Native modes guarantee the shape. They don't run your business rules: a schema-valid age: 400 sails through. Instructor's value is the Pydantic validators plus the reask loop, and the fact that the same code runs against many providers, including local ones like Ollama. If you only ever call one provider and your rules are all expressible in JSON Schema, the native mode may be enough. Once you have rules like "end date after start date", Instructor is the shorter path.
If you're building whole agents around typed outputs rather than single extraction calls, Pydantic AI is the related tool to look at; our JSON Schema cheat sheet helps when you need to see what your Pydantic model turns into.
A checklist before you ship an extractor
- Every field that might be absent is
Optionalwith aNonedefault. - Validator error messages tell the model how to fix the value.
max_retriesis 2 or 3, and you catchInstructorRetryException.- The provider SDK's own transport retries are configured separately.
- You've run the extractor on twenty real inputs, including ugly ones, and logged how many needed a retry.
Written by AIDToolStack Editorial
Researched from official documentation, specifications and vendor pages, listed under Sources below. Last checked November 2026.