LLM之RAG实战(二):使用LlamaIndex + Metaphor实现知识工作自动化
最先进的大型语言模型(LLM),如ChatGPT、GPT-4、Claude 2,具有令人难以置信的推理能力,可以解锁各种用例——从洞察力提取到问答,再到通用工作流自动化。然而,他们检索上下文相关信息的能力有限。检索增强生成(RAG)系统可以将LLM与静态知识源上的外部存储解决方案相结合。
RAG通常需要两个核心组件:
-
通用抽象,允许LLM以“读取”和“写入”的方式智能地对数据执行各种任务;
-
一个适合LLM使用的好搜索引擎
LlamaIndex数据代理抽象有助于满足第一个核心组件。一个完整的数据代理由一个推理循环和一组工具组成。这些工具可以是用于搜索/检索的接口,或者更一般地是任何外部API。给定一个查询,代理将执行其推理循环,并动态地计算出完成手头任务所需的工具集。
数据代理可以访问LlamaHub上提供的一套丰富的工具,从Gmail API到SQL数据库API,再到Bing搜索形式的基本工具。我们已经证明,他们能够执行e2e任务,从发送电子邮件、安排会议到自动化定制支持洞察力提取。然而,从来没有专门为LLM使用而设计的工具。
本文将介绍LlamaIndex和Metaphor的集成来实现RAG:将LlamaIndex数据代理的功能与Metaphor作为一种本地LLM搜索工具相结合,使知识工作者能够回答任何数据上的任何问题,无论是最近的还是复杂的。示例可以参考:https://github.com/emptycrown/llama-hub/blob/main/llama_hub/tools/notebooks/metaphor.ipynb
一、Metaphor介绍
Metaphor API旨在将你的LLM连接到互联网,它允许你在互联网上进行完全神经化、高度语义化的搜索,还可以从结果中获得干净的HTML内容。
根据人们在互联网上谈论事物的方式,Metaphor被训练来预测互联网上的链接。例如,有人可能会这样发布他们读到的一篇很棒的文章:
Found an amazing article I read about the history of Rome’s architecture: [LINK]
通过训练一个模型来预测人们谈论这些链接的方式,最终的结果是一种完全不同的互联网搜索方式——就像你要分享你想要的链接一样进行搜索。虽然一开始有点不直观,但以这种方式搜索可以返回极高质量的结果。但就LlamaIndex而言,您不必担心这一点,因为默认情况下,查询将转换为Metaphor Prompt。
为什么你会在Bing/Google上使用Metaphor搜索?主要有三个原因:
- 您可以完全从语义上进行搜索,例如使用感觉或复杂的描述符;
- 您只能搜索所需实体的类型。公司、文章、人;
- 你可能会发现谷歌的内容表现不佳,可能是因为关键词不是正确的工具,也可能只是因为谷歌不在乎为这类内容返回好的结果。
PS:要了解更多信息,您可以阅读完整的Metaphor API博客文章(https://platform.metaphor.systems/blog/building-search-for-the-post-chatgpt-world)。
二、LlamaIndex和Metaphor的集成原理
LlamaHub提供了Metaphor API接口,包括如下5个工具可供Agent使用。
- 搜索:是Metaphor的入口——Agent可以通过自然语言向Metaphor搜索引擎进行查询。查询还可以包含一些附加参数,例如返回结果的数量、要包含/排除的领域以及日期筛选器;
- 检索文档:根据搜索到的文档内容从中检索出符合条件的部分内容;
- 搜索和检索文档:结合了“搜索”和“检索文档”的功能;
- 查找相似:直接调用Metaphor提供的端点,可以返回与给定URL相似的文档列表;
- 当前日期:这是一个返回当前日期的函数。就其本身而言,它与Metaphor的API无关,但可能会事先调用它,以确定传递到Metaphor的某些端点的正确日期过滤器。
在下一节中,让我们了解数据代理如何通过各种用例使用这些端点。
三、LlamaIndex和Metaphor集成示例
让我们看一下LlamaIndex数据Agent是如何与Metaphor一起使用的。
3.1 Metaphor工具测试
第一步是导入MetaphorToolSpec:
# Set up Metaphor tool
from llama_hub.tools.metaphor.base import MetaphorToolSpec
metaphor_tool = MetaphorToolSpec(
api_key='your-key',
)
# convert tool spec to a list of tools
metaphor_tool_list = metaphor_tool.to_tool_list()
for tool in metaphor_tool_list:
print(tool.metadata.name)
输入
metaphor_tool.search('machine learning transformers', num_results=3)
输出
[{'title': 'On the potential of Transformers in Reinforcement Learning',
'url': 'https://lorenzopieri.com/rl_transformers/',
'id': 'ysJlYSgeGW3l4zyOBoSGcg'},
{'title': 'Transformers: Attention in Disguise',
'url': 'https://www.mihaileric.com/posts/transformers-attention-in-disguise/',
'id': 'iEYMai5rS9k0hN5_BH0VZg'},
{'title': 'Transformers in Computer Vision: Farewell Convolutions!',
'url': 'https://towardsdatascience.com/transformers-in-computer-vision-farewell-convolutions-f083da6ef8ab?gi=a1d0a9a2896c',
'id': 'kX1Z89DdjSvBrH1S1XLvwg'}]
3.2 使用Metaphor设置OpenAI Agent
我们可以创建一个可以访问上述所有工具的代理,并开始测试它:
from llama_index.agent import OpenAIAgent
# We don't give the Agent our unwrapped retrieve document tools, instead passing the wrapped tools
agent = OpenAIAgent.from_tools(
metaphor_tool_list,
verbose=True,
)
下面看一个直接查询的例子:
print(agent.chat('What are the best restaurants in toronto?"))
了解一下该例子中Metaphor工具的执行细节:
=== Calling Function ===
Calling function: search with args: {
"query": "best restaurants in Toronto"
}
[Metaphor Tool] Autoprompt string: Here's a link to the best restaurant in Toronto:
Got output: [{'title': 'Via Allegro Ristorante - Toronto Fine Dining Restaurant', 'url': 'https://viaallegroristorante.com/', 'id': 'EVlexzJh-lzkVr4tb2y_qw'}, {'title': 'The Senator – Home', 'url': 'https://thesenator.com/', 'id': 'dA3HVr5P8E0Bs7nH2gH7ZQ'}, {'title': 'Home - The Rushton', 'url': 'https://therushton.com/', 'id': '6Je-igG-i-ApqISC5XXmGQ'}, {'title': 'Location', 'url': 'https://osteriagiulia.ca/', 'id': 'HjP5c54vqb3n3UNa3HevSA'}, {'title': 'StockYards | Stockyards Toronto', 'url': 'https://www.thestockyards.ca/', 'id': 'Pffz-DQlOepqVgKQDmW5Ig'}, {'title': 'Select A Restaurant', 'url': 'https://www.torontopho.com/', 'id': 'DiQ1hU1gmrIzpKnOaVvZmw'}, {'title': 'Home | Kit Kat Italian Bar & Grill', 'url': 'http://www.kitkattoronto.com/', 'id': 'kdAcLioBgnwzuHyd0rWS1w'}, {'title': 'La Fenice', 'url': 'https://www.lafenice.ca/', 'id': 'M-LHQZP6V40V81fqLFAQxQ'}, {'title': 'Le Phénix', 'url': 'https://www.lephenixto.com/', 'id': 'spCTcFr0GHlFUTzyngfRVw'}, {'title': 'ITALIAN, INSPIRED.', 'url': 'https://figotoronto.com/', 'id': 'OvBcTqEo1tCSywr4ATptCg'}]
========================
Here are some of the best restaurants in Toronto:
1. [Via Allegro Ristorante](https://viaallegroristorante.com/)
2. [The Senator](https://thesenator.com/)
3. [The Rushton](https://therushton.com/)
4. [Osteria Giulia](https://osteriagiulia.ca/)
5. [Stockyards](https://www.thestockyards.ca/)
6. [Toronto Pho](https://www.torontopho.com/)
7. [Kit Kat Italian Bar & Grill](http://www.kitkattoronto.com/)
8. [La Fenice](https://www.lafenice.ca/)
9. [Le Phénix](https://www.lephenixto.com/)
10. [Figo](https://figotoronto.com/)
You can visit their websites for more information. Enjoy your dining experience in Toronto!
可以看到agent执行了”search“操作,结果返回了Toronto最好的饭店列表。
继续追问进行多轮对话:
print(agent.chat('tell me more about Osteria Giulia'))
=== Calling Function ===
Calling function: retrieve_documents with args: {
"ids": ["HjP5c54vqb3n3UNa3HevSA"]
}
Got output: […]
========================
Osteria Giulia is a restaurant located at 134 Avenue Road in Toronto, Ontario. You can contact them at 416.964.8686 or via email at info@osteriagiulia.ca (for general inquiries only, no reservation requests via email).
The restaurant's operating hours are from Monday to Saturday, from 5:00pm to 11:00pm. On Sundays, the restaurant is available for private bookings.
Parking is available on Avenue Road and Davenport Road.
You can follow Osteria Giulia on Instagram [@osteriagiulia](https://www.instagram.com/osteriagiulia). They also have a sister restaurant called Giulietta, which you can visit at [giu.ca](https://giu.ca) or on Instagram [@giulietta972](https://www.instagram.com/giulietta972).
Please note that the information provided is based on the available document and may be subject to change. It is recommended to visit their official website or contact them directly for the most up-to-date information.
3.3 避免上下文窗口问题(高级)
使用retrieve的一个问题是内容可能很长。如果内容被直接地附加到会话历史并转储到LLM上下文窗口中,那么我们可能会遇到上下文窗口限制。
LlamaIndex提供了工具抽象来帮助处理这一问题。我们的LoadAndSearchToolSpec嵌入了任何可能返回大量数据的工具,并将其分为两个工具:一个是将数据动态存储在索引中的加载工具,另一个是允许在该索引上进行搜索的搜索工具。
在Metaphor方面,我们定义search_and_recovere_documents端点来结合search和retrieve。这允许代理进行单个查询以检索大量文档,当这些文档与LoadAndSearchToolSpec结合使用时,这些文档将直接存储在索引中。如果代理分别调用search和retrieve,那么将搜索结果写入会话历史记录,然后再次将其传递到提示中,以调用retrieve覆盖所有文档ID,将花费更长的时间,并消耗更多的token。
创建LoadAndSearchToolSpec:
from llama_index.tools.tool_spec.load_and_search.base import LoadAndSearchToolSpec
# The search_and_retrieve_documents tool is the third in the tool list, as seen above
wrapped_retrieve = LoadAndSearchToolSpec.from_defaults(
metaphor_tool_list[2],
)
下面展示一个完整的例子:
# Just pass the wrapped tools and the get_date utility
agent = OpenAIAgent.from_tools(
[*wrapped_retrieve.to_tool_list(), metaphor_tool_list[4]],
verbose=True,
)
print(agent.chat('Can you summarize everything published in the last month regarding news on superconductors'))
下面看一个agent调用多个工具的详细过程:
=== Calling Function ===
Calling function: current_date with args: {}
Got output: 2023-08-20
========================
=== Calling Function ===
Calling function: search_and_retrieve_documents with args: {
"query": "superconductors",
"start_published_date": "2023-07-20",
"end_published_date": "2023-08-20"
}
[Metaphor Tool] Autoprompt: "Here is an interesting article about superconductors:
Got output: Content loaded! You can now search the information using read_search_and_retrieve_documents
========================
=== Calling Function ===
Calling function: read_search_and_retrieve_documents with args: {
"query": "superconductors"
}
Got output:
Superconductors are materials that can perfectly conduct electricity. They are used in a variety of applications, such as particle accelerators, nuclear fusion devices, MRI machines, and maglev trains. However, so far, no superconductor has been proven to work at ambient pressures and temperatures. On July 22, scientists in South Korea published research claiming to have solved this problem with a material called LK-99, which has an electrical resistivity that drops to near zero at 30 degrees Celsius (86 degrees Fahrenheit).
========================
In the last month, there have been developments in the field of superconductors. Scientists in South Korea have published research on a material called LK-99, which has the ability to conduct electricity with near-zero resistance at a temperature of 30 degrees Celsius (86 degrees Fahrenheit). This breakthrough could potentially lead to the development of superconductors that work at ambient pressures and temperatures, opening up new possibilities for various applications such as particle accelerators, nuclear fusion devices, MRI machines, and maglev trains.
agent使用get_date工具来确定当前月份,然后在调用search时,根据发布日期应用Metaphor中的过滤器。使用retrieve_documents加载文档,并使用read_retrieve_documents读取这些文档。
参考文献:
[1] https://blog.llamaindex.ai/llamaindex-metaphor-towards-automating-knowledge-work-with-llms-5520a32efa2f
相关文章:

LLM之RAG实战(二):使用LlamaIndex + Metaphor实现知识工作自动化
最先进的大型语言模型(LLM),如ChatGPT、GPT-4、Claude 2,具有令人难以置信的推理能力,可以解锁各种用例——从洞察力提取到问答,再到通用工作流自动化。然而,他们检索上下文相关信息的能力有限。…...
【容器】Docker打包Linux操作系统迁移
0x0 场景 因老服务器操作系统文centos6.5,现要迁移至uos v20 1050a(底层centos8),其中需要迁移的应用组件有: mysql 、tomcat、apachehttpd,因版本跨越太大,导致centos8直接安装无法完全恢复原…...

redis基本数据结构
Redis入门:五大数据类型 文章目录 Redis入门:五大数据类型一.概述二.Redis的基本了解三.Redis五大数据类型1.String (字符串)2.List(列表)3.Set集合(元素唯一不重复)4.Hash集合5.zSet(有序集合) 一.概述 什么是Redis Redis(Remote Dictiona…...

Learning Normal Dynamics in Videos with Meta Prototype Network 论文阅读
文章信息:发表在cvpr2021 原文链接: Learning Normal Dynamics in Videos with Meta Prototype Network 摘要1.介绍2.相关工作3.方法3.1. Dynamic Prototype Unit3.2. 视频异常检测的目标函数3.3. 少样本视频异常检测中的元学习 4.实验5.总结代码复现&a…...

Unity 关于SpriteRenderer 和正交相机缩放
float oldWidth 750f;float oldHeight 1334f;float newWidth Screen.width;float newHeight Screen.height;float oldAspect oldWidth / oldHeight;float newAspect newWidth / newHeight;//水平方向缩放float horizontalCompressionRatio newAspect / oldAspect;//垂直…...

HarmonyOS应用开发者基础认证考试(98分答案)
基于最近大家都在考这个应用开发者基础认证考试,因此出了一期,一样复制word里面搜索做,很快,当然good luck 判断题 Ability是系统调度应用的最小单元,是能够完成一个独立功能的组件。一个应用可以包含一个或多个Ability。 正确(Tr…...
Ubuntu20.04 Kimera Semantic运行记录
Ubuntu20.04 Kimera Semantic 官方bag运行记录 以下基本为官方教程,有部分修改 依赖 sudo apt-get install python3-wstool python3-catkin-tools protobuf-compiler autoconf sudo apt-get install ros-noetic-cmake-modulessudo apt-get install ros-noetic-i…...

服务器RAID系统的常见故障,结合应用场景谈谈常规的维修处理流程
常见的服务器RAID系统故障包括硬盘故障、控制器故障、电源故障、写入错误和热插拔错误。下面结合这些故障的应用场景和常规维修处理流程来详细讨论: 硬盘故障: 应用场景:在服务器RAID系统中,硬盘故障是最常见的问题之一。硬盘可能…...

计算机网络——数据链路层-封装成帧(帧定界、透明传输-字节填充,比特填充、MTU)
目录 介绍 帧定界 PPP帧 以太网帧 透明传输 字节填充(字符填充) 比特填充 比特填充习题 MTU 介绍 所谓封装成帧,就是指数据链路层给上层交付下来的协议数据单元添加帧头和帧尾,使之成为帧。 例如下图所示: …...

MySQL笔记-第03章_基本的SELECT语句
视频链接:【MySQL数据库入门到大牛,mysql安装到优化,百科全书级,全网天花板】 文章目录 第03章_基本的SELECT语句1. SQL概述1.1 SQL背景知识1.2 SQL语言排行榜1.3 SQL 分类 2. SQL语言的规则与规范2.1 基本规则2.2 SQL大小写规范 …...

FTP服务文件上传失败,错误码553的排故过程
本文主要记录文件上传失败,错误码553的排故过程。 1 背景 树莓派通过FTP给嵌入式板卡传输文件,好几套设备,发现有的能传输成功,有的传输不成功。树莓派和嵌入式板卡都一样的,出现问题时感觉很懵。 2 逐项对比 2.1 自…...

音频录制软件哪个好?帮助你找到最合适的一款
音频录制软件是日常工作、学习和创作中不可或缺的一部分。选择一个适合自己需求的录音软件对于确保音频质量和提高工作效率至关重要。可是您知道音频录制软件哪个好吗?本文将深入探讨两种常见的音频录制软件,通过详细的步骤指南,帮助您了解它…...

9.Unity搭建HTTP服务器
搭建HTTP服务器的几种方式 //1.使用别人做好的HTTP服务器软件,一般作为资源服务器时使用该方式(学习阶段建议使用) //2.自己编写HTTP服务器应用程序,一般作为Web服务器 或者 短链接游戏服务器时 使用该方式 使用别人做好的HTTP服…...

C# 热键注册工具类
写在前面 介绍一个验证过的热键注册工具类,使用系统类库user32.dll中的RegisterHotkey函数来实现全局热键的注册。 代码实现 [Flags]public enum KeyModifiers{Alt 1,Control 2,Shift 4,Windows 8,NoRepeat 0x4000}public static class HotKeyHelper{[DllImp…...

nodejs微信小程序+python+PHP天天网站书城管理系统的设计与实现-计算机毕业设计推荐
目 录 摘 要 I ABSTRACT II 目 录 II 第1章 绪论 1 1.1背景及意义 1 1.2 国内外研究概况 1 1.3 研究的内容 1 第2章 相关技术 3 2.1 nodejs简介 4 2.2 express框架介绍 6 2.4 MySQL数据库 4 第3章 系统分析 5 3.1 需求分析 5 3.2 系统可行性分析 5 3.2.1技术可行性:…...
Hive环境准备[重点学习]
1.前提启动hadoop集群 hadoop在统一虚拟机中已经配置了环境变量 启动hdfs和yarn集群 命令:start-all.sh [rootnode1 /]# start-all.sh启动mr历史服务 命令:mapred --daemon start historyserver [rootnode1 /]# mapred --daemon start historyserver检查服务 命令:jps [r…...
软件工程 室友整理
如何理解结构化需求分析方法的基本思想; 结构化分析方法是一种面向数据流的需求分析方法,其中数据作为独立实体转换,数据建模定义数据的属性和关系,操作数据的处理建模表名当做数据在系统流动时候处理如何转换数据 简述面向对象的基本概念&a…...

JVM==>图解字节码指令
一,原始代码 我们来看一下执行这段代码的具体流程 那执行这段代码中 JVM就会把已经编译好的.class文件加载到内存中,交给CPU运行 1)常量池载入运行时常量池 我们发现 10 并没有被存入常量池中, 这是因为short范围以内的数字不会…...

MISRA C 2012 标准浅析
MISRA(The Motor Industry Software Reliability Association),汽车工业软件可靠性联会; 1994年,英国成立。致力于协助汽车厂商开发安全可靠的软件的跨国协会,其成员包括:AB汽车电子、罗孚汽车、宾利汽车、福特汽车、捷…...

Redis高可用之Sentinel哨兵模式
一、背景与简介 Redis关于高可用与分布式有三个与之相关的运维部署模式。分别是主从复制master-slave模式、哨兵Sentinel模式以及集群Cluster模式。 这三者都有各自的优缺点以及所应对的场景、对应的业务使用量与公司体量。 1、主从master-slave模式 【介绍】 这种模式可以采用…...

python打卡day49
知识点回顾: 通道注意力模块复习空间注意力模块CBAM的定义 作业:尝试对今天的模型检查参数数目,并用tensorboard查看训练过程 import torch import torch.nn as nn# 定义通道注意力 class ChannelAttention(nn.Module):def __init__(self,…...
Java多线程实现之Callable接口深度解析
Java多线程实现之Callable接口深度解析 一、Callable接口概述1.1 接口定义1.2 与Runnable接口的对比1.3 Future接口与FutureTask类 二、Callable接口的基本使用方法2.1 传统方式实现Callable接口2.2 使用Lambda表达式简化Callable实现2.3 使用FutureTask类执行Callable任务 三、…...

Mac下Android Studio扫描根目录卡死问题记录
环境信息 操作系统: macOS 15.5 (Apple M2芯片)Android Studio版本: Meerkat Feature Drop | 2024.3.2 Patch 1 (Build #AI-243.26053.27.2432.13536105, 2025年5月22日构建) 问题现象 在项目开发过程中,提示一个依赖外部头文件的cpp源文件需要同步,点…...
Xen Server服务器释放磁盘空间
disk.sh #!/bin/bashcd /run/sr-mount/e54f0646-ae11-0457-b64f-eba4673b824c # 全部虚拟机物理磁盘文件存储 a$(ls -l | awk {print $NF} | cut -d. -f1) # 使用中的虚拟机物理磁盘文件 b$(xe vm-disk-list --multiple | grep uuid | awk {print $NF})printf "%s\n"…...

使用LangGraph和LangSmith构建多智能体人工智能系统
现在,通过组合几个较小的子智能体来创建一个强大的人工智能智能体正成为一种趋势。但这也带来了一些挑战,比如减少幻觉、管理对话流程、在测试期间留意智能体的工作方式、允许人工介入以及评估其性能。你需要进行大量的反复试验。 在这篇博客〔原作者&a…...

Windows安装Miniconda
一、下载 https://www.anaconda.com/download/success 二、安装 三、配置镜像源 Anaconda/Miniconda pip 配置清华镜像源_anaconda配置清华源-CSDN博客 四、常用操作命令 Anaconda/Miniconda 基本操作命令_miniconda创建环境命令-CSDN博客...

FFmpeg:Windows系统小白安装及其使用
一、安装 1.访问官网 Download FFmpeg 2.点击版本目录 3.选择版本点击安装 注意这里选择的是【release buids】,注意左上角标题 例如我安装在目录 F:\FFmpeg 4.解压 5.添加环境变量 把你解压后的bin目录(即exe所在文件夹)加入系统变量…...

mac:大模型系列测试
0 MAC 前几天经过学生优惠以及国补17K入手了mac studio,然后这两天亲自测试其模型行运用能力如何,是否支持微调、推理速度等能力。下面进入正文。 1 mac 与 unsloth 按照下面的进行安装以及测试,是可以跑通文章里面的代码。训练速度也是很快的。 注意…...

DAY 45 超大力王爱学Python
来自超大力王的友情提示:在用tensordoard的时候一定一定要用绝对位置,例如:tensorboard --logdir"D:\代码\archive (1)\runs\cifar10_mlp_experiment_2" 不然读取不了数据 知识点回顾: tensorboard的发展历史和原理tens…...

react-pdf(pdfjs-dist)如何兼容老浏览器(chrome 49)
之前都是使用react-pdf来渲染pdf文件,这次有个需求是要兼容xp环境,xp上chrome最高支持到49,虽然说iframe或者embed都可以实现预览pdf,但为了后续的定制化需求,还是需要使用js库来渲染。 chrome 49测试环境 能用的测试…...