Structured LLM outputs in Python with Instructor¶
Define the fields you need in a Pydantic model and pass it to Instructor as response_model. Instructor sends the schema to your LLM, validates the response, and returns a Python object.
What is Instructor?¶
Instructor is a Python library for extracting structured data from text, images, and documents. If a record fails validation, Instructor can send the error back to the LLM and retry.
- Extract your first record or learn how response models work.
- Stream a list of completed records or watch one record fill in.
- Classify and score content with typed decisions in Instructor 1.18 and later.
For agent workflows, see PydanticAI.
Quick Start¶
Use Python 3.10 or later. The base install includes Pydantic and the OpenAI SDK. See the installation guide for other providers.
Extract Structured Data¶
Set OPENAI_API_KEY in your environment. This example asks GPT-6 Luna to extract three fields from a sentence.
import instructor
from pydantic import BaseModel
class Person(BaseModel):
name: str
age: int
occupation: str
client = instructor.from_provider("openai/gpt-6-luna")
# Extract structured data from natural language
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')
The from_provider API supports both sync and async usage (async_client=True) and automatically handles provider-specific configurations. See all supported providers โ
Complex Schemas & Validation¶
Instructor excels at extracting complex, nested data structures with custom validation rules. Here's a concise example:
import instructor
from pydantic import BaseModel, Field, field_validator
from typing import List, Optional
from enum import Enum
class Priority(str, Enum):
LOW = "low"
MEDIUM = "medium"
HIGH = "high"
CRITICAL = "critical"
class Ticket(BaseModel):
title: str = Field(..., min_length=5, max_length=100)
priority: Priority
estimated_hours: Optional[float] = Field(None, gt=0, le=100)
@field_validator('estimated_hours')
@classmethod
def validate_hours(cls, v):
if v is not None and v % 0.5 != 0:
raise ValueError('Hours must be in 0.5 increments')
return v
class CustomerSupport(BaseModel):
customer_name: str
tickets: List[Ticket] = Field(..., min_items=1)
client = instructor.from_provider("openai/gpt-6-luna")
support_case = client.create(
response_model=CustomerSupport,
messages=[{"role": "user", "content": "Extract support case details..."}],
max_retries=3,
)
Key Features: - Deep nesting with nested models and lists - Custom validation with Pydantic validators - Automatic retries on validation failures - Type-safe extraction with full IDE support
Learn more about validation and complex schemas โ
Supported LLM Providers¶
Use from_provider to select a provider and model. Check the integration guide for supported modes, SDKs, and credentials.
Star the Repo Cookbooks Prompting Guide
If you ever get stuck, you can always run instructor docs to open the documentation in your browser. It even supports searching for specific topics.
Provider Examples¶
All providers use the same simple interface. Here are quick examples for the most popular providers:
Citation¶
If you use Instructor in your research or project, please cite it using:
@software{liu2024instructor,
author = {Jason Liu and Contributors},
title = {Instructor: A library for structured outputs from large language models},
url = {https://github.com/567-labs/instructor},
year = {2024},
month = {3}
}
Why use Instructor?¶
-
Simple API with Full Prompt Control
Instructor provides a straightforward API that gives you complete ownership and control over your prompts. This allows for fine-tuned customization and optimization of your LLM interactions.
-
Multi-Language Support
Simplify structured data extraction from LLMs with type hints and validation.
-
Reasking and Validation
Automatically reask the model when validation fails, ensuring high-quality outputs. Leverage Pydantic's validation for robust error handling.
-
Streaming Support
Stream partial results and iterables with ease, allowing for real-time processing and improved responsiveness in your applications.
-
Powered by Type Hints
Leverage Pydantic for schema validation, prompting control, less code, and IDE integration.
-
Simplified LLM Interactions
Support for OpenAI, Anthropic, Google, Vertex AI, Mistral, Ollama, llama-cpp-python, Cohere, LiteLLM.
Using Hooks¶
Instructor's hooks system lets you intercept and handle events during LLM interactions. Use hooks for logging, monitoring, or custom error handling:
import instructor
from pydantic import BaseModel
class UserInfo(BaseModel):
name: str
age: int
client = instructor.from_provider("openai/gpt-6-luna")
# Attach hooks for logging and error handling
client.on("completion:kwargs", lambda **kw: print("Called with:", kw))
client.on("completion:error", lambda e: print(f"Error: {e}"))
user_info = client.create(
response_model=UserInfo,
messages=[{"role": "user", "content": "Extract: John is 20 years old"}],
)
Type Inference & Advanced Methods¶
Instructor provides full type inference for better IDE support and type safety. The client includes specialized methods for different use cases:
Basic extraction:
import instructor
from pydantic import BaseModel
class User(BaseModel):
name: str
age: int
client = instructor.from_provider("openai/gpt-6-luna")
user = client.create(response_model=User, messages=[...]) # Type: User
Async support:
client = instructor.from_provider("openai/gpt-6-luna", async_client=True)
user = await client.create(...) # Type: User
Access original completion:
Stream partial objects:
Stream multiple objects:
All methods provide full type inference for better IDE autocomplete and type checking.
Frequently Asked Questions¶
What is Instructor?¶
Instructor is a Python library that extracts structured, validated data from Large Language Models (LLMs). It uses Pydantic models to define output schemas and automatically handles validation, retries, and error handling.
Which LLM providers does Instructor support?¶
Instructor supports 15+ providers including OpenAI, Anthropic, Google Gemini, Mistral, Cohere, Ollama, DeepSeek, and many more. See our integrations page for the complete list.
Do I need to know Pydantic to use Instructor?¶
Basic Pydantic knowledge helps, but you can get started with simple models. Instructor works with any Pydantic BaseModel, and you can learn advanced features as you need them.
How does Instructor compare to other libraries?¶
Instructor focuses specifically on structured outputs with automatic validation and retries. Unlike larger frameworks, Instructor does one thing very well: getting reliable, validated data from LLMs.
Can I use Instructor with open source models?¶
Yes! Instructor works with Ollama, llama-cpp-python, and other local models. See our Ollama integration guide to get started.
Does Instructor work with async code?¶
Yes, Instructor fully supports async/await. Use async_client=True when creating your client, then use await client.create().
Templating¶
Instructor supports templating with Jinja, which lets you create dynamic prompts. This is useful when you want to fill in parts of a prompt with data. Here's a simple example:
import instructor
from pydantic import BaseModel
client = instructor.from_provider("openai/gpt-6-luna")
class User(BaseModel):
name: str
age: int
# Create a completion using a Jinja template in the message content
response = client.create(
messages=[
{
"role": "user",
"content": """Extract the information from the
following text: {{ data }}`""",
},
],
response_model=User,
context={"data": "John Doe is thirty years old"},
)
print(response)
#> User(name='John Doe', age=30)
Learn more about templating :octicons-arrow-right:
Validation¶
You can also use Pydantic to validate your outputs and get the llm to retry on failure. Check out our docs on retrying and validation context.
import instructor
from pydantic import BaseModel, ValidationError, BeforeValidator
from typing_extensions import Annotated
from instructor import llm_validator
# Create instructor client
client = instructor.from_provider("openai/gpt-6-luna")
class QuestionAnswer(BaseModel):
question: str
answer: Annotated[
str,
BeforeValidator(llm_validator("don't say objectionable things", client=client)),
]
try:
qa = QuestionAnswer(
question="What is the meaning of life?",
answer="The meaning of life is to be evil and steal",
)
except ValidationError as e:
print(e)
"""
1 validation error for QuestionAnswer
answer
Assertion failed, The statement promotes objectionable behavior by encouraging evil and stealing. [type=assertion_error, input_value='The meaning of life is to be evil and steal', input_type=str]
"""
Contributing¶
If you want to help out, checkout some of the issues marked as good-first-issue or help-wanted. Found here. They could be anything from code improvements, a guest blog post, or a new cook book.
License¶
This project is licensed under the terms of the MIT License.