[ PROMPT_NODE_22904 ]
Prompt Engineering Dspy 模块
[ SKILL_DOCUMENTATION ]
# DSPy 模块
DSPy 内置模块的完整指南,用于语言模型编程。
## 模块基础
DSPy 模块是受 PyTorch 神经网络模块启发的组合构建块:
- 具有可学习的参数(提示词、少样本示例)
- 可以使用 Python 控制流进行组合
- 通用化以处理任何签名
- 可使用 DSPy 优化器进行优化
### 基础模块模式
python
import dspy
class CustomModule(dspy.Module):
def __init__(self):
super().__init__()
# 初始化子模块
self.predictor = dspy.Predict("input -> output")
def forward(self, input):
# 模块逻辑
result = self.predictor(input=input)
return result
## 核心模块
### dspy.Predict
**基础预测模块** - 在没有推理步骤的情况下进行语言模型调用。
python
# 内联签名
qa = dspy.Predict("question -> answer")
result = qa(question="What is 2+2?")
# 类签名
class QA(dspy.Signature):
"""简洁地回答问题。"""
question = dspy.InputField()
answer = dspy.OutputField(desc="简短、事实性的回答")
qa = dspy.Predict(QA)
result = qa(question="What is the capital of France?")
print(result.answer) # "Paris"
**使用场景:**
- 简单、直接的预测
- 不需要推理步骤
- 需要快速响应
### dspy.ChainOfThought
**逐步推理** - 在回答之前生成推理过程。
**参数:**
- `signature`: 任务签名
- `rationale_field`: 自定义推理字段(可选)
- `rationale_field_type`: 推理字段类型(默认:`str`)
python
# 基本用法
cot = dspy.ChainOfThought("question -> answer")
result = cot(question="If I have 5 apples and give away 2, how many remain?")
print(result.rationale) # "Let's think step by step..."
print(result.answer) # "3"
# 自定义推理字段
cot = dspy.ChainOfThought(
signature="problem -> solution",
rationale_field=dspy.OutputField(
prefix="Reasoning: Let's break this down step by step to"
)
)
**使用场景:**
- 复杂的推理任务
- 数学应用题
- 逻辑推演
- 质量优先于速度
**性能:**
- 比 Predict 慢约 2 倍
- 在推理任务上准确率显著提高
### dspy.ProgramOfThought
**基于代码的推理** - 生成并执行 Python 代码。
python
pot = dspy.ProgramOfThought("question -> answer")
result = pot(question="What is 15% of 240?")
# 内部生成:answer = 240 * 0.15
# 执行代码并返回结果
print(result.