介绍如何利用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模块,需要用到两种方法:
__init__方法负责初始化,它声明了所需的子模块:dspy.Retrieve用于信息检索,dspy.ChainOfThought则用于按照我们的GenerateAnswer签名进行思考链的构建。
forward方法定义了回答问题的具体流程。面对一个问题,该方法首先检索与之相关的前三段文本,然后利用这些文本作为上下文,生成精确的答案。
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实现的初步观察表明:
利用丰富的参数,可以方便地创建初始的RAG应用程序。 拥有一个强大的数据摄取流程,这为数据处理提供了极大的便利,是个值得考虑的优势。 内置的流程和检索评估机制,使性能监控和优化变得更加方便。 作为一个快速独立的实现,其在简化实现方面的表现确实令人印象深刻。 最后,从下面的图表可以看出,LangChain、LlamaIndex和DSPy在GitHub社区中的活跃度和影响力。