DSPy

活跃
GitHub Python MIT

简介

DSPy 是声明式 LLM 编程框架,强调可优化的提示与程序结构,适合构建复杂 Agent 流程。

核心特性

  • 声明式 LLM 编程 — 用 Python 代码而非提示词定义 LM 调用逻辑,实现模块化 AI 系统构建
  • 自动提示优化 — 通过 DSPy Compiler 自动优化 prompt 和 few-shot 示例,无需手动调参
  • 模块化管道组合 — 支持 ChainOfThought、ReAct、multi-hop 等模块的自由组合,构建复杂推理链
  • RAG 流水线支持 — 内置检索增强生成管道,支持向量检索、重排序等组件的声明式编排
  • Agent 循环框架 — 支持构建 Agent loop,将工具调用、推理、检索编排为可优化的程序
  • 可微分权重优化 — 支持对 LM 进行 fine-tuning,同时优化 prompt 和模型权重

适用场景

💡 构建分类和信息抽取管道 — 用声明式方式定义分类器或信息抽取器,通过 Compiler 自动优化准确率
💡 多步 RAG 系统 — 编排检索、重排、生成等多步流程,自动优化每一步的 prompt
💡 Agent 工具调用流程 — 将工具选择、参数提取、结果整合编排为可优化的 Agent 管道
💡 学术研究和基准测试 — 快速搭建 NLP 任务管道并进行系统性优化和评估

快速开始

pip install dspy

import dspy

# Configure your LM
dspy.configure(lm=dspy.LM('openai/gpt-4o-mini'))

# Define a simple module
class RAG(dspy.Module):
    def __init__(self, passages_per_query=3):
        self.retrieve = dspy.Retrieve(k=passages_per_query)
        self.generate = dspy.ChainOfThought('context, question -> answer')

    def forward(self, question):
        context = self.retrieve(question).passages
        return self.generate(context=context, question=question)

rag = RAG()
result = rag(question='What is DSPy?')
print(result.answer)

相关项目

相关文章