instructor
БесплатноБез исполняемых скриптовНе проверенInstructor is a Python and TypeScript library that returns validated, typed objects from LLM calls using Pydantic models or Zod schemas, with automatic…
от TerminalSkills★ 221 звезда на GitHubОб этом скилле
Instructor — Structured LLM Output with Validation
Overview
Instructor wraps an LLM client so that create(...) takes a response_model (a Pydantic class in Python, a Zod schema in TypeScript) and returns an instance of it. The schema is sent to the provider as a tool or JSON schema, the reply is parsed and validated, and on a validation error the error text is sent back to the model for another attempt (max_retries). Python is the main, actively released implementation (1.17.0 on PyPI, September 2026). The TypeScript package @instructor-ai/instructor last released 1.7.0 in January 2025; it still works (checked below) but gets no new provider support.
Instructions
Install
pip install instructor # or: uv add instructor
pip install anthropic # provider SDKs are separate: openai, anthropic, google-genai ...
npm install @instructor-ai/instructor zod openai
Create a client
The documented way is from_provider("<provider>/<model>"). It reads the key from the provider's usual environment variable (OPENAI_API_KEY, ANTHROPIC_API_KEY) and returns a client whose create takes response_model. Pass async_client=True for async.
import instructor
client = instructor.from_provider("openai/gpt-4o-mini")
Wrapping an existing SDK client also works and gives the older client.chat.completions.create(...) form:
import instructor
from openai import OpenAI
client = instructor.from_openai(OpenAI()) # Mode.TOOLS by default
Mode is chosen with mode=instructor.Mode.TOOLS | JSON | MD_JSON | JSON_SCHEMA | .... Use Mode.JSON for servers without tool calling (many local models). Anthropic: the docs recommend Mode.TOOLS, and every call needs max_tokens. The PARALLEL_TOOLS and ANTHROPIC_REASONING_TOOLS modes are deprecated for Anthropic.
Streaming and lists
client.create_partial(response_model=..., ...)yields the object as it fills in (fields may be missing until the end).client.create_iterable(response_model=Contact, ...)yields several objects of the same type one at a time.client.create_with_completion(...)returns(object, raw_completion)when you need token usage.
Validation
Pydantic validators (Field(ge=0, le=1), @field_validator, Literal[...]) are what trigger a retry: a failed check becomes feedback to the model. After max_retries failures Instructor raises InstructorRetryException (import it from instructor.core.exceptions).
Examples
Extract contacts from an email (Python)
import instructor
from typing import Optional
from pydantic import BaseModel, Field
class ContactInfo(BaseModel):
name: str = Field(description="Full name of the person")
email: Optional[str] = Field(default=None, description="Email address if mentioned")
role: Optional[str] = None
class ExtractedContacts(BaseModel):
contacts: list[ContactInfo]
confidence: float = Field(ge=0, le=1, description="Overall extraction confidence")
client = instructor.from_provider("openai/gpt-4o-mini")
result = client.create(
response_model=ExtractedContacts,
messages=[{
"role": "user",
"content": "Extract contacts: Sarah Chen ([email protected]) is VP of "
"Engineering at TechCorp. CC: Mike Johnson, [email protected], Head of DevOps",
}],
max_retries=3,
)
print(result.contacts[0].name) # Sarah Chen
print(result.contacts[1].role) # Head of DevOps
result is an ExtractedContacts instance; a confidence outside 0-1 would be rejected and retried.
Stream partial objects, and use Anthropic
client = instructor.from_provider("anthropic/claude-sonnet-5")
for partial in client.create_partial(
response_model=ExtractedContacts,
messages=[{"role": "user", "content": email_text}],
max_tokens=1024,
):
print(f"{len(partial.contacts or [])} contacts so far")
Local Ollama (OpenAI-compatible endpoint):
from openai import OpenAI
client = instructor.from_openai(
OpenAI(base_url="http://localhost:11434/v1", api_key="ollama"),
mode=instructor.Mode.JSON,
)
TypeScript (Zod)
import Instructor from "@instructor-ai/instructor";
import OpenAI from "openai";
import { z } from "zod";
const client = Instructor({ client: new OpenAI(), mode: "TOOLS" });
const Contact = z.object({
name: z.string(),
email: z.string().email().nullable(),
});
const result = await client.chat.completions.create({
model: "gpt-4o-mini",
response_model: { schema: Contact, name: "Contact" },
messages: [{ role: "user", content: "Reach Sarah Chen at [email protected]" }],
max_retries: 3,
});
// result is typed as z.infer<typeof Contact>
This was run against a local mock OpenAI-compatible server with openai 7.x and zod 3.25; it returned the parsed object.
Guidelines
- Put a
descriptionon every field; it goes into the schema the model sees. M
Установить instructor в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл instructor?
Instructor is a Python and TypeScript library that returns validated, typed objects from LLM calls using Pydantic models or Zod schemas, with automatic retries when validation fails, streaming of partial objects, and support for OpenAI, Anthropic, Gemini and local models. Use when someone asks to extract structured data from text, get JSON from an LLM that matches a schema, validate model output, or stream partial structured results.
Как установить скилл instructor?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл instructor запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic