
Photo: Daniil Komov / Pexels
Stop Parsing LLM JSON by Hand: Instructor + Pydantic Gets You Validated Python Objects Every Time
Chris Harper
2 min read
Aug 5, 2026 · 20:07 UTC
The instructor library patches your OpenAI/Anthropic/Ollama client to enforce a Pydantic schema and automatically retry on validation failures — reliable structured output from any LLM in under 10 lines.
Every agent eventually needs to extract structured data from an LLM: a list of entities, a classification, a tool call argument. The raw approach — JSON mode, then json.loads(), then manual validation — breaks on malformed output and you write retry logic from scratch every time. Instructor automates the whole loop.
How it works
Define a Pydantic model, patch your client once, and call .messages.create() with response_model=:
pip install instructor
import instructor
from anthropic import Anthropic
from pydantic import BaseModel
from typing import Literal
class MovieReview(BaseModel):
title: str
sentiment: Literal["positive", "negative", "neutral"]
score: int # 1-10
summary: str
client = instructor.from_anthropic(Anthropic())
review = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=512,
messages=[{
"role": "user",
"content": "Review: 'Dune Part 3 was stunning but three hours long.' Extract a structured review."
}],
response_model=MovieReview,
)
print(review.sentiment) # "positive"
print(review.score) # 8
print(type(review)) # <class '__main__.MovieReview'>
You get back a validated Python object, not a string or dict. If the model returns invalid JSON or a score outside 1–10, instructor feeds the Pydantic validation error back to the model and retries — up to 3 times by default. The loop is invisible to your code.
Why this matters for agents
Reliable structured output is the invisible foundation of every agent tool call. When your agent decides {"action": "search", "query": "..."}, a validation failure means a dropped tool invocation. Instructor makes that failure mode disappear.
It works across providers — the same response_model= API regardless of whether the provider uses native structured output, tool calling, or JSON mode:
# One-line provider swap:
client = instructor.from_openai(OpenAI()) # OpenAI native structured output
client = instructor.from_anthropic(Anthropic()) # Claude tool-calling under the hood
client = instructor.from_ollama(...) # local Ollama JSON mode
Sources: instructor docs · Instructor + Pydantic video — YouTube · Beginner's guide — DEV Community · Production validation guide