Instructor / Outlines for Guaranteed Structure
Instructor (Python) and Outlines constrain decoding so the model literally cannot produce invalid JSON.
Instructor / Outlines for Guaranteed Structure is a free AI Agents lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Agents learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Two Major Libraries
Two leading approaches for guaranteed structured outputs:
- Instructor (Jason Liu) — Pydantic wrapper around OpenAI/Anthropic/many providers
- Outlines (.txt) — constrained decoding for OSS models
Instructor Basics
# pip install instructor openai
import instructor
from openai import OpenAI
from pydantic import BaseModel
client = instructor.from_openai(OpenAI())
class User(BaseModel):
name: str
age: int
user = client.chat.completions.create(
model='gpt-4o-mini',
response_model=User,
messages=[{'role': 'user', 'content': 'Alice, 30'}]
)
print(user.name, user.age)Instructor Magic
Behind the scenes, Instructor:
- Generates a JSON Schema from your Pydantic model
- Adds it as a tool to the OpenAI call
- Forces that tool to be called
- Parses the arguments and returns a Pydantic instance
- Retries with repair on validation errors
Instructor with Validation
from pydantic import field_validator
class User(BaseModel):
name: str
age: int
@field_validator('age')
@classmethod
def positive(cls, v):
if v <= 0:
raise ValueError('Age must be positive')
return v
# Instructor catches ValidationError and retries automaticallyStreaming Instructor
for partial in client.chat.completions.create_partial(
model='gpt-4o-mini',
response_model=User,
messages=[{'role': 'user', 'content': 'Alice, 30'}]
):
print(partial)
# Streams partial Pydantic instances as fields fill in.Instructor with Anthropic
from anthropic import Anthropic
client = instructor.from_anthropic(Anthropic())
user = client.messages.create(
model='claude-sonnet-4-5',
max_tokens=1024,
response_model=User,
messages=[{'role': 'user', 'content': 'Alice, 30'}]
)Outlines for OSS Models
Outlines uses grammar-constrained decoding. It works with HuggingFace, vLLM, llama.cpp:
# pip install outlines
import outlines
model = outlines.models.transformers('mistralai/Mistral-7B-Instruct-v0.2')
generator = outlines.generate.json(model, User)
user = generator('Alice, 30')Why Constrained Decoding?
Outlines sees what tokens are legal at each step (per the schema) and masks out illegal tokens. The model literally cannot emit invalid JSON.
Outlines Regex / Choice
You can constrain to a regex or list of choices:
import outlines.text.generate as g
yes_no = g.choice(model, ['yes', 'no'])
result = yes_no('Are bananas fruits?') # 'yes'Combining Both
For maximum reliability:
- Use Instructor for managed/closed models (OpenAI, Anthropic)
- Use Outlines for self-hosted models
- Pydantic models are shared across both
Cost Comparison
- Strict Outputs (native OpenAI) — included in price
- Instructor — small overhead from retries on validation
- Outlines — slight throughput drop from masking, but no extra calls
When to Use Which
| Use Case | Tool |
|---|---|
| OpenAI/Anthropic | Instructor + Pydantic |
| Self-hosted OSS | Outlines |
| Latency-critical | OpenAI Structured Outputs (native) |
Outlines Approach
How does Outlines guarantee structured output?
Recap
For OpenAI/Anthropic, use native Structured Outputs or Instructor. For OSS, use Outlines. Pydantic models tie everything together.
Frequently asked questions
Is the “Instructor / Outlines for Guaranteed Structure” lesson free?
Yes — the full text of “Instructor / Outlines for Guaranteed Structure” is free to read here on the web, and the AI Agents course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Agents course, upgrade to CoddyKit PRO.
What will I learn in “Instructor / Outlines for Guaranteed Structure”?
Instructor (Python) and Outlines constrain decoding so the model literally cannot produce invalid JSON. You practise AI Agents with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start AI Agents?
No prior experience is required. AI Agents on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Instructor / Outlines for Guaranteed Structure” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this AI Agents lesson?
Yes. Every AI Agents lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- JSON Mode and Tool-Call Outputs
- Pydantic Schema Validation
- Repair Loops for Malformed Output
- Instructor / Outlines for Guaranteed Structure