使用Llama index构建多代理 RAG

news2024/9/23 11:17:37

检索增强生成(RAG)已成为增强大型语言模型(LLM)能力的一种强大技术。通过从知识来源中检索相关信息并将其纳入提示,RAG为LLM提供了有用的上下文,以产生基于事实的输出。

但是现有的单代理RAG系统面临着检索效率低下、高延迟和次优提示的挑战。这些问题在限制了真实世界的RAG性能。多代理体系结构提供了一个理想的框架来克服这些挑战并释放RAG的全部潜力。通过划分职责,多代理系统允许专门的角色、并行执行和优化协作。

单代理RAG

当前的RAG系统使用单个代理来处理完整的工作流程——查询分析、段落检索、排序、摘要和提示增强。

这种单一的方法提供了一个简单的一体化解决方案。但是对每个任务依赖一个代理会导致瓶颈。代理会浪费时间从大量语料库中检索无关紧要的段落。长上下文的总结很糟糕,并且提示无法以最佳方式集成原始问题和检索到的信息。

这些低效率严重限制了实时应用程序的RAG的可伸缩性和速度。

多代理RAG

多代理体系结构可以克服单代理的限制。通过将RAG划分为并发执行的模块化角色可以实现:

检索:专用检索代理专注于使用优化的搜索技术进行有效的通道检索。这将最小化延迟。

搜索:通过排除检索因素,搜索可以在检索代理之间并行化,以减少等待时间。

排名:单独的排名代理评估检索的丰富度,特异性和其他相关信号的传代。这将过滤最大的相关性。

总结:将冗长的上下文总结成简洁的片段,只包含最重要的事实。

优化提示:动态调整原始提示和检索信息的集成。

灵活的体系:可以替换和添加代理来定制系统。可视化工具代理可以提供对工作流的洞察。

通过将RAG划分为专门的协作角色,多代理系统增强了相关性,减少了延迟,并优化了提示。这将解锁可伸缩的高性能RAG。

划分职责允许检索代理结合互补技术,如向量相似性、知识图谱和互联网抓取。这种多信号方法允许检索捕获相关性不同方面的不同内容。

通过在代理之间协作分解检索和排序,可以从不同的角度优化相关性。结合阅读和编排代理,它支持可伸缩的多角度RAG。

模块化架构允许工程师跨专门代理组合不同的检索技术。

Llama index的多代理 RAG

Llama index概述了使用多代理RAG的具体示例:

文档代理——在单个文档中执行QA和摘要。

向量索引——为每个文档代理启用语义搜索。

摘要索引——允许对每个文档代理进行摘要。

高阶(TOP-LEVEL)代理——编排文档代理以使用工具检索回答跨文档的问题。

对于多文档QA,比单代理RAG基线显示出真正的优势。由顶级代理协调的专门文档代理提供基于特定文档的更集中、更相关的响应。

下面我们看看Llama index是如何实现的:

我们将下载关于不同城市的Wikipedia文章。每篇文章都是单独存储的。我们只找了18个城市,虽然不是很大,但是这已经可以很好的演示高级文档检索的功能。

 from llama_index import (
     VectorStoreIndex,
     SummaryIndex,
     SimpleKeywordTableIndex,
     SimpleDirectoryReader,
     ServiceContext,
 )
 from llama_index.schema import IndexNode
 from llama_index.tools import QueryEngineTool, ToolMetadata
 from llama_index.llms import OpenAI

下面是城市的列表:

 wiki_titles = [
     "Toronto",
     "Seattle",
     "Chicago",
     "Boston",
     "Houston",
     "Tokyo",
     "Berlin",
     "Lisbon",
     "Paris",
     "London",
     "Atlanta",
     "Munich",
     "Shanghai",
     "Beijing",
     "Copenhagen",
     "Moscow",
     "Cairo",
     "Karachi",
 ]

下面是下载每个城市文档代码:

 from pathlib import Path
 
 import requests
 
 for title in wiki_titles:
     response = requests.get(
         "https://en.wikipedia.org/w/api.php",
         params={
             "action": "query",
             "format": "json",
             "titles": title,
             "prop": "extracts",
             # 'exintro': True,
             "explaintext": True,
         },
     ).json()
     page = next(iter(response["query"]["pages"].values()))
     wiki_text = page["extract"]
 
     data_path = Path("data")
     if not data_path.exists():
         Path.mkdir(data_path)
 
     with open(data_path / f"{title}.txt", "w") as fp:
         fp.write(wiki_text)

加载下载的文档

 # Load all wiki documents
 city_docs = {}
 for wiki_title in wiki_titles:
     city_docs[wiki_title] = SimpleDirectoryReader(
         input_files=[f"data/{wiki_title}.txt"]
     ).load_data()

定义LLM +上下文+回调管理器

 llm = OpenAI(temperature=0, model="gpt-3.5-turbo")
 service_context = ServiceContext.from_defaults(llm=llm)

我们为每个文档定义“文档代理”:为每个文档定义向量索引(用于语义搜索)和摘要索引(用于摘要)。然后将这两个查询引擎转换为传递给OpenAI函数调用工具。

文档代理可以动态选择在给定文档中执行语义搜索或摘要。我们为每个城市创建一个单独的文档代理。

 from llama_index.agent import OpenAIAgent
 from llama_index import load_index_from_storage, StorageContext
 from llama_index.node_parser import SimpleNodeParser
 import os
 
 node_parser = SimpleNodeParser.from_defaults()
 
 # Build agents dictionary
 agents = {}
 query_engines = {}
 
 # this is for the baseline
 all_nodes = []
 
 for idx, wiki_title in enumerate(wiki_titles):
     nodes = node_parser.get_nodes_from_documents(city_docs[wiki_title])
     all_nodes.extend(nodes)
 
     if not os.path.exists(f"./data/{wiki_title}"):
         # build vector index
         vector_index = VectorStoreIndex(nodes, service_context=service_context)
         vector_index.storage_context.persist(
             persist_dir=f"./data/{wiki_title}"
         )
     else:
         vector_index = load_index_from_storage(
             StorageContext.from_defaults(persist_dir=f"./data/{wiki_title}"),
             service_context=service_context,
         )
 
     # build summary index
     summary_index = SummaryIndex(nodes, service_context=service_context)
     # define query engines
     vector_query_engine = vector_index.as_query_engine()
     summary_query_engine = summary_index.as_query_engine()
 
     # define tools
     query_engine_tools = [
         QueryEngineTool(
             query_engine=vector_query_engine,
             metadata=ToolMetadata(
                 name="vector_tool",
                 description=(
                     "Useful for questions related to specific aspects of"
                     f" {wiki_title} (e.g. the history, arts and culture,"
                     " sports, demographics, or more)."
                 ),
             ),
         ),
         QueryEngineTool(
             query_engine=summary_query_engine,
             metadata=ToolMetadata(
                 name="summary_tool",
                 description=(
                     "Useful for any requests that require a holistic summary"
                     f" of EVERYTHING about {wiki_title}. For questions about"
                     " more specific sections, please use the vector_tool."
                 ),
             ),
         ),
     ]
 
     # build agent
     function_llm = OpenAI(model="gpt-4")
     agent = OpenAIAgent.from_tools(
         query_engine_tools,
         llm=function_llm,
         verbose=True,
         system_prompt=f"""\
 You are a specialized agent designed to answer queries about {wiki_title}.
 You must ALWAYS use at least one of the tools provided when answering a question; do NOT rely on prior knowledge.\
 """,
     )
 
     agents[wiki_title] = agent
     query_engines[wiki_title] = vector_index.as_query_engine(
         similarity_top_k=2
     )

下面就是高阶代理,它可以跨不同的文档代理进行编排,回答任何用户查询。

高阶代理可以将所有文档代理作为工具,执行检索。这里我们使用top-k检索器,但最好的方法是根据我们的需求进行自定义检索。

 # define tool for each document agent
 all_tools = []
 for wiki_title in wiki_titles:
     wiki_summary = (
         f"This content contains Wikipedia articles about {wiki_title}. Use"
         f" this tool if you want to answer any questions about {wiki_title}.\n"
     )
     doc_tool = QueryEngineTool(
         query_engine=agents[wiki_title],
         metadata=ToolMetadata(
             name=f"tool_{wiki_title}",
             description=wiki_summary,
         ),
     )
     all_tools.append(doc_tool)
     
 # define an "object" index and retriever over these tools
 from llama_index import VectorStoreIndex
 from llama_index.objects import ObjectIndex, SimpleToolNodeMapping
 
 tool_mapping = SimpleToolNodeMapping.from_objects(all_tools)
 obj_index = ObjectIndex.from_objects(
     all_tools,
     tool_mapping,
     VectorStoreIndex,
 )
 
 from llama_index.agent import FnRetrieverOpenAIAgent
 
 top_agent = FnRetrieverOpenAIAgent.from_retriever(
     obj_index.as_retriever(similarity_top_k=3),
     system_prompt=""" \
 You are an agent designed to answer queries about a set of given cities.
 Please always use the tools provided to answer a question. Do not rely on prior knowledge.\
 
 """,
     verbose=True,
 )

作为比较,我们定义了一个“简单”的RAG管道,它将所有文档转储到单个矢量索引集合中。设置top_k = 4

 base_index = VectorStoreIndex(all_nodes)
 base_query_engine = base_index.as_query_engine(similarity_top_k=4)

让我们运行一些示例查询,对比单个文档的QA /摘要到多个文档的QA /摘要。

 response = top_agent.query("Tell me about the arts and culture in Boston")

结果如下:

 === Calling Function ===
 Calling function: tool_Boston with args: {
   "input": "arts and culture"
 }
 === Calling Function ===
 Calling function: vector_tool with args: {
   "input": "arts and culture"
 }
 Got output: Boston is known for its vibrant arts and culture scene. The city is home to a number of performing arts organizations, including the Boston Ballet, Boston Lyric Opera Company, Opera Boston, Boston Baroque, and the Handel and Haydn Society. There are also several theaters in or near the Theater District, such as the Cutler Majestic Theatre, Citi Performing Arts Center, the Colonial Theater, and the Orpheum Theatre. Boston is a center for contemporary classical music, with groups like the Boston Modern Orchestra Project and Boston Musica Viva. The city also hosts major annual events, such as First Night, the Boston Early Music Festival, and the Boston Arts Festival. In addition, Boston has several art museums and galleries, including the Museum of Fine Arts, the Isabella Stewart Gardner Museum, and the Institute of Contemporary Art.
 ========================
 Got output: Boston is renowned for its vibrant arts and culture scene. It is home to numerous performing arts organizations, including the Boston Ballet, Boston Lyric Opera Company, Opera Boston, Boston Baroque, and the Handel and Haydn Society. The city's Theater District houses several theaters, such as the Cutler Majestic Theatre, Citi Performing Arts Center, the Colonial Theater, and the Orpheum Theatre.
 
 Boston is also a hub for contemporary classical music, with groups like the Boston Modern Orchestra Project and Boston Musica Viva. The city hosts major annual events, such as First Night, the Boston Early Music Festival, and the Boston Arts Festival, which contribute to its cultural richness.
 
 In terms of visual arts, Boston boasts several art museums and galleries. The Museum of Fine Arts, the Isabella Stewart Gardner Museum, and the Institute of Contemporary Art are among the most notable. These institutions offer a wide range of art collections, from ancient to contemporary, attracting art enthusiasts from around the world.
 ========================

下面我们看看上面的简单RAG管道的结果

 # baseline
 response = base_query_engine.query(
     "Tell me about the arts and culture in Boston"
 )
 print(str(response))
 
 Boston has a rich arts and culture scene. The city is home to a variety of performing arts organizations, such as the Boston Ballet, Boston Lyric Opera Company, Opera Boston, Boston Baroque, and the Handel and Haydn Society. Additionally, there are numerous contemporary classical music groups associated with the city's conservatories and universities, like the Boston Modern Orchestra Project and Boston Musica Viva. The Theater District in Boston is a hub for theater, with notable venues including the Cutler Majestic Theatre, Citi Performing Arts Center, the Colonial Theater, and the Orpheum Theatre. Boston also hosts several significant annual events, including First Night, the Boston Early Music Festival, the Boston Arts Festival, and the Boston gay pride parade and festival. The city is renowned for its historic sites connected to the American Revolution, as well as its art museums and galleries, such as the Museum of Fine Arts, Isabella Stewart Gardner Museum, and the Institute of Contemporary Art.

可以看到我们构建的多代理系统的结果要好的多。

总结

RAG系统必须发展多代理体系结构以实现企业级性能。正如这个例子所说明的,划分职责可以在相关性、速度、摘要质量和及时优化方面获得收益。通过将RAG分解为专门的协作角色,多代理系统可以克服单代理的限制,并启用可扩展的高性能RAG。

https://avoid.overfit.cn/post/7f39d14f7e1a47188870b04c0c332641

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

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

相关文章

第65讲:MySQL存储过程之循环语法的核心概念与应用案例

文章目录 1.存储过程中循环的种类2.WHILE循环控制2.1.WHILE循环语法格式2.2.WHILE循环经典案例 3.REPEAT循环控制3.1.REPEAT循环语法结构3.2.REPEAT循环经典案例 4.LOOP循环控制4.1.LOOP循环语法结构4.2.LOOP循环经典案例一4.3.LOOP循环经典案例二 1.存储过程中循环的种类 在存…

git 撤销已经push到远程的提交

git 撤销已经push到远程的提交 1. 情景2. 解决方法2.1 git revert2.2 git reset 1. 情景 工作中会有很多时候提交git的时候会提交错东西,而且已经push到远程的话怎么办呢? 2. 解决方法 2.1 git revert 一种常见的方法是使用 git revert 命令来创建一…

酷开科技,让家庭更有温度!

生活中总有一些瞬间,会让我们感到无比温暖和幸福。一个拥抱、一句问候、一杯热茶,都能让我们感受到家庭的温馨和关爱。酷开科技也用自己的方式为我们带来了独属于科技的温暖,通过全新的体验将消费者带进一个充满惊喜的世界,让消费…

iPhone无法关机未必是坏了!如何修复无法关闭的iPhone

iPhone运行很慢且发热是一个比较罕见的情况,但如果它发生在你身上,下面解释了发生的原因以及你如何修复它。 iPhone无法关闭的原因 iPhone无法关闭的最可能原因是: 由于软件问题,它被冻结了。 睡眠/唤醒按钮坏了。 屏幕坏了&a…

【Redis】环境配置

环境配置 Linux版本: Ubuntu 22.04.2 LTS 下载redis sudo apt install redis 启动redis redis-server 输入redis-server启动redis竟然报错了,原因是redis已经启动,网上大多数的解决方案如下: ps -ef | grep -i redis 查询redi…

软件开发项目文档系列之六概要设计:构建可靠系统的蓝图

概要设计是软件开发项目中至关重要的阶段,它为整个系统提供了设计蓝图和技术方向。它的重要性在于明确项目目标、规划系统结构、确定技术选择、识别风险、以及为团队提供共同的视角,确保项目在后续开发阶段按计划进行。概要设计的主要内容包括项目的背景…

九州未来入选“2023边缘计算产业图谱”三大细分领域

10月26日,边缘计算社区正式发布《2023边缘计算产业图谱》,九州未来凭借深厚的技术积累、优秀的产品服务、完善的产品解决方案体系以及开源贡献,实力入选图谱——边缘计算平台、边缘计算开源、边缘云服务提供商三大细分领域,充分彰…

统信UOS1060上修改sudo权限

原文链接:统信UOS1060上修改sudo权限 hello,大家好啊,今天给大家带来在统信UOS桌面操作系统1060上修改管理员权限,使其在使用sudo的时候,不要输入本用户密码验证的文章,主要通过修改 /etc/sudoers文件实现&…

恒驰服务 | 华为云数据使能专家服务offering之大数据建设

恒驰大数据服务主要针对客户在进行智能数据迁移的过程中,存在业务停机、数据丢失、迁移周期紧张、运维成本高等问题,通过为客户提供迁移调研、方案设计、迁移实施、迁移验收等服务内容,支撑客户实现快速稳定上云,有效降低时间成本…

el-upload 组件上传/移除/报错/预览文件,预览图片、pdf 等功能

目录 页面代码样式代码页面展示 页面代码 dialog.vue <!-- 上传文件 --> <template><el-dialogtitle"上传文件":visible.sync"dialogVisible"width"60%"top"6vh":close-on-click-modal"false"close"h…

中国人民大学与加拿大女王大学金融硕士——在职读研,演绎精彩的人生

为什么在职读研呢&#xff1f;这是对即将读研人的“灵魂拷问”&#xff0c;每个人读研的原因不同&#xff0c;有人因为职业瓶颈&#xff0c;有人晋升需要&#xff0c;还有人为了完成曾经的读研梦想&#xff1b;读书深造是一种经历&#xff0c;不光是学历的加持&#xff0c;我们…

API Testing v0.0.14 新增 gRPC, tRPC 协议的支持

api-testing 本次版本发布中的内容中&#xff0c;包含了两位高校同学的 contribution&#xff0c;其中屈晗煜在GitLink编程夏令营&#xff08;GLCC&#xff09;活动期间非常给力地增加了gRPC 协议的支持。 atest 版本发布 v0.0.14 atest 是一款用 Golang 编写的、开源的接口测试…

Vue3最佳实践 第八章 ESLint 与 测试 ( Jest )

Jest 测试 Vue 组件 ​在前端项目开发过程中&#xff0c;有很多时候也会要进行测试工作。本文将重点介绍如何利用 JavaScript 测试框架 Jest 进行高效的测试。Jest 是由 FaceBook 开发的顶级测试框架之一&#xff0c;广受开发者们的欢迎和信赖。在接下来的内容中&#xff0c;我…

【Ubuntu 系统使用进入,自动进入base虚拟环境解决最全】

项目场景&#xff1a; 在Ubuntu上安装完anaconda后&#xff0c;发现每次打开终端后都会自动进入到base的虚拟环境中去&#xff0c;虽然在这些环境下使用问题不大&#xff0c;但一些软件的安装在虚拟环境下有影响。每次使用conda deactivate退出也很麻烦。 问题描述 安装玩之…

软件测试这些基本类型你知道吗

关于软件测试的类型&#xff0c;从不同角度来讲&#xff0c;可以分很多种&#xff0c;有时候甚至觉得软件测试是人类创造出来的最复杂的职业。。。 对一些常见的测试类型做了一个基本的文档总结&#xff0c;有些测试类型在之前的基础知识里面已经有所介绍&#xff0c;这里就没…

【Python爬虫+可视化】解析小破站热门视频,看看播放量为啥会这么高!评论、弹幕主要围绕什么展开

大家早好、午好、晚好吖 ❤ ~欢迎光临本文章 如果有什么疑惑/资料需要的可以点击文章末尾名片领取源码 环境使用 Python 3.8 Pycharm 模块使用 import requests import csv import datetime import hashlib import time 一. 数据来源分析 明确需求 明确采集网站以及数…

Linux Spug自动化运维平台公网远程访问

文章目录 前言1. Docker安装Spug2 . 本地访问测试3. Linux 安装cpolar4. 配置Spug公网访问地址5. 公网远程访问Spug管理界面6. 固定Spug公网地址 前言 Spug 面向中小型企业设计的轻量级无 Agent 的自动化运维平台&#xff0c;整合了主机管理、主机批量执行、主机在线终端、文件…

Unity HoloLens 2 应用程序发布

设置3D 启动器画面&#xff0c;glb格式的模型 VS中可以直接生成所有大小的图标

C++:快速入门篇

C:.cpp(面向对象) C语音&#xff1a;.c(面向过程)是为了弥补C的不足 命名冲突&#xff1a; 1.写的跟库冲突 2.自己写的互相冲突 1.命名空间 在C/C中&#xff0c;变量、函数和后面要学到的类都是大量存在的&#xff0c;这些变量、函数和类的名称将都存在于全局作用域中&#xff…