JSON mode solves the wrong half of the problem. Turn it on and the provider guarantees that whatever comes back parses as JSON. It does not guarantee the JSON has the fields you asked for, that the nested objects are shaped right, that an optional field you did not get is null instead of the string “N/A”, or that a number is a number and not "142.50". You traded a parsing crash for a silent data-quality bug, which is worse, because the parsing crash at least told you something was wrong.

I have watched a pipeline run clean for a month on JSON mode and then quietly start writing {"amount": "unknown"} into a decimal column because one tenant’s documents phrased things differently and the model decided prose was the honest answer. JSON mode was happy. The database was not.

Instructor is the library that closes the other half. It is not an agent framework and not a new SDK to learn. It patches the client you already have so that response_model=Invoice returns a validated Invoice, retries the model with the validation error when the content is wrong, and does the same thing in Python with Pydantic and in TypeScript with Zod. This post is about what that actually buys you and where it stops.

The Naive Approach and Where It Breaks

Everyone starts in the same place. Ask for JSON, parse the string.

import re, json

resp = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    messages=[{"role": "user", "content": f"Extract the invoice as JSON: {text}"}],
)
raw = resp.content[0].text
data = json.loads(re.search(r"\{.*\}", raw, re.DOTALL).group(0))

This breaks on a prose preamble, inline backticks, nested braces that confuse the greedy match, and the first model version bump. Fine. So you turn on the provider’s JSON mode and the syntax problem goes away:

resp = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    messages=[{"role": "user", "content": f"Return only JSON for the invoice: {text}"}],
)
data = json.loads(resp.content[0].text)  # guaranteed to parse

Now json.loads never throws. But look at what you are still writing by hand for every schema and every call site:

  • A data.get("invoice_id") for each field, because JSON mode does not enforce your shape.
  • A cast from "142.50" to a float, because the model string-typed the number.
  • A decision about what data.get("currency") being absent means, versus present and null.
  • A validation that line_items is a list of objects and not a list of strings this time.
  • A retry if any of that is wrong, which means a hand-assembled follow-up message, a loop counter, and a termination condition you will get subtly wrong.

Each of these is three lines. Multiplied by every field, every schema, and every provider you support, it is a validation framework you are writing by accident, untested, scattered across call sites. That is the exact gap Instructor fills, and it fills it without asking you to restructure your code around a new object model.

The Core Idea: Patch the Client You Already Have

Instructor does not replace your SDK. It wraps it. You keep your anthropic.Anthropic() or openai.OpenAI() client, hand it to Instructor, and get back a client with the same surface plus one new argument.

import instructor
from anthropic import Anthropic
from pydantic import BaseModel

class Invoice(BaseModel):
    invoice_id: str
    total: float
    currency: str
    line_items: list[str]

client = instructor.from_anthropic(Anthropic())

invoice = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    response_model=Invoice,
    messages=[{"role": "user", "content": f"Extract the invoice: {text}"}],
)

print(invoice.total)  # a float, statically typed, validated

invoice is an Invoice instance. Not a dict, not a response object you have to dig through. Your IDE and mypy know invoice.total is a float before the program runs. The response.content[0].text dance, the json.loads, the field-by-field casting, and the shape checking are all gone, replaced by the Pydantic model you were going to write anyway.

The important design decision is that Instructor is a thin behavioral patch, not a framework. There is no Agent, no dependency container, no new mental model. If your codebase already calls client.messages.create, the diff to adopt Instructor is the two lines that wrap the client and the one response_model argument. That low footprint is the whole reason to reach for it over a heavier framework when extraction is all you need.

Retry With Error Feedback Is the Feature That Pays Rent

Schema compliance is not semantic correctness. A model can return a perfectly shaped Invoice whose total does not match the line items, or whose invoice_id it invented because the document did not have one. Instructor lets you express the real constraint as a Pydantic validator, and when the validator fails, it feeds the error back to the model and asks it to try again.

from pydantic import BaseModel, field_validator, model_validator

class Invoice(BaseModel):
    invoice_id: str
    total: float
    line_item_total: float

    @field_validator("invoice_id")
    @classmethod
    def looks_like_an_id(cls, v: str) -> str:
        if not v.startswith("INV-"):
            raise ValueError("invoice_id must start with INV-")
        return v

    @model_validator(mode="after")
    def totals_reconcile(self) -> "Invoice":
        if abs(self.total - self.line_item_total) > 0.01:
            raise ValueError(
                f"total {self.total} does not match line_item_total "
                f"{self.line_item_total}; recompute from the line items"
            )
        return self

invoice = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    response_model=Invoice,
    max_retries=3,
    messages=[{"role": "user", "content": text}],
)

When the model returns an invoice whose totals do not reconcile, the Pydantic ValidationError is caught, its message is appended to the conversation as a correction turn, and the model tries again, up to max_retries. The critical part is that the model sees the exact error string. “total 142.50 does not match line_item_total 138.00” is a far more useful instruction than any amount of up-front prompt engineering about being careful with numbers. You are debugging the model at runtime with its own feedback loop instead of trying to anticipate every failure in the system prompt.

If it still fails after the retries, you get an exception, not a silently wrong row. That is the line between defensive parsing and an enforced invariant.

For the “the document does not contain this” case, do not force the model to fabricate. Give it an honest branch with a union type:

from typing import Union

class ExtractionFailed(BaseModel):
    reason: str

result = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    response_model=Union[Invoice, ExtractionFailed],
    messages=[{"role": "user", "content": text}],
)

if isinstance(result, ExtractionFailed):
    log.warning("no invoice: %s", result.reason)
else:
    save(result)

Now the model has a legitimate way to say “there is no total here” and your downstream code pattern-matches on the type instead of inspecting a boolean flag you hoped it set.

Nested Schemas and Optional Fields, the Thing JSON Mode Fumbles

The payoff grows with schema complexity. Flat key-value extraction is where JSON mode looks adequate. The moment you have nested objects, lists of objects, and genuinely optional fields, the hand-rolled version collapses and Instructor stays flat.

from pydantic import BaseModel, Field
from typing import Optional

class LineItem(BaseModel):
    description: str
    quantity: int
    unit_price: float

class Address(BaseModel):
    line1: str
    city: str
    postal_code: Optional[str] = None  # genuinely optional, stays None

class Invoice(BaseModel):
    invoice_id: str
    vendor: str
    billing_address: Address
    line_items: list[LineItem] = Field(min_length=1)
    notes: Optional[str] = None

invoice = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=2048,
    response_model=Invoice,
    messages=[{"role": "user", "content": text}],
)

Instructor turns the whole nested model, including the Field(min_length=1) constraint and the Optional fields, into a JSON schema the model is constrained to follow, then validates the result against it. An optional field that is absent comes back as None, not "N/A", because the Pydantic type says so and the validator enforces it. A line_items list that comes back empty fails min_length and triggers a retry. You wrote the constraint once, as a type, and it is enforced on input instead of discovered three screens downstream.

TypeScript, Because Your Extraction Service Is Not Always Python

Instructor is not Python-only, and this is the main reason to pick it over a Python-first framework when your stack is Node. The TypeScript package wraps the OpenAI-compatible client and uses Zod where Python uses Pydantic. The model is the same: define the schema, pass it as response_model, get back a validated object with retries.

import Instructor from "@instructor-ai/instructor"
import OpenAI from "openai"
import { z } from "zod"

const oai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY })
const client = Instructor({ client: oai, mode: "TOOLS" })

const InvoiceSchema = z.object({
  invoice_id: z.string(),
  total: z.number(),
  currency: z.string(),
  line_items: z.array(z.string()).min(1),
})

const invoice = await client.chat.completions.create({
  model: "gpt-4o",
  response_model: { schema: InvoiceSchema, name: "Invoice" },
  max_retries: 3,
  messages: [{ role: "user", content: text }],
})

console.log(invoice.total) // typed as number, validated at runtime

The Zod schema gives you the same thing Pydantic does on the Python side: a single source of truth that is both the compile-time type and the runtime validator. One team can run the Python extractor and another the TypeScript one against the same provider with the same semantics, which is a real operational win when you have polyglot services doing the same extraction.

Streaming Structured Output

Waiting for a large nested object to finish generating before you can show anything is a bad user experience. Instructor streams partials: it yields progressively more complete, still-validated versions of your model as tokens arrive, so a UI can render fields the moment they are available.

from instructor import Partial

stream = client.messages.create_partial(
    model="claude-sonnet-4-6",
    max_tokens=2048,
    response_model=Invoice,
    messages=[{"role": "user", "content": text}],
)

for partial in stream:
    # partial is an Invoice with fields filled in as they arrive
    render(partial)

Each yielded partial is an Invoice where the fields generated so far are populated and the rest are defaulted, so your render code works against the same typed object throughout instead of parsing a half-finished JSON string. For extracting a list of records, create_iterable yields each complete, validated element as it finishes, which lets you start processing record one while the model is still producing record fifty.

Modes: How Instructor Talks to Each Provider

Different providers enforce structure through different mechanisms, and Instructor abstracts that behind a mode. You usually set it once and forget it, but knowing the options helps when a model misbehaves.

ModeMechanismWhen to use
TOOLSFunction/tool calling with your schema as the toolDefault for OpenAI and Anthropic; most reliable
JSONNative JSON/structured-output modeProviders with strong JSON schema support
MD_JSONAsks for a fenced JSON block, parses itFallback for models without tool calling
ANTHROPIC_TOOLSAnthropic tool-use shaped requestClaude models via the Anthropic SDK

The point is that your response_model code does not change when you switch providers or modes. The schema definition, the validators, and the retry behavior are identical whether the structure is enforced by tool calling on Claude or JSON mode on another provider. That provider-independence is what makes “run the same extraction against two vendors” a configuration change rather than a rewrite.

import instructor
from openai import OpenAI
from anthropic import Anthropic

openai_client = instructor.from_openai(OpenAI())
claude_client = instructor.from_anthropic(Anthropic())

def extract(client, model: str, text: str) -> Invoice:
    return client.messages.create(
        model=model,
        max_tokens=2048,
        response_model=Invoice,  # same schema, same validators, either provider
        messages=[{"role": "user", "content": text}],
    )

Where Instructor Sits in the Pipeline

          raw document / user text
                    |
                    v
   +-----------------------------------+
   |   patched provider client          |
   |   (from_anthropic / from_openai)   |
   +-----------------------------------+
                    |
          request + JSON schema
          derived from Pydantic model
                    |
                    v
             LLM provider
                    |
            structured response
                    |
                    v
   +-----------------------------------+
   |   Pydantic / Zod validation        |
   |   - shape check                    |
   |   - field + model validators       |
   +-----------------------------------+
            |                 |
         valid            ValidationError
            |                 |
            v                 v
      typed object     append error, retry
      to your code     (up to max_retries)
                              |
                       still failing?
                              |
                              v
                        raise exception

The whole value is that the boundary between “LLM text” and “typed object your program trusts” is one well-defined box with a retry loop inside it, instead of being smeared across your codebase as parsing, casting, and ad-hoc validation.

Honest Assessment

What works: Instructor is the lowest-friction way to make LLM extraction a typed function call. If you already have a provider client and a Pydantic or Zod schema, adoption is a few lines and the retry-with-error-feedback loop removes a category of brittle prompt engineering. The multi-provider abstraction is real, the TypeScript parity is rare and genuinely useful for polyglot teams, and streaming partials are the right answer for latency-sensitive UIs. For the specific job of “turn this text into this validated shape,” it is the tool I reach for first.

What does not: Instructor is an extraction and validation library, not an orchestration framework. It has no agent loop, no tool-dispatch runtime, no dependency injection, no built-in state for multi-step workflows. If you need an agent that calls tools in a loop and threads a database handle through them, you want Pydantic AI or a real agent framework, and bolting that onto Instructor means rebuilding it yourself. Retries also cost tokens and latency; a validator that rejects too aggressively turns one call into four, so set max_retries deliberately and log how often it fires. And constrained decoding plus validation still cannot invent information the document lacks, which is why the union-with-failure-branch pattern matters more than the retry count.

What to actually do: if your task is “extract structured records from text or documents,” start with Instructor, define the schema with the validators that encode your real invariants, set max_retries to 2 or 3, and use a union failure type instead of forcing fabrication. Keep the provider behind the patched client so switching vendors is a config change. Reach for a heavier framework only when the work grows past extraction into genuine multi-step agent behavior. For the common case, which is more common than people admit, Instructor is all you need and you will delete a surprising amount of parsing code the day you adopt it.