instructor
하는 일
이 스킬은 언어 모델 답변에서 구조화되고 검증된 데이터를 얻는 라이브러리 Instructor를 설명합니다. 모델 출력에서 이름, 나이, 이메일 같은 깔끔한 필드가 필요한 개발자를 위한 스킬입니다.
사용하는 경우
- ✓AI 답변에서 이름, 날짜, 금액 같은 필드를 추출해야 할 때.
- ✓출력이 스키마와 맞는지 자동으로 확인하고 싶을 때.
- ✓모델이 작성하는 동안 부분 결과를 스트리밍으로 받고 싶은 경우.
스킬 링크
https://github.com/Orchestra-Research/AI-Research-SKILLs/blob/main/16-prompt-engineering/instructor/SKILL.md복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.
사용 방법
가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
AI에게 요청하는 예시
“이 텍스트에서 이름, 나이, 이메일을 뽑아서 코드에서 쓸 수 있는 깔끔한 필드로 돌려주세요.”
매주 새 스킬 5개. 읽는 데 1분.
작동 방식
출력 형태를 Pydantic 모델로 정의하고 이를 응답 모델로 전달합니다. Instructor는 답변을 확인하고, 검증에 실패하면 재시도하며, 타입이 지정된 객체를 돌려줍니다.
기술 내용 (원본 SKILL.md)
작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.
Instructor: Structured LLM Outputs
When to Use This Skill
Use Instructor when you need to:
- Extract structured data from LLM responses reliably
- Validate outputs against Pydantic schemas automatically
- Retry failed extractions with automatic error handling
- Parse complex JSON with type safety and validation
- Stream partial results for real-time processing
- Support multiple LLM providers with consistent API
GitHub Stars: 15,000+ | Battle-tested: 100,000+ developers
Installation
# Base installation
pip install instructor
# With specific providers
pip install "instructor[anthropic]" # Anthropic Claude
pip install "instructor[openai]" # OpenAI
pip install "instructor[all]" # All providers
Quick Start
Basic Example: Extract User Data
import instructor
from pydantic import BaseModel
from anthropic import Anthropic
# Define output structure
class User(BaseModel):
name: str
age: int
email: str
# Create instructor client
client = instructor.from_anthropic(Anthropic())
# Extract structured data
user = client.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=1024,
messages=[{
"role": "user",
"content": "John Doe is 30 years old. His email is john@example.com"
}],
response_model=User
)
print(user.name) # "John Doe"
print(user.age) # 30
print(user.email) # "john@example.com"
With OpenAI
from openai import OpenAI
client = instructor.from_openai(OpenAI())
user = client.chat.completions.create(
model="gpt-4o-mini",
response_model=User,
messages=[{"role": "user", "content": "Extract: Alice, 25, alice@email.com"}]
)
Core Concepts
1. Response Models (Pydantic)
Response models define the structure and validation rules for LLM outputs.
Basic Model
from pydantic import BaseModel, Field
class Article(BaseModel):
title: str = Field(description="Article title")
author: str = Field(description="Author name")
word_count: int = Field(description="Number of words", gt=0)
tags: list[str] = Field(description="List of relevant tags")
article = client.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=1024,
messages=[{
"role": "user",
"content": "Analyze this article: [article text]"
}],
response_model=Article
)
Benefits:
- Type safety with Python type hints
- Automatic validation (word_count > 0)
- Self-documenting with Field descriptions
- IDE autocomplete support
Nested Models
class Address(BaseModel):
street: str
city: str
country: str
class Person(BaseModel):
name: str
age: int
address: Address # Nested model
person = client.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=1024,
messages=[{
"role": "user",
"content": "John lives at 123 Main St, Boston, USA"
}],
response_model=Person
)
print(person.address.city) # "Boston"
Optional Fields
from typing import Optional
class Product(BaseModel):
name: str
price: float
discount: Optional[float] = None # Optional
description: str = Field(default="No description") # Default value
# LLM doesn't need to provide discount or description
Enums for Constraints
from enum import Enum
class Sentiment(str, Enum):
POSITIVE = "positive"
NEGATIVE = "negative"
NEUTRAL = "neutral"
class Review(BaseModel):
text: str
sentiment: Sentiment # Only these 3 values allowed
review = client.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=1024,
messages=[{
"role": "user",
"content": "This product is amazing!"
}],
response_model=Review
)
print(review.sentiment) # Sentiment.POSITIVE
2. Validation
Pydantic validates LLM outputs automatically. If validation fails, Instructor retries.
Built-in Validators
from pydantic import Field, EmailStr, HttpUrl
class Contact(BaseModel):
name: str = Field(min_length=2, max_length=100)
age: int = Field(ge=0, le=120) # 0 <= age <= 120
email: EmailStr # Validates email format
website: HttpUrl # Validates URL format
# If LLM provides invalid data, Instructor retries automatically
Custom Validators
from pydantic import field_validator
class Event(BaseModel):
name: str
date: str
attend
자주 묻는 질문
Pydantic이란 무엇인가요?
데이터 형태를 정의하고 값이 그에 맞는지 확인하는 Python 라이브러리입니다.
어떤 제공자와 함께 작동하나요?
Anthropic과 OpenAI를 보여 주며, 여러 제공자를 위한 하나의 API를 제공한다고 설명합니다.
어떻게 설치하나요?
anthropic 또는 openai 추가 옵션과 함께 pip install instructor를 실행하면 됩니다.
상세 정보
작성자의 원본 설명
Extract structured data from LLM responses with Pydantic validation, retry failed extractions automatically, parse complex JSON with type safety, and stream partial results with Instructor - battle-tested structured output library
인기도
- GitHub 스타
- 14k
- 순위
- #11228
- 라이선스
- MIT
- 업데이트
- 2026. 10. 10.
댓글
- …
이 저장소의 다른 스킬
autoresearch
14k에이전트가 문헌 검토부터 실험과 글쓰기까지 AI 연구 프로젝트 전체를 진행하도록 안내합니다. 테스트와 검토를 반복하는 주기를 따릅니다.
prompt-guard
14k에이전트가 Meta의 작은 분류기로, AI 앱에 도달하기 전에 텍스트에서 프롬프트 인젝션과 탈옥 시도를 검사하도록 돕습니다.
pytorch-fsdp2
14k에이전트가 PyTorch FSDP2를 학습 스크립트에 추가해, 큰 모델을 여러 GPU에 나누고 올바르게 저장하도록 보여 줍니다.
ml-training-recipes
14k에이전트에게 모델 선택, 옵티마이저, 학습률, 손실 급등 해결 등 신경망 학습의 검증된 방법을 알려 줍니다.
비슷한 스킬
writing-skills
311k에이전트를 위한 새 스킬을 작성하고, 각 스킬이 실제로 에이전트의 행동을 바꾸는지 사용하기 전에 테스트하도록 가르칩니다.
writing-for-agents
310k스킬, AGENTS.md, CLAUDE.md 등 AI 에이전트가 읽는 문서를 명확하게 쓰는 방법을 알려 주어 에이전트가 예측 가능하게 행동하도록 돕습니다.
bengali-nlp
280k에이전트가 벵골어 텍스트를 처리하도록 돕습니다. 언어를 이해하고 다루며, 텍스트를 정규화하고 고유한 특징을 처리합니다.