DSPy 完全指南:Stanford Prompt 编程框架用 ofox 跑(2026)

DSPy 完全指南:Stanford Prompt 编程框架用 ofox 跑(2026)

TL;DR — DSPy 是 Stanford NLP 开发的 AI 框架,核心理念是”用代码编程而非调试 prompt”。你定义任务的输入输出(Signature)、选择执行策略(Module),DSPy 自动生成 prompt 并通过优化器提升性能。配合 ofox API 接入 Claude、GPT、Gemini 等模型。

DSPy 是什么

DSPy 是 Stanford NLP 实验室开发的模块化 AI 框架。核心目标是让开发者从”调试 prompt 字符串”转向”编写结构化代码”。

传统 prompt 工程的问题:

  • prompt 字符串难维护,版本控制麻烦
  • 换模型就得重新调 prompt
  • 多步骤任务的 prompt 组合复杂
  • 性能优化靠人工试错

DSPy 怎么解决:

  • Signature:声明式定义输入输出
  • Module:封装执行策略(ChainOfThought、ReAct 等)
  • Optimizer:自动优化 prompt 和模型权重
  • Composability:模块化组合多步骤流程

核心概念

Signature(签名)

Signature 定义任务的输入输出规范,DSPy 根据它自动生成 prompt。

# 传统方式:手写 prompt
prompt = "Given the question: {question}, provide a detailed answer."

# DSPy 方式:声明式 Signature
class QA(dspy.Signature):
    """Answer questions with detailed explanations."""
    question = dspy.InputField()
    answer = dspy.OutputField(desc="detailed answer with reasoning")

好处:

  • 类型安全,IDE 自动补全
  • 不用手动拼接 prompt 字符串
  • 换模型时 Signature 不变,DSPy 自动适配

Module(模块)

Module 是执行策略的封装,常用的有:

ChainOfThought:让模型先推理再回答

cot = dspy.ChainOfThought(QA)
response = cot(question="What is DSPy?")
print(response.answer)

ReAct:结合推理和工具调用

react = dspy.ReAct(QA)
response = react(question="What's the weather in Beijing?")

Predict:直接预测输出

predict = dspy.Predict(QA)
response = predict(question="Explain quantum computing")

Optimizer(优化器)

优化器根据训练样本和评估指标自动提升系统性能。

MIPROv2:多指令提示优化

from dspy.teleprompt import MIPROv2

# 定义评估指标
def accuracy_metric(example, pred, trace=None):
    return example.answer.lower() == pred.answer.lower()

# 准备训练数据
trainset = [
    dspy.Example(question="What is 2+2?", answer="4").with_inputs("question"),
    dspy.Example(question="Capital of France?", answer="Paris").with_inputs("question"),
]

# 运行优化器
optimizer = MIPROv2(metric=accuracy_metric, num_candidates=10)
optimized_cot = optimizer.compile(cot, trainset=trainset)

BootstrapFinetune:合成 few-shot 示例并微调

from dspy.teleprompt import BootstrapFinetune

optimizer = BootstrapFinetune(metric=accuracy_metric)
optimized_program = optimizer.compile(cot, trainset=trainset)

优化器通常能提升 20-30% 性能,不用手动调 prompt。

用 ofox API 接入 DSPy

DSPy 支持数十种 LM 提供商,ofox API 提供统一接口接入所有主流模型。

安装 DSPy

pip install dspy-ai

配置 ofox API

DSPy 使用 OpenAI 兼容接口,ofox 提供统一的 API 端点:

import dspy
import os

# 配置 ofox API
lm = dspy.LM(
    model="openai/gpt-5.4",  # 或 anthropic/claude-opus-4-7, google/gemini-3.1-pro-preview
    api_base="https://api.ofox.ai/v1",
    api_key=os.getenv("OFOX_API_KEY")
)

dspy.configure(lm=lm)

支持的模型

ofox 上架的所有模型都可以通过 DSPy 调用:

模型系列模型 ID适用场景
OpenAIopenai/gpt-5.4通用任务、复杂推理
Anthropicanthropic/claude-opus-4-7长文本、编程、分析
Googlegoogle/gemini-3.1-pro-preview多模态、快速响应
DeepSeekdeepseek/deepseek-v4-pro编程、数学推理
智谱z-ai/glm-5中文理解、代码生成

完整模型列表:https://ofox.ai/zh/models

多模型切换

换模型不用改代码:

# 切换到 Claude Opus 4.7
lm_claude = dspy.LM(
    model="anthropic/claude-opus-4-7",
    api_base="https://api.ofox.ai/v1",
    api_key=os.getenv("OFOX_API_KEY")
)
dspy.configure(lm=lm_claude)

# 同样的代码,不同的模型
response = cot(question="Explain DSPy")

实战:文本分类系统

用 DSPy 搭一个情感分类系统,展示 Module 组合和优化器使用。

定义 Signature

class ClassifySentiment(dspy.Signature):
    """Classify the sentiment of a text."""
    text = dspy.InputField()
    sentiment = dspy.OutputField(desc="positive, negative, or neutral")
    confidence = dspy.OutputField(desc="confidence score 0-1")

构建分类 Module

class SentimentClassifier(dspy.Module):
    def __init__(self):
        super().__init__()
        self.classify = dspy.ChainOfThought(ClassifySentiment)
    
    def forward(self, text):
        return self.classify(text=text)

运行和优化

# 初始化分类器
classifier = SentimentClassifier()

# 测试
response = classifier(text="DSPy makes prompt engineering so much easier!")
print(f"Sentiment: {response.sentiment}, Confidence: {response.confidence}")

# 优化(需要训练数据)
trainset = [
    dspy.Example(
        text="This product is amazing!",
        sentiment="positive"
    ).with_inputs("text"),
    dspy.Example(
        text="Terrible experience, would not recommend.",
        sentiment="negative"
    ).with_inputs("text"),
]

def accuracy_metric(example, pred, trace=None):
    return example.sentiment.lower() == pred.sentiment.lower()

optimizer = MIPROv2(metric=accuracy_metric, num_candidates=10)
optimized_classifier = optimizer.compile(classifier, trainset=trainset)

多步骤流程组合

DSPy 支持将多个 Module 组合成复杂流程。

案例:多步骤文本处理

class TextProcessor(dspy.Module):
    def __init__(self):
        super().__init__()
        self.summarize = dspy.ChainOfThought("text -> summary")
        self.extract_keywords = dspy.Predict("summary -> keywords")
        self.classify = dspy.ChainOfThought(ClassifySentiment)
    
    def forward(self, text):
        # 第一步:生成摘要
        summary = self.summarize(text=text).summary
        
        # 第二步:提取关键词
        keywords = self.extract_keywords(summary=summary).keywords
        
        # 第三步:情感分类
        sentiment = self.classify(text=summary)
        
        return dspy.Prediction(
            summary=summary,
            keywords=keywords,
            sentiment=sentiment.sentiment
        )

端到端优化

# 优化整个流程
processor = TextProcessor()
optimizer = MIPROv2(metric=accuracy_metric)
optimized_processor = optimizer.compile(processor, trainset=trainset)

优化器会自动调整每个步骤的 prompt,全局优化。

成本优化

用 ofox API 跑 DSPy 可以降低成本。

模型路由

根据任务复杂度选择不同模型:

def get_lm(complexity):
    if complexity == "simple":
        return dspy.LM(model="openai/gpt-5.4-mini", api_base="https://api.ofox.ai/v1", api_key=os.getenv("OFOX_API_KEY"))
    elif complexity == "complex":
        return dspy.LM(model="anthropic/claude-opus-4-7", api_base="https://api.ofox.ai/v1", api_key=os.getenv("OFOX_API_KEY"))

# 简单任务用 mini 模型
dspy.configure(lm=get_lm("simple"))
response = predict(question="What is 2+2?")

# 复杂任务用 Opus
dspy.configure(lm=get_lm("complex"))
response = cot(question="Explain quantum entanglement")

批量调用

DSPy 支持批量处理,ofox API 自动优化并发:

questions = ["What is AI?", "Explain ML", "Define NLP"]
responses = [cot(question=q) for q in questions]

常见问题

DSPy 适合什么场景?

适合:

  • 多步骤 AI 流程(RAG、Agent、工作流)
  • 需要频繁切换模型的项目
  • 对性能有优化需求的生产系统

不适合:

  • 简单的单次 prompt 调用(直接用 API 更快)

如何调试 DSPy 程序?

# 查看模块内部状态
response = cot(question="Test")
print(response.rationale)  # ChainOfThought 的推理过程

DSPy 会在执行过程中记录每个模块的输入输出,你可以通过访问返回对象的属性来查看中间结果。

优化器需要多少训练数据?

  • MIPROv2:10-50 个样本即可
  • BootstrapFinetune:50-200 个样本
  • 数据质量比数量更重要

ofox API 和官方 API 有什么区别?

对比项ofox API官方 API
接入方式统一 OpenAI 兼容接口各厂商独立接口
支付方式支付宝/微信信用卡
国内访问直连,无需代理需要代理
价格有竞争力官方定价

相关资源

下一步