[ PROMPT_NODE_22908 ]
guidance
[ SKILL_DOCUMENTATION ]
# Guidance: 约束式 LLM 生成
## 何时使用此技能
当你需要以下功能时使用 Guidance:
- 使用正则表达式或语法**控制 LLM 输出语法**
- **保证有效的 JSON/XML/代码**生成
- **降低延迟**(相比传统提示词方法)
- **强制执行结构化格式**(日期、电子邮件、ID 等)
- 使用 Pythonic 控制流**构建多步工作流**
- 通过语法约束**防止无效输出**
**GitHub 星标**: 18,000+ | **来源**: 微软研究院
## 安装
bash
# 基础安装
pip install guidance
# 带有特定后端
pip install guidance[transformers] # Hugging Face 模型
pip install guidance[llama_cpp] # llama.cpp 模型
## 快速入门
### 基本示例:结构化生成
python
from guidance import models, gen
# 加载模型(支持 OpenAI, Transformers, llama.cpp)
lm = models.OpenAI("gpt-4")
# 带约束生成
result = lm + "The capital of France is " + gen("capital", max_tokens=5)
print(result["capital"]) # "Paris"
### 使用 Anthropic Claude
python
from guidance import models, gen, system, user, assistant
# 配置 Claude
lm = models.Anthropic("claude-sonnet-4-5-20250929")
# 使用上下文管理器进行聊天格式化
with system():
lm += "You are a helpful assistant."
with user():
lm += "What is the capital of France?"
with assistant():
lm += gen(max_tokens=20)
## 核心概念
### 1. 上下文管理器
Guidance 使用 Pythonic 上下文管理器进行聊天式交互。
python
from guidance import system, user, assistant, gen
lm = models.Anthropic("claude-sonnet-4-5-20250929")
# 系统消息
with system():
lm += "You are a JSON generation expert."
# 用户消息
with user():
lm += "Generate a person object with name and age."
# 助手响应
with assistant():
lm += gen("response", max_tokens=100)
print(lm["response"])
**优势:**
- 自然的聊天流程
- 清晰的角色分离
- 易于阅读和维护
### 2. 约束式生成
Guidance 使用正则表达式或语法确保输出符合指定模式。
#### 正则表达式约束
python
from guidance import models, gen
lm = models.Anthropic("claude-sonnet-4-5-20250929")
# 约束为有效的电子邮件格式
lm += "Email: " + gen("email", regex=r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}")
# 约束为日期格式 (YYYY-MM-DD)
lm += "Date: " + gen("date", regex=r"d{4}-d{2}-d{2}")
# 约束为电话号码
lm += "Phone: " + gen("ph