让模型评估模型:构建双代理RAG评估系统的步骤解析

在当前大语言模型(LLM)应用开发的背景下,一个关键问题是如何评估模型输出的准确性。我们需要确定哪些评估指标能够有效衡量提示(prompt)的效果,以及在多大程度上需要对提示进行优化。

为解决这一问题,我们将介绍一个基于双代理的RAG(检索增强生成)评估系统。该系统使用生成代理和反馈代理,基于预定义的测试集对输出进行评估。或者更简单的说,我们使用一个模型来评估另外一个模型的输出。

在本文中将详细介绍如何构建这样一个RAG评估系统,并展示基于四种提示工程技术的不同结果,包括ReAct、思维链(Chain of Thought)、自一致性(Self-Consistency)和角色提示(Role Prompting)。

以下是该项目的整体架构图:

数据收集与摄入

此部分在 ingestion.py 中实现

数据收集过程使用了三篇文章作为源数据。在加载和分割数据后,我们对文本进行嵌入,并将嵌入向量存储在FAISS中。FAISS(Facebook AI Similarity Search)是由Meta开发的开源库,用于高效进行密集向量的相似性搜索和聚类。

以下是实现代码:

 urls= [  "https://medium.com/@fareedkhandev/prompt-engineering-complete-guide-2968776f0431",  "https://medium.com/@researchgraph/prompt-engineering-21112dbfc789",  "https://blog.fabrichq.ai/what-is-prompt-engineering-a-detailed-guide-with-examples-4d3cbbd53792"  ]  loader=WebBaseLoader(urls)  # 文本分割器  text_splitter=RecursiveCharacterTextSplitter(  chunk_size=1000, chunk_overlap=20  )  documents=loader.load_and_split(text_splitter)  # LLM  embedder_llm=OpenAIModel().embed_model()  # 对文档块进行嵌入  vectorstore=FAISS.from_documents(documents, embedder_llm)  vectorstore.save_local("faiss_embed")  print("===== 数据摄入完成 ===== ")

创建测试集

此部分在 create_test_set.py 中实现

测试集的构建使用了Giskard工具。Giskard是一个开源工具,专为测试和改进机器学习模型而设计。它使用户能够创建、运行和自动化测试,以评估模型的性能、公平性和稳健性。

实现代码如下:

 fromlangchain_community.document_loadersimportWebBaseLoader  fromlangchain.text_splitterimportRecursiveCharacterTextSplitter  # 用于构建测试集  fromgiskard.ragimportKnowledgeBase, generate_testset  # 数据框  importpandasaspd  fromLLM.modelsimportOpenAIModel  if__name__=='__main__':  urls= [  "https://medium.com/@fareedkhandev/prompt-engineering-complete-guide-2968776f0431",  "https://medium.com/@researchgraph/prompt-engineering-21112dbfc789",  "https://blog.fabrichq.ai/what-is-prompt-engineering-a-detailed-guide-with-examples-4d3cbbd53792"  ]  loader=WebBaseLoader(urls)  # 文本分割器  text_splitter=RecursiveCharacterTextSplitter(  chunk_size=1000, chunk_overlap=20  )  documents=loader.load_and_split(text_splitter)  df=pd.DataFrame([doc.page_contentfordocindocuments], columns=["text"])  print(df.head(10))  ## 将数据框添加到giskard KnowledgeBase  knowledge_base=KnowledgeBase(df)  # 生成测试集  test_set=generate_testset(  knowledge_base,  num_questions=10,  agent_description="A chatbot answering question about prompt engineering"  )  test_set.save("test-set.jsonl")

由于文本太多,生成的样例就不显示了

答案检索

此部分在 generation.py 中实现

本文的第一个流程是生成流程。我们从FAISS检索数据。实现代码如下:

 generate_llm=OpenAIModel().generate_model()  embedder_llm=OpenAIModel().embed_model()  vectorstore=FAISS.load_local("faiss_embed", embedder_llm, allow_dangerous_deserialization=True)  retrieval_qa_chat_prompt= (retrieval)  prompt=ChatPromptTemplate.from_messages(  [  ("system", retrieval_qa_chat_prompt),  ("human", "{input}"),  ]  )combine_docs_chain=create_stuff_documents_chain(generate_llm, prompt)  retrival_chain=create_retrieval_chain(  retriever=vectorstore.as_retriever(),  combine_docs_chain=combine_docs_chain  )

评估

此部分在 evaluation.py 中实现

评估过程中向LLM提供三个输入:问题、AI答案(第一个LLM的输出)和实际答案(从测试集中检索)。实现代码如下:

 defRAG_eval(question, AI_answer, Actual_answer, prompt):  evaluation_prompt_template=PromptTemplate(  input_variables=[  "question", "AI_answer", "Actual_answer"  ],  template=prompt  )  generate_llm=OpenAIModel().generate_model()  optimization_chain=evaluation_prompt_template|generate_llm|StrOutputParser()  result_optimization=optimization_chain.invoke(  {"question": question, "AI_answer": AI_answer, "Actual_answer": Actual_answer})  returnresult_optimization

链接整合

此部分在 main.py 中实现

主文件遍历测试数据,使用问题作为第一个LLM的输入。然后将第一个LLM的输出用作第二个LLM的输入。实现代码如下:

 foritemindata:  question= {"input": item['question']}  # 生成回答  result=retrival_chain.invoke(input=question)  AI_answer=result['answer']  # 获取实际答案  Actual_answer=item['reference_answer']  # 将所有内容提供给第二个LLM  Evaluation=RAG_eval(  question=question,  AI_answer=AI_answer,  Actual_answer=Actual_answer,  prompt=evaluation_self_consistency_prompting  )  print(f"AI_answer:{AI_answer}")  print(Evaluation)

实验结果

评估组件采用了四种不同的提示工程技术:

  1. 思维链(Chain of Thought)
  2. ReAct
  3. 角色提示(Role Prompting)
  4. 自一致性(Self-Consistency)

以下是基于这四种不同提示技术的评估代理对测试集第一个问题的输出示例:

问题: What is the purpose of incorporating knowledge in prompt engineering?

实际答案: Incorporating knowledge or information in prompt engineering enhances the model’s prediction accuracy. By providing relevant knowledge or information related to the task at hand, the model can leverage this additional context to make more accurate predictions. This technique enables the model to tap into external resources or pre-existing knowledge to improve its understanding and generate more informed responses

**AI答案:**Incorporating knowledge in prompt engineering enhances the quality of responses by guiding AI models to provide not just answers, but also relevant context and insights. This leads to more informative and meaningful interactions, improving user experience and understanding.

使用思维链输出的**评估结果:**The student’s answer correctly identifies that incorporating knowledge enhances the quality of responses and improves user experience. However, it lacks emphasis on the model’s prediction accuracy and the importance of leveraging external resources or pre-existing knowledge, which are key components of the actual answer. This omission affects the completeness and correctness of the response.

使用ReAct输出评估结果**:**The student’s answer correctly identifies that incorporating knowledge enhances the quality of responses and improves user experience. However, it lacks emphasis on the specific aspect of prediction accuracy and the importance of leveraging external resources or pre-existing knowledge, which are key components of the actual answer. This omission affects the completeness of the response, leading to a lower evaluation percentage.

使用角色提示输出评估结果**:**The student’s response accurately captures the essence of incorporating knowledge in prompt engineering by emphasizing the enhancement of response quality and user experience. However, it lacks specific mention of prediction accuracy and the model’s ability to leverage external resources, which are key aspects of the actual response.

使用自一致性输出评估结果**:**The student’s answer captures the essence of enhancing the quality of responses through knowledge incorporation, but it lacks specific mention of prediction accuracy and the model’s ability to leverage external resources. The initial evaluation was slightly optimistic, but upon reevaluation, it became clear that the answer did not fully align with the actual answer’s emphasis on prediction accuracy and context utilization

实验结果分析

下图展示了四种提示工程技术的准确性比较。每种技术由图中的一条独立线条表示,X轴上的10个数据点对应测试数据的索引值,Y轴表示准确性值。

在评估过程中,准确性达到85%及以上的响应视为真正准确(True),低于85%则视为不准确(False)。下面的条形图展示了基于每种提示工程技术的评估结果中True和False的计数。

实验结果显示,ReAct和思维链(Chain of Thought)的性能几乎相似,而自一致性(Self-Consistency)则表现出完全相反的行为。角色提示(Role Prompting)在所有方法中表现最不稳定。

一些发现

  1. 评估代理的所有响应虽然在内容上相近,都提到了类似的缺失元素,但反馈之间的差异主要体现在具体措辞和强调点上,这些细微差别可能会对最终的评分过程产生影响。
  2. 角色提示和自一致性技术倾向于强调结果的积极方面,而ReAct和思维链则更多地使用特定措辞来突出回答中的缺失部分。

总结

本文展示了如何构建一个基于双代理的RAG(检索增强生成)评估系统,该系统使用两个大语言模型(LLM):一个用于生成响应,另一个用于提供反馈。通过采用四种不同的提示工程技术——思维链、ReAct、角色提示和自一致性,我们能够全面评估AI生成响应的准确性和质量。

实验结果表明:

  1. ReAct和思维链技术在性能上表现相似,这可能是因为它们都强调了结构化思考过程。
  2. 自一致性技术经常产生与其他方法相反的结果,这突显了在评估过程中考虑多个角度的重要性。
  3. 角色提示技术被证明是最不可靠的,这可能是由于其在不同上下文中的不一致性。

本文代码:

https://avoid.overfit.cn/post/f64e1de74d8a423a859086dfed4d5a47

作者:Homayoun S.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/1541092.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

MySQL练手题--日期连续类型(困难)

一、准备工作 Create table If Not Exists Failed (fail_date date); Create table If Not Exists Succeeded (success_date date); Truncate table Failed; insert into Failed (fail_date) values (2018-12-28); insert into Failed (fail_date) values (2018-12-29); inser…

攻防世界-1-misc

下载附件,提示需要密码 提示密码是出题人的生日,这里可以自己定义一个关于生日的字典,使用字典生成工具,直接生成字典。(我用的是19000101至20231231字典进行的爆破测试) 使用archpr软件,和刚刚…

k8s下的网络通信与调度

目录 一、k8s网络通信 1、k8s通信整体架构 2、flannel网络插件 (1)flannel跨主机通信原理 (2)flannel支持的后端模式 3、calico网络插件 (1)简介 (2)网络架构 (…

Css_动态渐变圆圈旋转效果

1、效果图 2、实现代码 <template><div class"box"><div class"line"></div><div class"lineNew"></div></div> </template><script lang"ts" setup></script><styl…

C语言 | Leetcode C语言题解之第421题数组中两个数的最大异或值

题目&#xff1a; 题解&#xff1a; const int HIGH_BIT 30;struct Trie {// 左子树指向表示 0 的子节点struct Trie* left;// 右子树指向表示 1 的子节点struct Trie* right; };struct Trie* createTrie() {struct Trie* ret malloc(sizeof(struct Trie));ret->left re…

天润融通创新功能,将无效会话转化为企业新商机

“您好&#xff0c;请问有什么可以帮您&#xff1f;” “......” 一个新的咨询会话进来&#xff0c;但客户却并不说话&#xff0c;这种情况客服人员肯定不会陌生&#xff0c;它一般被称为“无效会话”。 如今“无效会话”越来越多&#xff0c;已经成为困扰无数企业的难题。…

数学建模 第二讲 - 初等建模

绪论 主要内容:介绍以下几个初等模型&#xff0c;椅子问题、席位分配问题、行走步长问题、实物交换模型。 主要目的:体会数学建模的形式多样性与方法多样性&#xff0c;了解建模思想&#xff0c;着重理解由现实问题向数学问题的转化过程。 一、椅子问题 问题 四条腿长度相等…

Flat File端口更新:如何实现嵌套结构

Flat File端口可以实现平面文件和XML文件的互相转换&#xff0c;本文主要介绍在知行之桥EDI系统8971及更高版本中&#xff0c;Flat File端口如何支持类似EDI嵌套结构的转换。 Flatfile端口如何自定义嵌套结构 下载示例工作流以及示例文件 打开知行之桥EDI系统&#xff0c;创建…

2024年中国研究生数学建模竞赛ABCDEF题【附带解题思路代码+结果】

2024年中国研究生数学建模竞赛D题 点击链接加入群聊【2024华为杯数学建模助攻资料】&#xff1a;http://qm.qq.com/cgi-bin/qm/qr?_wv1027&kxtS4vwn3gcv8oCYYyrqd0BvFc7tNfhV7&authKeyedQFZne%2BzvEfLEVg2v8FOm%2BWNg1V%2Fiv3H4tcE6X%2FW6lCmkhaSaZV4PwQ%2FOVPDtF%2B…

css实现居中的方法

水平居中 1. 行内设置text-align 给父元素设置text-align为center&#xff0c;一般用于实现文字水平居中 2. 给当前元素设置margin&#xff1a;0 auto 原理&#xff1a;块级独占一行&#xff0c;表现为在水平方向上占满整个父容器&#xff0c;当水平方向padding&#xff0c;…

算法-Init

&#xff08;1&#xff09;有限性&#xff08;Finiteness&#xff09;&#xff1a;算法必 需在有限步骤内结束&#xff1b; &#xff08;2&#xff09;确定性&#xff08;Definiteness&#xff09;&#xff1a;算法的每一个步骤必须清晰无歧义地定义&#xff1b; &#xff08;3…

2024年Q3国际信息系统安全认证联盟(ISC2)内部研讨会要点分享

2024年是CISSP认证成立30周年&#xff0c;这是一项具有里程碑意义的成就&#xff0c;代表了CISSP在网络安全领域的卓越、创新和领导力。博主于今年9月份参加了ISC2&#xff08;国际信息系统安全认证联盟&#xff09;组织的2024年第3季度内部网络研讨会&#xff0c;针对会议中的…

国标视频流媒体服务GB28181和Ehome等多协议接入的Liveweb方案详解

Liveweb视频融合/汇聚云平台基于“云-边-端”一体化架构&#xff0c;部署轻量简单、功能灵活多样&#xff0c;平台可支持多协议&#xff08;GB28181/RTSP/Onvif/海康SDK/Ehome/大华SDK/RTMP推流等&#xff09;、多类型设备接入(IPC/NVR/监控平台)&#xff0c;在视频能力上&…

Python 二级考试

易错点 电脑基础知识 定义学生关系模式如下&#xff1a;Student &#xff08;S#&#xff0c; Sn&#xff0c; Ssex&#xff0c;class&#xff0c;monitorS#&#xff09;&#xff08;其属性分别为学号、学生名、性别、班级和班长学号&#xff09; 在关系模式中&#xff0c;如果…

.NET内网实战:通过FSharp白名单执行命令

01阅读须知 此文所节选自小报童《.NET 内网实战攻防》专栏&#xff0c;主要内容有.NET在各个内网渗透阶段与Windows系统交互的方式和技巧。 02基本介绍 本文内容部分节选自小报童《.NET 通过Fsharp执行命令绕过安全防护》我们会长期更新&#xff01; 03编码实现 Fsi.exe 是…

信息安全工程师(9)网络信息安全管理内容与方法

前言 网络信息安全管理是确保网络资产&#xff08;包括网络设备、网络通信协议、网络服务及网络管理&#xff09;的安全性、可用性、完整性和可控性的重要工作。 一、网络信息安全管理内容 数据安全&#xff1a; 保密性&#xff1a;确保数据不被未经授权的第三方获取。完整性&a…

go的结构体、方法、接口

结构体&#xff1a; 结构体&#xff1a;不同类型数据集合 结构体成员是由一系列的成员变量构成&#xff0c;这些成员变量也被称为“字段” 先声明一下我们的结构体&#xff1a; type Person struct {name stringage intsex string } 定义结构体法1&#xff1a; var p1 P…

xhs 小红书 x-s web 分析

声明: 本文章中所有内容仅供学习交流使用&#xff0c;不用于其他任何目的&#xff0c;抓包内容、敏感网址、数据接口等均已做脱敏处理&#xff0c;严禁用于商业用途和非法用途&#xff0c;否则由此产生的一切后果均与作者无关&#xff01; 有相关问题请第一时间头像私信联系我…

详解npm源及其使用方法

详解npm源及其使用方法 npm源是一个用于存储和提供npm包的服务器地址&#xff0c;npm在安装包时会通过这个源地址下载对应的依赖包。默认情况下&#xff0c;npm使用官方的npm源&#xff08;https://registry.npmjs.org/&#xff09;&#xff0c;该源存储了海量的Node.js开源包…

QMT获取可转债行情数据方法介绍!支持QMT量化软件的券商平台?

获取可转债行情 为了获取转债的日线/1m/1d的k数据&#xff0c;以通过数据订阅形式获取最新行情subscribe_quote。如果您需要获取历史数据&#xff0c;可以使用download_history_data函数下载相关数据&#xff0c;然后使用get_market_data_ex函数提取所需的信息。这样&#xff…