LLM-阿里 DashVector + langchain self-querying retriever 优化 RAG 实践【Query 优化】

news/2024/9/13 21:37:54/ 标签: langchain, AI, LLM

文章目录

  • 前言
  • self querying 简介
  • 代码实现
  • 总结

前言

现在比较流行的 RAG 检索就是通过大模型 embedding 算法将数据嵌入向量数据库中,然后在将用户的查询向量化,从向量数据库中召回相似性数据,构造成 context template, 放到 LLM 中进行查询。

如果说将用户的查询语句直接转换为向量查询可能并不会得到很好的结果,比如说我们往向量数据库中存入了一些商品向量,现在用户说:“我想要一条价格低于20块的黑色羊毛衫”,如果使用传统的嵌入算法,该查询语句转换为向量查询就可能“失帧”,被转换为查询黑色羊毛衫。

针对这种情况我们就会使用一些优化检索查询语句方式来优化 RAG 查询,其中 AIN.html" title=langchain>langchain 的 self-querying 就是一种很好的方式,这里使用阿里云的 DashVector 向量数据库和 DashScope LLM 来进行尝试,优化后的查询效果还是挺不错的。


现在很多网上的资料都是使用 OpenAI 的 Embedding 和 LLM,但是个人角色现在国内阿里的 LLM 和向量数据库已经非常好了,而且 OpenAI 已经禁用了国内的 API 调用,国内的云服务又便宜又好用,真的不尝试一下么?关于 DashVector 和 DashScope 我之前写了几篇实践篇,大家感兴趣的可以参考下:

LLM-文本分块(AIN.html" title=langchain>langchain)与向量化(阿里云DashVector)存储,嵌入LLM实践
LLM-阿里云 DashVector + ModelScope 多模态向量化实时文本搜图实战总结
LLM-AIN.html" title=langchain>langchain 与阿里 DashScop (通义千问大模型) 和 DashVector(向量数据库) 结合使用总结

前提条件

  • 确保开通了通义千问 API key 和 向量检索服务 API KEY
  • 安装依赖:
    pip install AIN.html" title=langchain>langchain
    pip install AIN.html" title=langchain>langchain-community
    pip install dashVector
    pip install dashscope

self querying 简介

简单来说就是通过 self-querying 的方式我们可以将用户的查询语句进行结构化转换,转换为包含两层意思的向量化数据:

  • Query: 和查询语义相近的向量查询
  • Filter: 关于查询内容的一些 metadata 数据

image.png
比如说上图中用户输入:“bar 说了关于 foo 的什么东西?”,self-querying 结构化转换后就变为了两层含义:

  • 查询关于 foo 的数据
  • 其中作者为 bar

代码实现

DASHSCOPE_API_KEY, DASHVECTOR_API_KEY, DASHVECTOR_ENDPOINT替换为自己在阿里云开通的。

import osfrom AIN.html" title=langchain>langchain_core.documents import Document
from AIN.html" title=langchain>langchain_community.vectorstores.dashvector import DashVector
from AIN.html" title=langchain>langchain_community.embeddings.dashscope import DashScopeEmbeddings
from AIN.html" title=langchain>langchain.chains.query_constructor.base import AttributeInfo
from AIN.html" title=langchain>langchain.retrievers.self_query.base import SelfQueryRetriever
from AIN.html" title=langchain>langchain_community.chat_models.tongyi import ChatTongyi
from AIN.html" title=langchain>langchain_core.vectorstores import VectorStoreclass SelfQuerying:def __init__(self):# 我们需要同时开通 DASHSCOPE_API_KEY 和 DASHVECTOR_API_KEYos.environ["DASHSCOPE_API_KEY"] = ""os.environ["DASHVECTOR_API_KEY"] = ""os.environ["DASHVECTOR_ENDPOINT"] = ""self.llm = ChatTongyi(temperature=0)def handle_embeddings(self)->'VectorStore':docs = [Document(page_content="A bunch of scientists bring back dinosaurs and mayhem breaks loose",metadata={"year": 1993, "rating": 7.7, "genre": "science fiction"},),Document(page_content="Leo DiCaprio gets lost in a dream within a dream within a dream within a ...",metadata={"year": 2010, "director": "Christopher Nolan", "rating": 8.2},),Document(page_content="A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea",metadata={"year": 2006, "director": "Satoshi Kon", "rating": 8.6},),Document(page_content="A bunch of normal-sized women are supremely wholesome and some men pine after them",metadata={"year": 2019, "director": "Greta Gerwig", "rating": 8.3},),Document(page_content="Toys come alive and have a blast doing so",metadata={"year": 1995, "genre": "animated"},),Document(page_content="Three men walk into the Zone, three men walk out of the Zone",metadata={"year": 1979,"director": "Andrei Tarkovsky","genre": "thriller","rating": 9.9,},),]# 指定向量数据库中的 Collection namevectorstore = DashVector.from_documents(docs, DashScopeEmbeddings(), collection_name="AIN.html" title=langchain>langchain")return vectorstoredef build_querying_retriever(self, vectorstore: 'VectorStore', enable_limit: bool=False)->'SelfQueryRetriever':"""构造优化检索:param vectorstore: 向量数据库:param enable_limit: 是否查询 Top k:return:"""metadata_field_info = [AttributeInfo(name="genre",description="The genre of the movie. One of ['science fiction', 'comedy', 'drama', 'thriller', 'romance', 'action', 'animated']",type="string",),AttributeInfo(name="year",description="The year the movie was released",type="integer",),AttributeInfo(name="director",description="The name of the movie director",type="string",),AttributeInfo(name="rating", description="A 1-10 rating for the movie", type="float"),]document_content_description = "Brief summary of a movie"retriever = SelfQueryRetriever.from_llm(self.llm,vectorstore,document_content_description,metadata_field_info,enable_limit=enable_limit)return retrieverdef handle_query(self, query: str):"""返回优化查询后的检索结果:param query::return:"""# 使用 LLM 优化查询向量,构造优化后的检索retriever = self.build_querying_retriever(self.handle_embeddings())response = retriever.invoke(query)return responseif __name__ == '__main__':q = SelfQuerying()# 只通过查询属性过滤print(q.handle_query("I want to watch a movie rated higher than 8.5"))# 通过查询属性和查询语义内容过滤print(q.handle_query("Has Greta Gerwig directed any movies about women"))# 复杂过滤查询print(q.handle_query("What's a highly rated (above 8.5) science fiction film?"))# 复杂语义和过滤查询print(q.handle_query("What's a movie after 1990 but before 2005 that's all about toys, and preferably is animated"))

上边的代码主要步骤有三步:

  • 执行 embedding, 将带有 metadata 的 Doc 嵌入 DashVector
  • 构造 self-querying retriever,需要预先提供一些关于我们的文档支持的元数据字段的信息以及文档内容的简短描述。
  • 执行查询语句

执行代码输出查询内容如下:

# "I want to watch a movie rated higher than 8.5"
[Document(page_content='Three men walk into the Zone, three men walk out of the Zone', metadata={'director': 'Andrei Tarkovsky', 'genre': 'thriller', 'rating': 9.9, 'year': 1979}),Document(page_content='A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea', metadata={'director': 'Satoshi Kon', 'rating': 8.6, 'year': 2006})]# "Has Greta Gerwig directed any movies about women"
[Document(page_content='A bunch of normal-sized women are supremely wholesome and some men pine after them', metadata={'director': 'Greta Gerwig', 'rating': 8.3, 'year': 2019})]# "What's a highly rated (above 8.5) science fiction film?"
[Document(page_content='A bunch of normal-sized women are supremely wholesome and some men pine after them', metadata={'director': 'Greta Gerwig', 'rating': 8.3, 'year': 2019})]# "What's a movie after 1990 but before 2005 that's all about toys, and preferably is animated"
[Document(page_content='Toys come alive and have a blast doing so', metadata={'genre': 'animated', 'year': 1995})]

总结

本文主要讲了如何使用 AIN.html" title=langchain>langchain 的 self-query 来优化向量检索,我们使用的是阿里云的 DashVector 和 DashScope LLM 进行的代码演示,读者可以开通下,体验尝试一下。


http://www.ppmy.cn/news/1475710.html

相关文章

网站开发:使用VScode安装yarn包和运行前端项目

一、首先打开PowerShell-管理员身份运行ISE 输入命令: set-ExecutionPolicy RemoteSigned 选择“全是”,表示允许在本地计算机上运行由本地用户创建的脚本,没有报错就行了 二、接着打开VScode集成终端 输入 npm install -g yarn 再次输入以…

人工智能算法工程师(中级)课程12-PyTorch神经网络之LSTM和GRU网络与代码详解1

大家好,我是微学AI,今天给大家介绍一下人工智能算法工程师(中级)课程12-PyTorch神经网络之LSTM和GRU网络与代码详解。在深度学习领域,循环神经网络(RNN)因其处理序列数据的能力而备受关注。然而,传统的RNN存在梯度消失和梯度爆炸的问题,这使得它在长序列任务中的表现不尽…

CSS图像不透明度的艺术:探索透明度控制的无限可能

在网页设计中,图像的不透明度(Opacity)和透明度(Transparency)是两个关键的概念,它们不仅影响着页面的视觉效果,还能增强用户体验,创造丰富的交互效果。通过调整图像的不透明度&…

Matplotlib库学习之mpl_toolkits.mplot3d.Axes3D函数

Matplotlib库学习之mpl_toolkits.mplot3d.Axes3D函数 一、简介 mpl_toolkits.mplot3d.Axes3D 是 Matplotlib 的 mpl_toolkits.mplot3d 工具包中的一个类,用于创建三维坐标轴(3D Axes)。这个类继承自 matplotlib.axes.Axes,提供了…

el-table的selection多选表格改为单选

需求场景: 选择表格数据时&#xff0c;需要控制单条数据的操作按钮是否禁用。 效果图: html代码: <div><el-tableref"multipleTable":data"tableData"tooltip-effect"dark"style"width: 100%"selection-change"handl…

【Pytorch实战教程】对抗样本生成中是如何添加噪声的?

文章目录 对抗样本中添加随机生成的对抗噪声代码解析应用场景示例代码对抗样本中添加随机生成的对抗噪声 通常在对抗训练或者生成对抗样本时使用,目的是为了稍微扰动模型的输入数据,从而测试或增强模型在面对输入数据轻微变化时的鲁棒性。 x = x + torch.zeros_like(x).uni…

普中51单片机:串口通信原理与应用指南(八)

文章目录 引言接口及引脚定义硬件电路电平标准常见通信接口比较51单片机的UART工作模式串口参数及时序图波特率&#xff08;Baud Rate&#xff09;数据位&#xff08;Data Bits&#xff09;校验位&#xff08;Parity Bit&#xff09; 串口相关寄存器串口控制寄存器SCON电源控制…

k8s怎么配置secret呢?

在Kubernetes中&#xff0c;配置Secret主要涉及到创建、查看和使用Secret的过程。以下是配置Secret的详细步骤和相关信息&#xff1a; ### 1. Secret的概念 * Secret是Kubernetes用来保存密码、token、密钥等敏感数据的资源对象。 * 这些敏感数据可以存放在Pod或镜像中&#x…

Hive 常见问题

Hive 内部表和外部表的区别 外部表在创建时需要加关键字 external&#xff1b;创建内部表时&#xff0c;会将数据移动到数据仓库指定的路径&#xff1b;创建外部表时&#xff0c;不会移动数据&#xff0c;只会记录数据所在的路径&#xff1b;删除内部表时&#xff0c;会删除元…

爬虫技术探索:Node.js 的优势与实践

在大数据时代&#xff0c;数据挖掘与分析成为了企业和研究机构的重要工作之一。而网络爬虫作为获取公开网络数据的关键工具&#xff0c;其重要性不言而喻。在众多编程语言中&#xff0c;Node.js 因其异步非阻塞I/O模型、丰富的第三方库支持以及与现代Web技术的紧密集成&#xf…

Android系统上常见的性能优化工具

Android系统上常见的性能优化工具 在Android系统开发中&#xff0c;性能优化是一个重要的任务&#xff0c;有许多工具可以帮助你进行各种方面的性能分析和优化。以下是一些常见的Android性能优化工具及其用途和使用方法&#xff1a; 1. Android Studio Profiler 功能: 提供CP…

qt 创建一个矩形,矩形的边线可以拖拽

在Qt中&#xff0c;要创建一个矩形&#xff0c;其边线可以拖拽&#xff0c;你可以使用QGraphicsView和QGraphicsScene来实现。以下是一个简单的示例&#xff0c;展示如何创建一个矩形&#xff0c;并且它的边线可以被拖拽来改变矩形的大小。 首先&#xff0c;你需要包含必要的Q…

vs code 启动react项目,执行npm start报错原因分析

1.执行 npm start错误信息&#xff1a;npm : 无法将“npm”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写&#xff0c;如果包括路径&#xff0c;请确保路径正确&#xff0c;然后再试一次。 所在位置 行:1 字符: 1 npm start ~~~ CategoryInfo …

【Python百日进阶-Web开发-音频】Day702 - librosa安装及模块一览表

文章目录 一、Librosa简介与安装1.1 Librosa是什么1.2 Librosa官网 二、Librosa安装2.1 安装Librosa 三、安装ffmpeg3.1 ffmpeg官网下载3.2 ffmpeg安装3.2.1 解压3.2.2 添加环境变量3.2.3 测试ffmpeg是否安装成功 四、Librosa 库模块一览4.1 库函数结构4.2 Audio processing&am…

cuda缓存示意图

一、定义 cuda 缓存示意图gpu 架构示意图gpu 内存访问示意图 二、实现 cuda 缓存示意图 DRAM: 通常指的是GPU的显存&#xff0c;位于GPU芯片外部&#xff0c;通过某种接口&#xff08;如PCIE&#xff09;与GPU芯片相连。它是GPU访问的主要数据存储区域&#xff0c;用于存储大…

1.31、基于长短记忆网络(LSTM)的发动机剩余寿命预测(matlab)

1、基于长短记忆网络(LSTM)的发动机剩余寿命预测的原理及流程 基于长短期记忆网络(LSTM)的发动机剩余寿命预测是一种常见的机器学习应用&#xff0c;用于分析和预测发动机或其他设备的剩余可用寿命。下面是LSTM用于发动机剩余寿命预测的原理和流程&#xff1a; 数据收集&#…

数据中心巡检机器人助力,河南某数据中心机房智能化辅助项目交付

随着数据中心规模的不断扩大和业务需求的不断增长&#xff0c;确保其高效、安全、稳定地运行变得愈发重要。传统的人力巡检方式存在效率低、误差高、成本大等问题&#xff0c;难以满足现代数据中心的需求。为解决这些挑战&#xff0c;智能巡检机器人应运而生&#xff0c;成为数…

[PaddlePaddle飞桨] PaddleOCR-光学字符识别-小模型部署

PaddleOCR的GitHub项目地址 推荐环境&#xff1a; PaddlePaddle > 2.1.2 Python > 3.7 CUDA > 10.1 CUDNN > 7.6pip下载指令&#xff1a; python -m pip install paddlepaddle-gpu2.5.1 -i https://pypi.tuna.tsinghua.edu.cn/simple pip install paddleocr2.7…

周报(1)<仅供自己学习>

文章目录 一.pytorch学习1.配置GPU2.数据读取问题1&#xff08;已解决问题2&#xff08;已解决 3.卷积的学习 二.NeRF学习1.介绍部分问题1&#xff08;已解决 2.神经辐射场表示问题2&#xff08;已解决问题3&#xff08;已解决问题4&#xff08;已解决问题5&#xff1a;什么是视…

2 Java的基本程序设计结构(基本语法1)

文章目录 前言一、数据类型0 与Python的一些区别1 基本数据类型(1)整型(2)浮点数类型(3)字符(char)类型(4)布尔类型(true、false)(5)代码示例2 引用数据类型二、变量与常量1 变量2 常量(*)3 枚举类型变量(*)4 变量的作用域三、变量和类起名规范1 硬性要求(变量…