链载Ai

标题: 如此简单,利用DSPy高效实现RAG [打印本页]

作者: 链载Ai    时间: 前天 10:12
标题: 如此简单,利用DSPy高效实现RAG

介绍如何利用DSPy实现RAG。


检索增强生成(RAG)是一种先进的方法论,它赋予语言模型(LLMs)访问丰富知识库的能力,能够搜索并筛选出相关信息,进而生成精准而精炼的回答。

RAG技术允许语言模型在没有直接训练数据的情况下,通过上下文学习(ICL)动态地吸收和应用实时知识。

尽管这一技术带来了在构建和优化RAG流程方面的额外挑战,但DSPy提供了一种简洁而高效的解决方案,使得设置RAG提示流程变得流畅且轻松。

下面是DSPy RAG应用序列的展示:

1 DSPy RAG程序

这里使用GPT-3.5(特别是其高性能版本gpt-3.5-turbo)和ColBERTv2检索器。

ColBERTv2检索器部署在一台免费服务器上,它拥有一个基于2017年维基百科摘要的搜索索引,这些摘要涵盖了当年文章的开篇段落。

在DSPy的设置中,语言模型和检索器模型的配置如下所示,展示了如何将其集成并优化以实现最佳性能。

importdspy

turbo=dspy.OpenAI(model='gpt-3.5-turbo')
colbertv2_wiki17_abstracts=dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')

dspy.settings.configure(lm=turbo,rm=colbertv2_wiki17_abstracts)

接下来加载测试数据:

fromdspy.datasetsimportHotPotQA

#加载数据集。
dataset=HotPotQA(train_seed=1,train_size=20,eval_seed=2023,dev_size=50,test_size=0)
#告诉DSPy'问题'字段是输入。其他任何字段都是标签和/或元数据。
trainset=[x.with_inputs('question')forxindataset.train]
devset=[x.with_inputs('question')forxindataset.dev]

len(trainset),len(devset)

然后创建签名。你可以看到上下文、输入和输出字段是如何定义的。

classGenerateAnswer(dspy.Signature):
"""Answerquestionswithshortfactoidanswers."""

context=dspy.InputField(desc="maycontainrelevantfacts")
question=dspy.InputField()
answer=dspy.OutputField(desc="oftenbetween1and5words")

RAG流程被设计成DSPy模块,需要用到两种方法:

classRAG(dspy.Module):
def__init__(self,num_passages=3):
super().__init__()

self.retrieve=dspy.Retrieve(k=num_passages)
self.generate_answer=dspy.ChainOfThought(GenerateAnswer)

defforward(self,question):
context=self.retrieve(question).passages
prediction=self.generate_answer(context=context,question=question)
returndspy.Prediction(context=context,answer=prediction.answer)

这里有一个训练数据的例子:

Example({'question':'AtMyWindowwasreleasedbywhichAmericansinger-songwriter?',
'answer':'JohnTownesVanZandt'})
(input_keys={'question'}),

Example({'question':'whichAmericanactorwasCandaceKitagueststarredwith',
'answer':'BillMurray'})
(input_keys={'question'}),

Example({'question':'Whichofthesepublicationswasmostrecentlypublished,WhoPuttheBomporSelf?',
'answer':'Self'})
(input_keys={'question'}),

2 执行程序

接下来,程序将针对一个问题进行运行。

#你可以向这个简单的RAG程序提出任何问题。
my_question="WhatcastledidDavidGregoryinherit?"

#获取预测。这包含`pred.context`和`pred.answer`。
pred=compiled_rag(my_question)

#打印上下文和答案。
print(f"Question:{my_question}")
print(f"redictedAnswer:{pred.answer}")
print(f"RetrievedContexts(truncated):{[c[:200]+'...'forcinpred.context]}")

得到响应:

Question: What castle did David Gregory inherit?
Predicted Answer: Kinnairdy Castle
Retrieved Contexts (truncated): ['David Gregory (physician) | David Gregory (20 December 1625 – 1720) was a Scottish physician and inventor. His surname is sometimes spelt as Gregorie, the original Scottish spelling. He inherited Kinn...', 'Gregory Tarchaneiotes | Gregory Tarchaneiotes (Greek: Γρηγόριος Ταρχανειώτης , Italian: "Gregorio Tracanioto" or "Tracamoto" ) was a "protospatharius" and the long-reigning catepan of Italy from 998 t...', 'David Gregory (mathematician) | David Gregory (originally spelt Gregorie) FRS (? 1659 – 10 October 1708) was a Scottish mathematician and astronomer. He was professor of mathematics at the University ...']

3 总结

对DSPy实现的初步观察表明:







欢迎光临 链载Ai (https://www.lianzai.com/) Powered by Discuz! X3.5