Skip to content

Menu

Tutorials

Validated Structured Output with Instructor and Pydantic

AIDToolStack EditorialNovember 30, 20265 min read
InstructorPydanticStructured outputPython
Share:Twitter

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.

Loop diagram: create() sends response_model and messages to the LLM, the JSON reply is validated by Pydantic, and on failure the error is sent back and retried up to max_retries
Loop diagram: create() sends response_model and messages to the LLM, the JSON reply is validated by Pydantic, and on failure the error is sent back and retried up to max_retries

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_retries on client.create(...) sets Instructor's validation retries after the first extraction attempt. max_retries=2 means 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 InstructorRetryException from instructor.core.exceptions. It carries n_attempts and failed_attempts, and each failed attempt has an attempt_number and the exception.

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:

HabitWhy
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 categoriesThe model picks from a list instead of inventing labels
Make genuinely optional things Optional[...] = NoneOtherwise the model invents a value to satisfy "required"
Add Field(description=...) for anything ambiguousThey become part of the JSON schema
Keep nesting shallow at firstDeep 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

  1. Every field that might be absent is Optional with a None default.
  2. Validator error messages tell the model how to fix the value.
  3. max_retries is 2 or 3, and you catch InstructorRetryException.
  4. The provider SDK's own transport retries are configured separately.
  5. You've run the extractor on twenty real inputs, including ugly ones, and logged how many needed a retry.
AE

Written by AIDToolStack Editorial

Researched from official documentation, specifications and vendor pages, listed under Sources below. Last checked November 2026.

Sources

  1. python.useinstructor.com
  2. python.useinstructor.com /concepts/retrying

Related Posts

Reviews and commentsShow

Reviews

Sign in to leave a review.

Loading reviews…

Comments

Sign in to leave a comment.

Loading comments…