Loading...

文章背景图

DSPy:用编程而非提示词来训练语言模型

2026-10-27
0
- 字
- 分钟
|

DSPy

官方信息表

项目 内容
项目名称 DSPy
仓库地址 stanfordnlp/dspy
官方文档 dspy.ai
开源协议 MIT
最新更新 2026-10-27
定位 声明式自改进 Python 框架

项目背景

DSPy 由 Stanford NLP 团队开发,核心思想是「编程而非提示词」:你不再手写和调试脆弱的提示词字符串,而是写模块化的 Python 代码,DSPy 自动为你优化提示词和模型权重。无论是分类器、RAG 管线还是智能体循环,都能用 DSPy 组合并自动优化。

核心特性

  • 编程而非提示词:把提示词当作可优化参数
  • Signature:声明输入输出 schema
  • Module:链式调用组合
  • 优化器家族:BootstrapFewShot、MIPRO、BootstrapFinetune
  • 模型无关:支持任意 LLM
  • 可测试可迭代:像传统软件工程一样版本化

环境要求

  • Python 3.9+
  • 任意 LLM API

部署步骤

pip install dspy

最新开发版:

pip install git+https://github.com/stanfordnlp/dspy.git

使用方法

import dspy
lm = dspy.LM("openai/gpt-4o")
dspy.configure(lm=lm)

class Answer(dspy.Signature):
    question: str = dspy.InputField()
    answer: str = dspy.OutputField()

cot = dspy.ChainOfThought(Answer)
print(cot(question="法国首都是哪里").answer)

优化器家族

DSPy 提供多种优化器:BootstrapFewShot 自动选示例;MIPRO 联合优化提示词和示例;BootstrapFinetune 蒸馏小模型。你只需要准备一个带标注的小数据集,DSPy 自动搜索最优提示词组合。

常见问题 FAQ

Q:DSPy 需要训练自己的模型吗? A:默认只优化提示词;也支持微调小模型。

Q:和 LangChain 比有什么区别? A:LangChain 是组件库,DSPy 把提示词当作可优化的参数。

Q:支持中文任务吗? A:支持,模型无关,任意中文 LLM 即可。

安装要求

pip install dspy
# 最新开发版
pip install git+https://github.com/stanfordnlp/dspy.git

更多使用示例

import dspy
dspy.configure(lm=dspy.LM("openai/gpt-4o"))

class Answer(dspy.Signature):
    question: str = dspy.InputField()
    answer: str = dspy.OutputField()

cot = dspy.ChainOfThought(Answer)
print(cot(question="法国首都是哪里").answer)

跳转链接

评论交流

文章目录