DSPy:声明式编程优化LLM提示词的框架
DSPy是一个用编程范式替代手工提示词的LLM开发框架。请解释DSPy的核心概念(Signature、Module、Teleprompter/Optimizer),对比DSPy与传统提示工程的工作方式差异,以及它如何处理多步骤推理的优化。
回答
专业代码师
DSPy核心概念:
1. Signature(签名):
- 声明式定义LLM任务的输入/输出
- 例:
"question -> answer"或"context, question -> answer: float" - 框架自动生成提示词(无需手动编写)
class GenerateAnswer(dspy.Signature):
"""Answer questions with short factoid answers."""
context = dspy.InputField()
question = dspy.InputField()
answer = dspy.OutputField(desc="often between 1 and 5 words")
2. Module(模块):
- 可组合的LLM调用单元
- 内置:dspy.Predict、dspy.ChainOfThought、dspy.ReAct、dspy.RAG
- 支持嵌套和多步骤pipeline
3. Teleprompter / Optimizer(优化器):
| 优化器 | 策略 | 适用场景 |
|---|---|---|
LabeledFewShot | 选择最优few-shot示例 | 小数据集 |
BootstrapFewShot | 用LLM自举生成示例 | 少量标注数据 |
BootstrapFewShotWithRandomSearch | 随机搜索最佳配置 | 中等数据 |
MIPROv2 | 多指令提示优化 | 复杂任务 |
COPRO | 指令优化 + 提示词优化 | 通用场景 |
与传统提示工程的对比:
| 维度 | 传统提示工程 | DSPy |
|---|---|---|
| 提示词 | 手工编写、调试 | 自动生成、优化 |
| 流水线 | 手动拼接LLM调用 | 声明式模块组合 |
| 可编程性 | 无(纯文本) | Python代码 |
| 优化 | 人工试错 | 自动搜索 |
| 可复现 | 差 | 好 |
多步骤推理优化:
- DSPy自动优化每个子模块的提示词和示例
- 通过BootstrapFewShot为中间步骤生成合成示例
- 端到端优化整个pipeline而非单个模块
代码示例:
# RAG模块:自动优化检索+生成
class RAG(dspy.Module):
def __init__(self, num_passages=3):
self.retrieve = dspy.Retrieve(k=num_passages)
self.generate_answer = dspy.ChainOfThought("context, question -> answer")
def forward(self, question):
context = self.retrieve(question).passages
return self.generate_answer(context=context, question=question)
teleprompter = dspy.BootstrapFewShot()
compiled_rag = teleprompter.compile(RAG(), trainset=trainset)