{/* 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. */}
Hướng dẫn
Kiểm soát đầu ra LLM bằng biểu thức chính quy và ngữ pháp, đảm bảo việc tạo JSON/XML/mã hợp lệ, thực thi các định dạng có cấu trúc và xây dựng quy trình làm việc nhiều bước với Hướng dẫn - khung tạo ràng buộc của Microsoft Research
Siêu dữ liệu kỹ năng
| Nguồn | Tùy chọn — cài đặt với |
| `Hermes skills install official/mlops/guidance | |
| ` | |
| Đường dẫn |
optional-skills/mlops/guidance ` | | 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 |
guidance
,
transformers |
| Nền tảng | Linux, macOS, Windows |
| Thẻ |
Prompt Engineering
, `Guidance
, `Constrained Generation
, `Structured Output
, `JSON Validation
, `Grammar
, `Microsoft Research
, `Format Enforcement
,
Multi-Step Workflows |
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.
Hướng dẫn: Tạo LLM bị ràng buộc
Khi nào nên sử dụng kỹ năng này
Sử dụng Hướng dẫn khi bạn cần:
- Kiểm soát cú pháp đầu ra LLM bằng biểu thức chính quy hoặc ngữ pháp
- Đảm bảo việc tạo JSON/XML/mã hợp lệ
- Giảm độ trễ so với các phương pháp nhắc truyền thống
- Thực thi các định dạng có cấu trúc (ngày, email, ID, v.v.)
- Xây dựng quy trình làm việc nhiều bước với luồng điều khiển Pythonic
- Ngăn chặn kết quả đầu ra không hợp lệ thông qua các hạn chế về ngữ pháp`Sao GitHub: 18.000+ | Từ: Nghiên cứu của Microsoft
Cài đặt
# Base installation
pip install guidance
# With specific backends
pip install guidance[transformers] # Hugging Face models
pip install guidance[Llama_cpp] # Llama.cpp models
`
## Bắt đầu nhanh
### Ví dụ cơ bản: Thế hệ có cấu trúc
``` python
from guidance import models, gen
# Load model (supports OpenAI, Transformers, Llama.cpp)
lm = models.OpenAI("GPT-4")
# Generate with constraints
result = lm + "The cAPItal of France is " + gen("cAPItal", max_tokens=5)
print(result["cAPItal"]) # "Paris"
`
### Với Claude nhân loại
`Python
from guidance import models, gen, system, user, assistant
# Configure Claude
lm = models.Anthropic("Claude-sonnet-4-5-20250929")
# Use context managers for chat format
with system():
lm += "You are a helpful assistant."`with user():
lm += "What is the cAPItal of France?"`with assistant():
lm += gen(max_tokens=20)
`
## Khái niệm cốt lõi
### 1. Trình quản lý bối cảnh
Hướng dẫn sử dụng trình quản lý bối cảnh Pythonic cho các tương tác kiểu trò chuyện.
`Python
from guidance import system, user, assistant, gen`lm = models.Anthropic("Claude-sonnet-4-5-20250929")
# System message
with system():
lm += "You are a JSON generation expert."
# User message
with user():
lm += "Generate a person object with name and age."
# Assistant response
with assistant():
lm += gen("response", max_tokens=100)
print(lm["response"])
`
``**Quyền lợi:**
- Luồng trò chuyện tự nhiên
- Phân chia vai trò rõ ràng
- Dễ đọc và bảo trì
### 2. Thế hệ ràng buộc
Hướng dẫn đảm bảo kết quả đầu ra khớp với các mẫu được chỉ định bằng cách sử dụng biểu thức chính quy hoặc ngữ pháp.
#### Ràng buộc Regex
``` python
from guidance import models, gen`lm = models.Anthropic("Claude-sonnet-4-5-20250929")
# Constrain to valid email format
lm += "Email: " + gen("email", regex=r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]\\{2,}")
# Constrain to date format (YYYY-MM-DD)
lm += "Date: " + gen("date", regex=r"\d\\{4}-\d\\{2}-\d\\{2}")
# Constrain to phone number
lm += "Phone: " + gen("phone", regex=r"\d\\{3}-\d\\{3}-\d\\{4}")
print(lm["email"]) # Guaranteed valid email
print(lm["date"]) # Guaranteed YYYY-MM-DD format
`
``**Cách thức hoạt động:**
- Regex được chuyển đổi sang ngữ pháp ở cấp độ mã thông báo
- Mã thông báo không hợp lệ được lọc trong quá trình tạo
- Mô hình chỉ có thể tạo ra kết quả đầu ra phù hợp
#### Ràng buộc lựa chọn
``` python
from guidance import models, gen, select`lm = models.Anthropic("Claude-sonnet-4-5-20250929")
# Constrain to specific choices
lm += "Sentiment: " + select(["positive", "negative", "neutral"], name="sentiment")
# Multiple-choice selection
lm += "Best answer: " + select(
["A) Paris", "B) London", "C) Berlin", "D) Madrid"],
name="answer"
)
print(lm["sentiment"]) # One of: positive, negative, neutral
print(lm["answer"]) # One of: A, B, C, or D
`
### 3. Chữa bệnh bằng token
Hướng dẫn tự động "khắc phục" ranh giới mã thông báo giữa lời nhắc và việc tạo.
**Vấn đề:** Quá trình mã hóa tạo ra các ranh giới không tự nhiên.
`Python
# Without token healing
prompt = "The cAPItal of France is "
# Last token: " is "
# First generated token might be " Par" (with leading space)
# Result: "The cAPItal of France is Paris" (double space!)
`
``**Giải pháp:** Hướng dẫn sao lưu một mã thông báo và tạo lại.
``` python
from guidance import models, gen`lm = models.Anthropic("Claude-sonnet-4-5-20250929")
# Token healing enabled by default
lm += "The cAPItal of France is " + gen("cAPItal", max_tokens=5)
# Result: "The cAPItal of France is Paris" (correct spacing)
`
``**Quyền lợi:**
- Ranh giới văn bản tự nhiên
- Không có vấn đề về khoảng cách khó xử
- Hiệu suất mô hình tốt hơn (xem chuỗi mã thông báo tự nhiên)
### 4. Tạo dựa trên ngữ pháp
Xác định các cấu trúc phức tạp bằng cách sử dụng ngữ pháp không ngữ cảnh.
``` python
from guidance import models, gen`lm = models.Anthropic("Claude-sonnet-4-5-20250929")
# JSON grammar (simplified)
JSON_grammar = """
{
"name": <gen name regex="[A-Za-z ]+" max_tokens=20,
"age": <gen age regex="[0-9]+" max_tokens=3,
"email": <gen email regex="[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]\\{2,}" max_tokens=50
}
"""
# Generate valid JSON
lm += gen("person", grammar=JSON_grammar)
print(lm["person"]) # Guaranteed valid JSON structure
`
``**Trường hợp sử dụng:**
- Đầu ra có cấu trúc phức tạp
- Cấu trúc dữ liệu lồng nhau
- Cú pháp ngôn ngữ lập trình
- Ngôn ngữ dành riêng cho miền
### 5. Chức năng hướng dẫn
Tạo các mẫu thế hệ có thể tái sử dụng với trình trang trí
@guidance
.
``` python
from guidance import guidance, gen, models`@guidance
def generate_person(lm):
"""Generate a person with name and age."""
lm += "Name: " + gen("name", max_tokens=20, stop="\n")
lm += "\nAge: " + gen("age", regex=r"[0-9]+", max_tokens=3)
return lm
# Use the function
lm = models.Anthropic("Claude-sonnet-4-5-20250929")
lm = generate_person(lm)
print(lm["name"])
print(lm["age"])
`
``**Hàm có trạng thái:**
`Python
@guidance(stateless=False)
def react_agent(lm, question, tools, max_rounds=5):
"""ReAct agent with tool use."""
lm += f"Question: \{question}\n\n"`for i in range(max_rounds):
# Thought
lm += f"Thought \{i+1}: " + gen("thought", stop="\n")
# Action
lm += "\nAction: " + select(list(tools.keys()), name="action")
# Execute tool
tool_result = tools[lm["action"]]()
lm += f"\nObservation: \{tool_result}\n\n"
# Check if done
lm += "Done? " + select(["Yes", "No"], name="done")
if lm["done"] == "Yes":
break
# Final answer
lm += "\nFinal Answer: " + gen("answer", max_tokens=100)
return lm
`
## Cấu hình phụ trợ
### Claude nhân loại
``` python
from guidance import models`lm = models.Anthropic(
model="Claude-sonnet-4-5-20250929",
API_key="your-API-key" # Or set Anthropic_API_KEY env var
)
`
### OpenAI
`Python
lm = models.OpenAI(
model="GPT-4o-mini",
API_key="your-API-key" # Or set OpenAI_API_KEY env var
)
`
### Mô hình cục bộ (Transformers)
`Python
from guidance.models import Transformers`lm = Transformers(
"Microsoft/Phi-4-mini-instruct",
device="cuda" # Or "cpu"
)
`
### Mô hình cục bộ (Llama.cpp)
`Python
from guidance.models import LlamACPp`lm = LlamACPp(
model_path="/path/to/model.gguf",
n_ctx=4096,
n_gpu_layers=35
)
`
## Các mẫu phổ biến
### Mẫu 1: Tạo JSON
`Python
from guidance import models, gen, system, user, assistant`lm = models.Anthropic("Claude-sonnet-4-5-20250929")
with system():
lm += "You generate valid JSON."`with user():
lm += "Generate a user profile with name, age, and email."`with assistant():
lm += """{
"name": """ + gen("name", regex=r'"[A-Za-z ]+"', max_tokens=30) + """,
"age": """ + gen("age", regex=r"[0-9]+", max_tokens=3) + """,
"email": """ + gen("email", regex=r'"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]\\{2,}"', max_tokens=50) + """
}"""`print(lm) # Valid JSON guaranteed
`
### Mẫu 2: Phân loại
`Python
from guidance import models, gen, select`lm = models.Anthropic("Claude-sonnet-4-5-20250929")
text = "This product is amazing! I love it."`lm += f"Text: \{text}\n"
lm += "Sentiment: " + select(["positive", "negative", "neutral"], name="sentiment")
lm += "\nConfidence: " + gen("confidence", regex=r"[0-9]+", max_tokens=3) + "%"`print(f"Sentiment: \{lm['sentiment']}")
print(f"Confidence: \{lm['confidence']}%")
`
### Mẫu 3: Suy luận nhiều bước
`Python
from guidance import models, gen, guidance`@guidance
def chain_of_thought(lm, question):
"""Generate answer with step-by-step reasoning."""
lm += f"Question: \{question}\n\n"
# Generate multiple reasoning steps
for i in range(3):
lm += f"Step \{i+1}: " + gen(f"step_\{i+1}", stop="\n", max_tokens=100) + "\n"
# Final answer
lm += "\nTherefore, the answer is: " + gen("answer", max_tokens=50)
return lm`lm = models.Anthropic("Claude-sonnet-4-5-20250929")
lm = chain_of_thought(lm, "What is 15% of 200?")
print(lm["answer"])
`
### Mẫu 4: Tác nhân ReAct
`Python
from guidance import models, gen, select, guidance`@guidance(stateless=False)
def react_agent(lm, question):
"""ReAct agent with tool use."""
tools = {
"calculator": lambda expr: eval(expr),
"search": lambda query: f"Search results for: \{query}",
}`lm += f"Question: \{question}\n\n"`for round in range(5):
# Thought
lm += f"Thought: " + gen("thought", stop="\n") + "\n"
# Action selection
lm += "Action: " + select(["calculator", "search", "answer"], name="action")
if lm["action"] == "answer":
lm += "\nFinal Answer: " + gen("answer", max_tokens=100)
break
# Action input
lm += "\nAction Input: " + gen("action_input", stop="\n") + "\n"
# Execute tool
if lm["action"] in tools:
result = tools[lm["action"]](lm["action_input"])
lm += f"Observation: \{result}\n\n"`return lm`lm = models.Anthropic("Claude-sonnet-4-5-20250929")
lm = react_agent(lm, "What is 25 * 4 + 10?")
print(lm["answer"])
`
### Mẫu 5: Trích xuất dữ liệu
``` python
from guidance import models, gen, guidance`@guidance
def extract_entities(lm, text):
"""Extract structured entities from text."""
lm += f"Text: \{text}\n\n"
# Extract person
lm += "Person: " + gen("person", stop="\n", max_tokens=30) + "\n"
# Extract organization
lm += "Organization: " + gen("organization", stop="\n", max_tokens=30) + "\n"
# Extract date
lm += "Date: " + gen("date", regex=r"\d\\{4}-\d\\{2}-\d\\{2}", max_tokens=10) + "\n"
# Extract location
lm += "Location: " + gen("location", stop="\n", max_tokens=30) + "\n"`return lm`text = "Tim Cook announced at Apple Park on 2024-09-15 in Cupertino."`lm = models.Anthropic("Claude-sonnet-4-5-20250929")
lm = extract_entities(lm, text)
print(f"Person: \{lm['person']}")
print(f"Organization: \{lm['organization']}")
print(f"Date: \{lm['date']}")
print(f"Location: \{lm['location']}")
`
## Các phương pháp hay nhất
### 1. Sử dụng Regex để xác thực định dạng
`Python
# ✅ Good: Regex ensures valid format
lm += "Email: " + gen("email", regex=r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]\\{2,}")
# ❌ Bad: Free generation may produce invalid emails
lm += "Email: " + gen("email", max_tokens=50)
`
### 2. Sử dụng select() cho các danh mục cố định
``` python
# ✅ Good: Guaranteed valid category
lm += "Status: " + select(["pending", "approved", "rejected"], name="status")
# ❌ Bad: May generate typos or invalid values
lm += "Status: " + gen("status", max_tokens=20)
`
### 3. Tận dụng việc chữa lành mã thông báo
``` python
# Token healing is enabled by default
# No special action needed - just concatenate naturally
lm += "The cAPItal is " + gen("cAPItal") # Automatic healing
`
### 4. Sử dụng chuỗi dừng
``` python
# ✅ Good: Stop at newline for single-line outputs
lm += "Name: " + gen("name", stop="\n")
# ❌ Bad: May generate multiple lines
lm += "Name: " + gen("name", max_tokens=50)
`
### 5. Tạo các hàm có thể sử dụng lại
``` python
# ✅ Good: Reusable pattern
@guidance
def generate_person(lm):
lm += "Name: " + gen("name", stop="\n")
lm += "\nAge: " + gen("age", regex=r"[0-9]+")
return lm
# Use multiple times
lm = generate_person(lm)
lm += "\n\n"
lm = generate_person(lm)
`
### 6. Ràng buộc cân bằng
``` python
# ✅ Good: Reasonable constraints
lm += gen("name", regex=r"[A-Za-z ]+", max_tokens=30)
# ❌ Too strict: May fail or be very slow
lm += gen("name", regex=r"^(John|Jane)$", max_tokens=10)
`
## So sánh với các lựa chọn thay thế| Tính năng | Hướng dẫn | Giảng viên | Đề cương | LMQL |
|----------|----------|-------------|----------|------|
| Ràng buộc Regex | ✅ Có | ❌ Không | ✅ Có | ✅ Có |
| Hỗ trợ ngữ pháp | ✅ CFG | ❌ Không | ✅ CFG | ✅ CFG |
| Xác thực Pydantic | ❌ Không | ✅ Có | ✅ Có | ❌ Không |
| Chữa bệnh bằng mã thông báo | ✅ Có | ❌ Không | ✅ Có | ❌ Không |
| Mô hình địa phương | ✅ Có | ⚠️ Có hạn | ✅ Có | ✅ Có |
| Mô hình API | ✅ Có | ✅ Có | ⚠️ Có hạn | ✅ Có |
| Cú pháp Python | ✅ Có | ✅ Có | ✅ Có | ❌ Giống SQL |
| Đường cong học tập | Thấp | Thấp | Trung bình | Cao |
**Khi nào nên chọn Hướng dẫn:**
- Cần các ràng buộc về biểu thức chính quy/ngữ pháp
- Muốn chữa bệnh bằng token
- Xây dựng quy trình công việc phức tạp với luồng điều khiển
- Sử dụng mô hình cục bộ (Transformers, Llama.cpp)
- Thích cú pháp Pythonic hơn`**Khi nào nên chọn phương án thay thế:**
- Người hướng dẫn: Cần xác nhận Pydantic với tính năng thử lại tự động
- Đề cương: Cần xác thực lược đồ JSON
- LMQL: Ưu tiên cú pháp truy vấn khai báo
## Đặc tính hiệu suất`**Giảm độ trễ:**
- Nhanh hơn 30-50% so với nhắc nhở truyền thống đối với đầu ra bị hạn chế
- Chữa bệnh bằng mã thông báo làm giảm khả năng tái sinh không cần thiết
- Các hạn chế về ngữ pháp ngăn chặn việc tạo mã thông báo không hợp lệ`**Sử dụng bộ nhớ:**
- Chi phí tối thiểu so với thế hệ không bị giới hạn
- Biên soạn ngữ pháp được lưu trữ sau lần sử dụng đầu tiên
- Lọc mã thông báo hiệu quả tại thời điểm suy luận`**Hiệu quả của mã thông báo:**
- Ngăn chặn lãng phí mã thông báo trên đầu ra không hợp lệ
- Không cần thử lại vòng lặp
- Đường dẫn trực tiếp đến đầu ra hợp lệ
## Tài nguyên
- **Tài liệu**: https://guidance.readthedocs.io
- **GitHub**: https://GitHub.com/guidance-ai/guidance (18k+ sao)
- **Sổ tay**: https://GitHub.com/guidance-ai/guidance/tree/main/notebooks
- **Discord**: Hỗ trợ cộng đồng sẵn sàng
## Xem thêm
-
`references/constraints.md
- Các mẫu ngữ pháp và biểu thức chính quy toàn diện
-
`references/backends.md
- Cấu hình dành riêng cho phần phụ trợ
-
`references/examples.md
- Ví dụ sẵn sàng sản xuất