AI Card Bao NAS.AICARDBAO.COM
Home / open source / Instructor
AI TOOL / #13022

Instructor

A library that retrieves clean, structured outputs from LLMs, efficiently extracting messy text into JSON fields.

Introduction

English · 简体中文

Define the data you need as a Pydantic model. Instructor asks your LLM for those fields and validates the response. Install Instructor and set OPENAI_API_KEY to run this example.

import instructor
from pydantic import BaseModel

# Define what you want
class User(BaseModel):
    name: str
    age: int

# Extract it from natural language
client = instructor.from_provider("openai/gpt-6-luna")
user = client.chat.completions.create(
    response_model=User,
    reasoning_effort="none",
    messages=[{"role": "user", "content": "John is 25 years old"}],
)

print(user)  # User(name='John', age=25)

If a response fails validation, Instructor can retry with feedback from Pydantic. Extract your first record or stream a list of records.

Instructor 1.18 adds classification and scoring through the OpenAI Decisions API and Jev. Define a decision model in Python.

Use Instructor for fast extraction, reach for PydanticAI when you need agents. Instructor keeps schema-first flows simple and cheap. If your app needs richer agent runs, built-in observability, or shareable traces, try PydanticAI. PydanticAI is the official agent runtime from the Pydantic team, adding typed tools, replayable datasets, evals, and production dashboards while using the same Pydantic models. Dive into the PydanticAI docs to see how it extends Instructor-style workflows.

Why use Instructor?

Getting structured data from LLMs is hard. You need to:

  1. Write complex JSON schemas
  2. Handle validation errors
  3. Retry failed extractions
  4. Parse unstructured responses
  5. Deal with different provider APIs

Instructor handles all of this with one simple interface:

Without Instructor With Instructor

response = openai.chat.completions.create(
    model="gpt-6-luna",
    reasoning_effort="none",
    messages=[{"role": "user", "content": "..."}],
    tools=[
        {
            "type": "function",
            "function": {
                "name": "extract_user",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "name": {"type": "string"},
                        "age": {"type": "integer"},
                    },
                },
            },
        }
    ],
)

# Parse response
tool_call = response.choices[0].message.tool_calls[0]
user_data = json.loads(tool_call.function.arguments)

# Validate manually
if "name" not in user_data:
    # Handle error...
    pass
client = instructor.from_provider("openai/gpt-6-luna")

user = client.chat.completions.create(
    response_model=User,
    messages=[{"role": "user", "content": "..."}],
)

# That's it! user is validated and typed

Install in seconds

pip install instructor

Or with your package manager:

uv add instructor
poetry add instructor

Works with every major provider

Use the same code with any LLM provider:

import os

# OpenAI
client = instructor.from_provider("openai/gpt-6-luna")

# Anthropic
client = instructor.from_provider("anthropic/claude-haiku-5-5")

# Google
client = instructor.from_provider("google/gemini-3.8-flash")

# Ollama (local)
client = instructor.from_provider("ollama/llama3.2")

# With API keys directly (no environment variables needed)
client = instructor.from_provider(
    "openai/gpt-6-luna", api_key=os.environ["OPENAI_API_KEY"]
)
client = instructor.from_provider(
    "anthropic/claude-haiku-5-5", api_key=os.environ["ANTHROPIC_API_KEY"]
)
client = instructor.from_provider("groq/llama-3.1-8b-instant", api_key="gsk_...")

# All use the same API!
user = client.chat.completions.create(
    response_model=User,
    messages=[{"role": "user", "content": "..."}],
)

Production-ready features

Automatic retries

Failed validations are automatically retried with the error message:

from pydantic import BaseModel, field_validator

class User(BaseModel):
    name: str
    age: int

    @field_validator('age')
    def validate_age(cls, v):
        if v < 0:
            raise ValueError('Age must be positive')
        return v

# Instructor automatically retries when validation fails
user = client.chat.completions.create(
    response_model=User,
    messages=[{"role": "user", "content": "..."}],
    max_retries=3,
)

Streaming support

Stream partial objects as they're generated:

from instructor import Partial

for partial_user in client.chat.completions.create(
    response_model=Partial[User],
    messages=[{"role": "user", "content": "..."}],
    stream=True,
):
    print(partial_user)
    # User(name=None, age=None)
    # User(name="John", age=None)
    # User(name="John", age=25)

Nested objects

Extract complex, nested data structures:

from typing import List

class Address(BaseModel):
    street: str
    city: str
    country: str

class User(BaseModel):
    name: str
    age: int
    addresses: List[Address]

# Instructor handles nested objects automatically
user = client.chat.completions.create(
    response_model=User,
    messages=[{"role": "user", "content": "..."}],
)

Used in production by

Trusted by over 100,000 developers and companies building AI applications:

  • 3M+ monthly downloads
  • 10K+ GitHub stars
  • 1000+ community contributors

Companies using Instructor include teams at OpenAI, Google, Microsoft, AWS, and many YC startups.

Get started

Basic extraction

Extract structured data from any text:

from pydantic import BaseModel
import instructor

client = instructor.from_provider("openai/gpt-6-luna")

class Product(BaseModel):
    name: str
    price: float
    in_stock: bool

product = client.chat.completions.create(
    response_model=Product,
    messages=[{"role": "user", "content": "iPhone 15 Pro, $999, available now"}],
)

print(product)
# Product(name='iPhone 15 Pro', price=999.0, in_stock=True)

Multiple languages

Instructor's simple API is available in many languages:

  • Python - The original
  • TypeScript - Full TypeScript support
  • Ruby - Ruby implementation
  • Go - Go implementation
  • Elixir - Elixir implementation
  • Rust - Rust implementation

Learn more

Why use Instructor over alternatives?

vs Raw JSON mode: Instructor provides automatic validation, retries, streaming, and nested object support. No manual schema writing.

vs LangChain/LlamaIndex: Instructor is focused on one thing - structured extraction. It's lighter, faster, and easier to debug.

vs Custom solutions: Battle-tested by thousands of developers. Handles edge cases you haven't thought of yet.

Contributing

We welcome contributions! Check out our good first issues to get started.

License

MIT License - see LICENSE for details.


Built by the Instructor community. Special thanks to Jason Liu and all contributors.

Visits:37 Updated:2026-12-04 AI tools

Related

Kiddoworksheets KiddoWorksheets is an online educational resource platform dedicated to providing free printable worksheets for children in the kindergarten to primary school age range – roughly aged 3 to 10, corresponding to K–5 grades. This platform offers a vast collection of free, printable paper materials. IPTV live broadcast source I would like to share with you two subscription links for IPTV live streaming sources. The authors of both projects regularly update these sources. Since IPv4 addresses often become invalid, I recommend using IPv6 addresses instead. Currently, most operators support IPv6, so you simply need to... Userscript.Zone Userscript.Zone is a website dedicated to searching for and installing userscripts online (UserScript, or “Tampermonkey scripts”). What is a userscript (UserScript)? It is a small JavaScript program that can immersive translation Immersive Translation is a translation tool/browser extension that focuses on bilingual parallel reading. It emphasizes the experience of “displaying the translated text directly within the context of the original text” (while preserving the contextual context at the paragraph level), and it supports translation in various content formats such as PDF, EPUB, and video subtitles. The bilingual feature of Immersive Translation allows users to... Galaxy AI Mirror-GPTPLUS Mirror Station Galaxy Video Bureau is a platform focusing on streaming media and AI productivity software sharing, reducing user costs through a shared rental model. It provides mainstream entertainment including Netflix, Disney+, HBO, Apple TV+, Midjourney, ChatGPT, etc. Toonme Upload one of your photos or avatars to the Toonme website, and after a few seconds, your image will be converted into a cartoon style. The website can be used for free without the need to register. Note: It may not be accessible in China due to network restrictions; you will need a special connection to use it. Additionally, the site will generate various styles of cartoon images for you – this has been tested in practice for accounting purposes.