{/* Trang này được tạo tự động từ SKILL.md của kỹ năng bởi website/scripts/generate-skill-docs.py. Chỉnh sửa nguồn SKILL.md, không phải trang này. */}
Giảng viên
Trích xuất dữ liệu có cấu trúc từ các phản hồi LLM bằng xác thực Pydantic, tự động thử lại các trích xuất không thành công, phân tích cú pháp JSON phức tạp với độ an toàn về loại và truyền phát một phần kết quả với Người hướng dẫn - thư viện đầu ra có cấu trúc đã được thử nghiệm trong trận chiến
Siêu dữ liệu kỹ năng
| Nguồn | Tùy chọn — cài đặt với |
| `Hermes skills install official/mlops/instructor | |
| ` | |
| Đường dẫn |
optional-skills/mlops/instructor ` | | Phiên bản |
1.0.0 ` | | Tác giả | Nghiên cứu dàn nhạc | | Giấy phép | MIT | | Phụ thuộc |
instructor
, `pydantic
, `OpenAI
,
Anthropic |
| Nền tảng | Linux, macOS, Windows |
| Thẻ |
Prompt Engineering
, `Instructor
, `Structured Output
, `Pydantic
, `Data Extraction
, `JSON Parsing
, `Type Safety
, `Validation
, `Streaming
, `OpenAI
,
Anthropic |
Tham khảo: đầy đủ SKILL.md
Sau đây là định nghĩa kỹ năng đầy đủ mà Hermes tải khi kỹ năng này được kích hoạt. Đây là những gì tác nhân coi là hướng dẫn khi kỹ năng được kích hoạt.
Người hướng dẫn: Đầu ra LLM có cấu trúc
Khi nào nên sử dụng kỹ năng này
Sử dụng Giảng viên khi bạn cần:
- Trích xuất dữ liệu có cấu trúc từ phản hồi LLM một cách đáng tin cậy
- Xác thực đầu ra tự động đối với các lược đồ Pydantic
- Thử lại quá trình trích xuất không thành công với tính năng xử lý lỗi tự động
- Phân tích cú pháp JSON phức tạp với tính năng xác thực và an toàn về loại
- Truyền phát một phần kết quả để xử lý theo thời gian thực
- Hỗ trợ nhiều nhà cung cấp LLM với API nhất quán`Sao GitHub: 15.000+ | Đã được thử nghiệm trong thực tế: Hơn 100.000 nhà phát triển
Cài đặt
# 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
`
## Bắt đầu nhanh
### Ví dụ cơ bản: Trích xuất dữ liệu người dùng
``` python
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"
`
### Với OpenAI
`Python
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"}]
)
`
## Khái niệm cốt lõi
### 1. Mô hình phản hồi (Pydantic)
Các mô hình phản hồi xác định cấu trúc và quy tắc xác thực cho đầu ra LLM.`####Mẫu cơ bản
`Python
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
)
`
``**Quyền lợi:**
- An toàn khi gõ với gợi ý kiểu Python
- Xác thực tự động (word_count > 0)
- Tự ghi tài liệu với mô tả trường
- Hỗ trợ tự động hoàn thành IDE
#### Mô hình lồng nhau
``` python
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"
`
#### Trường tùy chọn
`Python
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 cho các ràng buộc
`Python
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. Xác thực
Pydantic tự động xác nhận kết quả đầu ra LLM. Nếu xác thực không thành công, Người hướng dẫn sẽ thử lại.
#### Trình xác thực tích hợp
`Python
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
`
#### Trình xác thực tùy chỉnh
`Python
from pydantic import field_validator`class Event(BaseModel):
name: str
date: str
attendees: int`@field_validator('date')
def validate_date(cls, v):
"""Ensure date is in YYYY-MM-DD format."""
import re
if not re.match(r'\d\\{4}-\d\\{2}-\d\\{2}', v):
raise ValueError('Date must be YYYY-MM-DD format')
return v`@field_validator('attendees')
def validate_attendees(cls, v):
"""Ensure positive attendees."""
if v < 1:
raise ValueError('Must have at least 1 attendee')
return v
`
#### Xác thực cấp độ mô hình
`Python
from pydantic import model_validator`class DateRange(BaseModel):
start_date: str
end_date: str`@model_validator(mode='after')
def check_dates(self):
"""Ensure end_date is after start_date."""
from datetime import datetime
start = datetime.strptime(self.start_date, '%Y-%m-%d')
end = datetime.strptime(self.end_date, '%Y-%m-%d')
if end < start:
raise ValueError('end_date must be after start_date')
return self
`
### 3. Tự động thử lại
Người hướng dẫn tự động thử lại khi xác thực không thành công, cung cấp phản hồi lỗi cho LLM.
`Python
# Retries up to 3 times if validation fails
user = CLIent.messages.create(
model="Claude-sonnet-4-5-20250929",
max_tokens=1024,
messages=[{
"role": "user",
"content": "Extract user from: John, age unknown"
}],
response_model=User,
max_retries=3 # Default is 3
)
# If age can't be extracted, Instructor tells the LLM:
# "Validation error: age - field required"
# LLM tries again with better extraction
`
``**Cách thức hoạt động:**
1. LLM tạo đầu ra
2. Pydantic xác nhận
3. Nếu không hợp lệ: Thông báo lỗi gửi lại LLM
4. LLM thử lại với phản hồi lỗi
5. Lặp lại tối đa max_retries
### 4. Truyền phát
Truyền phát một phần kết quả để xử lý theo thời gian thực.
#### Truyền phát các đối tượng một phần
``` python
from instructor import Partial`class Story(BaseModel):
title: str
content: str
tags: list[str]
# Stream partial updates as LLM generates
for partial_story in CLIent.messages.create_partial(
model="Claude-sonnet-4-5-20250929",
max_tokens=1024,
messages=[{
"role": "user",
"content": "Write a short sci-fi story"
}],
response_model=Story
):
print(f"Title: \{partial_story.title}")
print(f"Content so far: \{partial_story.content[:100]}...")
# Update UI in real-time
`
#### Truyền phát các lần lặp
``` python
class Task(BaseModel):
title: str
priority: str
# Stream list items as they're generated
tasks = CLIent.messages.create_iterable(
model="Claude-sonnet-4-5-20250929",
max_tokens=1024,
messages=[{
"role": "user",
"content": "Generate 10 project tasks"
}],
response_model=Task
)
for task in tasks:
print(f"- \{task.title} (\{task.priority})")
# Process each task as it arrives
`
## Cấu hình nhà cung cấp
### Claude nhân loại
``` python
import instructor
from Anthropic import Anthropic
CLIent = instructor.from_Anthropic(
Anthropic(API_key="your-API-key")
)
# Use with Claude models
response = CLIent.messages.create(
model="Claude-sonnet-4-5-20250929",
max_tokens=1024,
messages=[...],
response_model=YourModel
)
`
### OpenAI
`Python
from OpenAI import OpenAI
CLIent = instructor.from_OpenAI(
OpenAI(API_key="your-API-key")
)
response = CLIent.chat.completions.create(
model="GPT-4o-mini",
response_model=YourModel,
messages=[...]
)
`
### Mô hình địa phương (OLlama)
`Python
from OpenAI import OpenAI
# Point to local OLlama server
CLIent = instructor.from_OpenAI(
OpenAI(
base_url="http://localhost:11434/v1",
API_key="OLlama" # Required but ignored
),
mode=instructor.Mode.JSON
)
response = CLIent.chat.completions.create(
model="Llama3.1",
response_model=YourModel,
messages=[...]
)
`
## Các mẫu phổ biến
### Mẫu 1: Trích xuất dữ liệu từ văn bản
`Python
class CompanyInfo(BaseModel):
name: str
founded_year: int
industry: str
employees: int
headquarters: str`text = """
Tesla, Inc. was founded in 2003. It operates in the automotive and energy
industry with approximately 140,000 employees. The company is headquartered
in Austin, Texas.
"""`company = CLIent.messages.create(
model="Claude-sonnet-4-5-20250929",
max_tokens=1024,
messages=[{
"role": "user",
"content": f"Extract company information from: \{text}"
}],
response_model=CompanyInfo
)
`
### Mẫu 2: Phân loại
`Python
class Category(str, Enum):
TECHNOLOGY = "technology"
FINANCE = "finance"
HEALTHCARE = "healthcare"
EDUCATION = "education"
OTHER = "other"`class ArticleClassification(BaseModel):
category: Category
confidence: float = Field(ge=0.0, le=1.0)
keywords: list[str]
classification = CLIent.messages.create(
model="Claude-sonnet-4-5-20250929",
max_tokens=1024,
messages=[{
"role": "user",
"content": "Classify this article: [article text]"
}],
response_model=ArticleClassification
)
`
### Mẫu 3: Trích xuất đa thực thể
`Python
class Person(BaseModel):
name: str
role: str`class Organization(BaseModel):
name: str
industry: str`class Entities(BaseModel):
people: list[Person]
organizations: list[Organization]
locations: list[str]
text = "Tim Cook, CEO of Apple, announced at the event in Cupertino..."`entities = CLIent.messages.create(
model="Claude-sonnet-4-5-20250929",
max_tokens=1024,
messages=[{
"role": "user",
"content": f"Extract all entities from: \{text}"
}],
response_model=Entities
)
for person in entities.people:
print(f"\{person.name} - \{person.role}")
`
### Mẫu 4: Phân tích có cấu trúc
`Python
class SentimentAnalysis(BaseModel):
overall_sentiment: Sentiment
positive_aspects: list[str]
negative_aspects: list[str]
suggestions: list[str]
score: float = Field(ge=-1.0, le=1.0)
review = "The product works well but setup was confusing..."`analysis = CLIent.messages.create(
model="Claude-sonnet-4-5-20250929",
max_tokens=1024,
messages=[{
"role": "user",
"content": f"Analyze this review: \{review}"
}],
response_model=SentimentAnalysis
)
`
### Mẫu 5: Xử lý hàng loạt
`Python
def extract_person(text: str) -> Person:
return CLIent.messages.create(
model="Claude-sonnet-4-5-20250929",
max_tokens=1024,
messages=[{
"role": "user",
"content": f"Extract person from: \{text}"
}],
response_model=Person
)
texts = [
"John Doe is a 30-year-old engineer",
"Jane Smith, 25, works in marketing",
"Bob Johnson, age 40, software developer"
]
people = [extract_person(text) for text in texts]
`
## Tính năng nâng cao
### Các loại liên minh
`Python
from typing import Union`class TextContent(BaseModel):
type: str = "text"
content: str`class ImageContent(BaseModel):
type: str = "image"
url: HttpUrl
caption: str`class Post(BaseModel):
title: str
content: Union[TextContent, ImageContent] # Either type
# LLM chooses appropriate type based on content
`
### Mô hình động
`Python
from pydantic import create_model
# Create model at runtime
DynamicUser = create_model(
'User',
name=(str, ...),
age=(int, Field(ge=0)),
email=(EmailStr, ...)
)
user = CLIent.messages.create(
model="Claude-sonnet-4-5-20250929",
max_tokens=1024,
messages=[...],
response_model=DynamicUser
)
`
### Chế độ tùy chỉnh
`Python
# For providers without native structured outputs
CLIent = instructor.from_Anthropic(
Anthropic(),
mode=instructor.Mode.JSON # JSON mode
)
# Available modes:
# - Mode.Anthropic_TOOLS (recommended for Claude)
# - Mode.JSON (fallback)
# - Mode.TOOLS (OpenAI tools)
`
### Quản lý bối cảnh
``` python
# Single-use CLIent
with instructor.from_Anthropic(Anthropic()) as CLIent:
result = CLIent.messages.create(
model="Claude-sonnet-4-5-20250929",
max_tokens=1024,
messages=[...],
response_model=YourModel
)
# CLIent closed automatically
`
## Xử lý lỗi
### Xử lý lỗi xác thực
``` python
from pydantic import ValidationError`try:
user = CLIent.messages.create(
model="Claude-sonnet-4-5-20250929",
max_tokens=1024,
messages=[...],
response_model=User,
max_retries=3
)
except ValidationError as e:
print(f"Failed after retries: \{e}")
# Handle gracefully`except Exception as e:
print(f"API error: \{e}")
`
### Thông báo lỗi tùy chỉnh
``` python
class ValidatedUser(BaseModel):
name: str = Field(description="Full name, 2-100 characters")
age: int = Field(description="Age between 0 and 120", ge=0, le=120)
email: EmailStr = Field(description="Valid email address")
class Config:
# Custom error messages
JSON_schema_extra = {
"examples": [
{
"name": "John Doe",
"age": 30,
"email": "john@example.com"
}
]
}
`
## Các phương pháp hay nhất
### 1. Xóa mô tả trường
``` python
# ❌ Bad: Vague
class Product(BaseModel):
name: str
price: float
# ✅ Good: Descriptive
class Product(BaseModel):
name: str = Field(description="Product name from the text")
price: float = Field(description="Price in USD, without currency symbol")
`
### 2. Sử dụng xác thực phù hợp
``` python
# ✅ Good: Constrain values
class Rating(BaseModel):
score: int = Field(ge=1, le=5, description="Rating from 1 to 5 stars")
review: str = Field(min_length=10, description="Review text, at least 10 chars")
`
### 3. Cung cấp ví dụ trong lời nhắc
``` python
messages = [{
"role": "user",
"content": """Extract person info from: "John, 30, engineer"
Example format:
{
"name": "John Doe",
"age": 30,
"occupation": "engineer"
}"""
}]
`
### 4. Sử dụng Enums cho các danh mục cố định
`Python
# ✅ Good: Enum ensures valid values
class Status(str, Enum):
PENDING = "pending"
APPROVED = "approved"
REJECTED = "rejected"`class Application(BaseModel):
status: Status # LLM must choose from enum
`
### 5. Xử lý dữ liệu bị thiếu một cách khéo léo
``` python
class PartialData(BaseModel):
required_field: str
optional_field: Optional[str] = None
default_field: str = "default_value"
# LLM only needs to provide required_field
`
## So sánh với các lựa chọn thay thế| Tính năng | Giảng viên | JSON thủ công | LangChain | DSPy |
|----------|-------------|-------------|----------|------|
| Loại An toàn | ✅ Có | ❌ Không | ⚠️ Một phần | ✅ Có |
| Xác thực tự động | ✅ Có | ❌ Không | ❌ Không | ⚠️ Có hạn |
| Tự động thử lại | ✅ Có | ❌ Không | ❌ Không | ✅ Có |
| Truyền phát | ✅ Có | ❌ Không | ✅ Có | ❌ Không |
| Đa nhà cung cấp | ✅ Có | ⚠️ Hướng dẫn sử dụng | ✅ Có | ✅ Có |
| Đường cong học tập | Thấp | Thấp | Trung bình | Cao |
**Thời điểm chọn người hướng dẫn:**
- Cần kết quả đầu ra có cấu trúc, được xác nhận
- Muốn có sự an toàn về kiểu và hỗ trợ IDE
- Yêu cầu thử lại tự động
- Xây dựng hệ thống trích xuất dữ liệu`**Khi nào nên chọn phương án thay thế:**
- DSPy: Cần tối ưu nhanh chóng
- LangChain: Xây dựng chuỗi phức tạp
- Thủ công: Chiết xuất đơn giản, một lần
## Tài nguyên
- **Tài liệu**: https://Python.useinstructor.com
- **GitHub**: https://GitHub.com/jxnl/instructor (15k+ sao)
- **Sách dạy nấu ăn**: https://Python.useinstructor.com/examples
- **Discord**: Hỗ trợ cộng đồng sẵn sàng
## Xem thêm
-
`references/validation.md
- Mẫu xác thực nâng cao
-
`references/providers.md
- Cấu hình dành riêng cho nhà cung cấp
-
`references/examples.md
- Các trường hợp sử dụng trong thế giới thực