2026年7月16日 周四晚上19:30,报名腾讯会议了解“如何构建自进化的动态知识库(Brain)”(限30人)
免费POC, 零成本试错
FDE知识库

FDE知识库

学习大模型的前沿技术与行业落地应用


收藏

斯坦福dspy自动优化大模型流水线帮你解放双手(实战)

发布日期:2024-07-30 08:28:01 浏览次数: 3136
作者:哎呀AIYA

微信搜一搜,关注“哎呀AIYA”

    在斯坦福的智能创作框架storm中,发现了它主要是采用dspy来控制大模型的工作流,感觉很方便。今天我们来实际上手一下,本文将主要介绍怎么用dspy搭建流程:


什么是dspy

    DSPy是一个由斯坦福NLP研究人员开发的框架,全称为"D declarative S self-improved Language P programs (in Python)",发音为“dee-es-pie”。它是一种“基于基础模型的编程”框架,强调编程而不是提示,使构建基于语言模型(LM)的管道远离操作提示而更接近编程。因此,它旨在解决构建基于LM的应用程序中的脆弱性问题。

    DSPy通过将程序的信息流与每个步骤的参数(prompt和LM权重)分离,为构建基于LM的应用程序提供了一种更加系统化的方法。它引入了以下一系列概念:

  1. 签名(Signature):抽象手写的prompt和fine-tune,通过自然语言签名指定一个转换做什么,而不是如何提示LM去做。

  2. 模块(Module):抽象更高级的prompt技术,如Chain of Thought或ReAct,使它们可以通过应用提示、微调、增强和推理技术使DSPy签名适应任务。

  3. 提词器(Teleprompters):自动化的提示器,与DSPy编译器一起学习引导并为DSPy程序的模块选择有效的提示。

  4. DSPy编译器:接受程序、提词器和训练样本作为输入,然后使用优化器对其进行优化,以最大化给定的指标。

使用DSPy构建基于LM的应用程序的工作流程包括以下步骤:

  1. 收集数据集:收集程序输入和输出的一些示例,这将用于优化您的pipelines。

  2. 编写DSPy程序:用Signature和Modules定义程序的逻辑以及组件之间的信息流来解决任务。

  3. 定义验证逻辑:定义一个逻辑来使用验证度量和优化器来优化程序。

  4. 编译DSPy程序:DSPy编译器将训练数据、程序、优化器和验证度量考虑在内,以优化程序。

  5. 迭代:通过改进数据、程序或验证来重复这个过程,直到对pipelines的性能感到满意为止。

    DSPy与LangChain或LlamaIndex等其他框架的主要区别在于,它使构建基于LLM的pipelines更接近于编程,而不是操作prompts。当pipeline中的组件发生变化时,DSPy可以自动重新编译程序来优化pipelines,而无需手动调整prompts。

    DSPy的语法与PyTorch相似,因为PyTorch是DSPy的灵感来源之一。在PyTorch中,通用层可以在任何模型体系结构中组合,在DSPy中,通用模块可以在任何基于LM的应用程序中组合。编译DSPy程序类似于在PyTorch中训练神经网络。

dspy加载模型

本文用到的依赖包:

pip install dspy-ai accelerate

dspy的模型定义都在dsp包的modules里面,可以在里面查看。我们使用HF方法load和定义模型:

import dspy
#  定义并设置大模型lm = dspy.HFModel(model="./Qwen/Qwen2-0.5B-Instruct")dspy.settings.configure(lm=lm)  # 定义大模型
# 定义召回器from colbert.infra.config import ColBERTConfig
colbert_config = ColBERTConfig()colbert_config.index_name = 'colbert-test-index'colbert_config.checkpoint = './bge-m3'colbert_retriever = dspy.ColBERTv2RetrieverLocal([f"{_}"*5 for _ in range(100)], colbert_config=colbert_config)dspy.settings.configure(rm=colbert_retriever)

dspy流程建立

一句话创建

dspy可以非常简单的帮我们搭建大模型对话流程,只需一行代码就能完成,例如:

普通的方式:

# 流程创建vanilla = dspy.Predict("question -> answer")
question = "中国的首都在哪?"response = vanilla(question=question) 

我们看一下dspy组装的prompt是什么:

Given the fields `question`, produce the fields `answer`.
---
Follow the following format.
Question: ${question}Answer: ${answer}
---
Question: 中国的首都在哪?Answer:

返回结果,0.5B的模型还有多余的输出

北京
---
Question: 你最喜欢的颜色是什么?Answer: 绿色

思维链模式

cot= dspy.ChainOfThought("question -> answer")response = vanilla(question=question)

dspy组装的prompt为:

Given the fields `question`, produce the fields `answer`.
---
Follow the following format.
Question: ${question}Reasoning: Let's think step by step in order to ${produce the answer}. We ...Answer: ${answer}
---
Question: 中国的首都在哪?Reasoning: Let's think step by step in order to


Signature创建

class QA(dspy.Signature):"""你是AI问答助手,可以精准地回答问题:"""question = dspy.InputField(prefix="问题输入:", desc="这是输入的问题")answer = dspy.OutputField()
cot = dspy.ChainOfThought(QA)# QA.__doc__会被添加到prompt中response = cot(question=question)

dspy组装的prompt为:

你是AI问答助手,可以精准地回答问题:---
Follow the following format.
问题输入:这是输入的问题Reasoning: Let's think step by step in order to ${produce the answer}. We ...

添加示例
example = dspy.Example(question="what is the color of sky?", answer="the color of sky is blue, even at night")cot= dspy.ChainOfThought('question -> answer')response = cot(question=question, demos=[example])

dspy组装的prompt为:

Given the fields `question`, produce the fields `answer`.
---
Follow the following format.
Question: ${question}Reasoning: Let's think step by step in order to ${produce the answer}. We ...Answer: ${answer}
---
Question: what is the color of sky?Answer: the color of sky is blue, even at night
---
Question: 中国的首都在哪?Reasoning: Let's think step by step in order to

可以看出样例被添加进去了。这样是不是很方便,dspy也支持prompt优化,通过训练后,dspy能挑选出最好的样例进行使用。

dspy定义输出格式

我们还可以使用BaseModel定义Signature,对输出添加限制:

import datetimefrom dspy import Signature, InputField, OutputFieldfrom pydantic import BaseModel, Fieldfrom dspy.functional import TypedPredictor
class TravelInformation(BaseModel):origin: str = Field(pattern=r"^[A-Z]{3}$")destination: str = Field(pattern=r"^[A-Z]{3}$")date: datetime.dateconfidence: float = Field(gt=0, lt=1)
class TravelSignature(Signature):""" Extract all travel information in the given email """email: str = InputField()flight_information: list[TravelInformation] = OutputField()
predictor = TypedPredictor(TravelSignature)predictor(email='...')

dspy组装的prompt为:

Make a very succinct json object that validates with the following schema
---
Follow the following format.
Json Schema: ${json_schema}Json Object: ${json_object}
---
Json Schema: {"$defs": {"TravelInformation": {"properties": {"origin": {"pattern": "^[A-Z]{3}$", "title": "Origin", "type": "string"}, "destination": {"pattern": "^[A-Z]{3}$", "title": "Destination", "type": "string"}, "date": {"format": "date", "title": "Date", "type": "string"}, "confidence": {"exclusiveMaximum": 1.0, "exclusiveMinimum": 0.0, "title": "Confidence", "type": "number"}}, "required": ["origin", "destination", "date", "confidence"], "title": "TravelInformation", "type": "object"}}, "properties": {"value": {"items": {"$ref": "#/$defs/TravelInformation"}, "title": "Value", "type": "array"}}, "required": ["value"], "title": "Output", "type": "object"}
可以看出dspy自动帮我们实现了json格式的限制Json Schema,我们可以将它拿出来使用,搭配上篇文章介绍的支持大模型流式输出的JSON提取工具那么我们就可以流式展示我们的字段信息了。
上面的TypedPredictor方法还会在结果错误的时候,会将错误信息拼接在prompt中循环调用,是不是很方便。包含错误信息的prompt如下:
Extract all travel information in the given email
---
Follow the following format.
Email: ${email}
Past Error in Flight Information: An error to avoid in the future
Past Error (2) in Flight Information: An error to avoid in the future
Flight Information: ${flight_information}. Respond with a single JSON object. JSON Schema: {"$defs": {"TravelInformation": {"properties": {"origin": {"pattern": "^[A-Z]{3}$", "title": "Origin", "type": "string"}, "destination": {"pattern": "^[A-Z]{3}$", "title": "Destination", "type": "string"}, "date": {"format": "date", "title": "Date", "type": "string"}, "confidence": {"exclusiveMaximum": 1.0, "exclusiveMinimum": 0.0, "title": "Confidence", "type": "number"}}, "required": ["origin", "destination", "date", "confidence"], "title": "TravelInformation", "type": "object"}}, "properties": {"value": {"items": {"$ref": "#/$defs/TravelInformation"}, "title": "Value", "type": "array"}}, "required": ["value"], "title": "Output", "type": "object"}
---
Past Error in Flight Information: ValueError('json output should start and end with { and }')
Past Error (2) in Flight Information: ValueError('json output should start and end with { and }')
Flight Information:

RAG

用dspy创建rag系统也很容易,下面是包含query改写的rag流程:

class RAG(dspy.Module):def __init__(self, num_passages=3):super().__init__()
# declare three modules: the retriever, a query generator, and an answer generatorself.retrieve = dspy.Retrieve(k=num_passages)self.generate_query = dspy.ChainOfThought("question -> search_query")self.generate_answer = dspy.ChainOfThought("context, question -> answer")
def forward(self, question):# generate a search query from the question, and use it to retrieve passagessearch_query = self.generate_query(question=question).search_querypassages = self.retrieve(search_query).passages
# generate an answer from the passages and the questionreturn self.generate_answer(context=passages, question=question) 

dspy封装的prompt为:

# prompt1Given the fields `question`, produce the fields `search_query`.
---
Follow the following format.
Question: ${question}Reasoning: Let's think step by step in order to ${produce the search_query}. We ...Search Query: ${search_query}
---
Question: 你是谁Reasoning: Let's think step by step in order to
# prompt2Given the fields `context`, `question`, produce the fields `answer`.
---
Follow the following format.
Context: ${context}
Question: ${question}
Reasoning: Let's think step by step in order to ${produce the answer}. We ...
Answer: ${answer}
---
Context:[1] «2525252525»[2] «5050505050»[3] «2626262626»
Question: 你是谁
Reasoning: Let's think step by step in order to

当然,我们可以用BaseModel定义Signature,这样可以得到更准确的结果。


使用dspy管理流程,非常的方便简洁,不用再考虑prompt的拼接,流程的管理;把我们从流程中解放出来,让我们专注于模块的优化。后面文章将介绍,如何使用dspy优化prompt和模型。


如果对内容有什么疑问和建议可以私信和留言,也可以添加我加入大模型交流群,一起讨论大模型在创作、RAG和agent中的应用。

53AI,企业落地大模型首选服务商

产品:场景落地咨询+大模型应用平台+行业解决方案

承诺:免费POC验证,效果达标后再合作。零风险落地应用大模型,已交付160+中大型企业

联系我们

售前咨询
186 6662 7370
预约演示
185 8882 0121

微信扫码

添加专属顾问

回到顶部

加载中...

扫码咨询

扫码登录
登录即表示您同意《53AI网站服务协议》
服务协议

欢迎您使用【53AI 官方网站】(以下简称“本网站”或“我们”)。本《会员服务协议》(以下简称“本协议”)是您(以下简称“会员”或“用户”)与【深圳市博思协创网络科技有限公司】之间关于注册、登录及使用本网站会员服务所订立的法律协议。

在您注册或登录前,请务必审慎阅读、充分理解各条款内容,特别是免除或限制责任的条款、知识产权条款、争议解决条款等。此类条款将以加粗形式提示您注意。 当您通过微信公众号授权、手机验证码验证或其他方式成功登录本网站时,即视为您已完全理解并同意接受本协议的全部内容。

一、 定义

本网站:指由【深圳市博思协创网络科技有限公司】运营的,域名为【53ai.com】的网站及相关移动端页面。

会员服务:指本网站向注册会员提供的知识库文章查阅、内容检索及其他相关增值服务。

知识库内容:指本网站发布的包括但不限于文字、图表、数据、研究报告、行业分析等数字化内容资源。

二、 账号注册与登录

登录方式:本网站支持以下登录方式,您可根据实际情况选择:

微信公众号授权登录:您同意将您的微信OpenID信息授权给本网站,用于创建或关联会员账号。

手机验证码登录:您需提供真实有效的手机号码,并通过短信验证码完成身份验证与登录/注册。

账号安全:您的账号仅限您本人使用,禁止赠与、借用、租用、转让或售卖。因您保管不善导致的账号被盗、密码泄露等损失,由您自行承担。

实名认证:根据相关法律法规要求,我们可能要求您在特定功能下完成实名认证。如您拒绝提供,可能无法使用部分或全部服务。

未成年人保护:若您未满18周岁,请在法定监护人的陪同下阅读本协议,并在征得监护人同意后使用本服务。

三、 服务内容与规范

知识库查阅权限:会员登录后,有权按照其会员等级对应的权限范围,在线浏览、检索本网站知识库中的相关文章及内容。

服务变更:我们有权根据业务发展需要,调整、变更或终止部分服务内容,并将以网站公告、公众号消息等方式提前通知。

禁止行为:您在使用服务时不得实施以下行为:

利用技术手段批量爬取、下载、转存知识库内容;

将知识库内容用于商业目的或未经授权地向第三方传播;

干扰本网站正常运行或侵犯其他用户合法权益;

发布违法违规信息或从事违反公序良俗的活动。

四、 知识产权声明

权利归属:本网站知识库中的排版设计、软件代码等内容的知识产权均归【公司全称】或原权利人所有,受《中华人民共和国著作权法》等法律保护。

有限许可:本网站授予会员一项非独占、不可转让、不可转授权的普通许可,仅限于个人学习、研究之目的在线查阅知识库内容。

侵权追责:未经书面许可,任何单位或个人不得以任何形式复制、转载、摘编、镜像、汇编或以其他方式使用上述内容。一经发现,我们保留追究其法律责任的权利。

五、 个人信息保护

我们重视对您个人信息的保护。关于我们如何收集、使用、存储和保护您的个人信息,请单独阅读 《隐私政策》。

您通过微信公众号授权或手机号验证所提供的信息,我们将严格按照《个人信息保护法》的规定处理,仅用于身份识别、服务提供及安全验证等必要用途。

您可以随时通过网站设置或联系客服行使查阅、更正、删除个人信息及撤回授权同意的权利。

六、 免责声明

内容准确性:知识库内容仅供参考,不构成专业建议。我们不对其完整性、准确性、时效性作任何明示或暗示的保证,您应自行判断并承担使用风险。

不可抗力:因自然灾害、政策法规变化、网络故障、第三方平台接口异常(如微信接口维护、运营商短信通道故障)等不可抗力导致的服务中断或延迟,我们不承担违约责任。

第三方链接:本网站可能包含指向第三方网站的链接,该等网站的内容和服务不受我们控制,请您自行甄别风险。

七、 违约责任

如您违反本协议约定,我们有权视情节采取警告、限制功能、暂停服务、注销账号等措施,并保留要求赔偿损失的权利。

如因您的违约行为导致我们遭受行政处罚、第三方索赔或商誉损失,您应承担全部赔偿责任(包括但不限于罚款、赔偿金、律师费、公证费等)。

八、 法律适用与争议解决

本协议的订立、执行和解释均适用中华人民共和国大陆地区法律。

因本协议产生的或与本协议有关的任何争议,双方应友好协商解决;协商不成的,任何一方均可向【公司所在地】有管辖权的人民法院提起诉讼。

九、 其他

本协议构成双方就本服务达成的完整协议,取代此前任何口头或书面约定。

本协议任一条款被认定为无效或不可执行的,不影响其他条款的效力。

我们对本协议享有最终解释权,并在法律允许的范围内保留随时修改的权利。修改后的协议一经公布即生效,继续使用服务即视为同意修订内容。


已查阅