当前位置: 首页 > news >正文

AI--向量的存储和检索

step1 Document

LangChain 实现了Document抽象,旨在表示文本单元和相关元数据。它具有两个属性:

  • page_content:代表内容的字符串;
  • metadata:包含任意元数据的字典。

该metadata属性可以捕获有关文档来源、其与其他文档的关系以及其他信息的信息.单个Document对象通常代表较大文档的一部分。

from langchain_core.documents import Documentdocuments = [Document(page_content="Dogs are great companions, known for their loyalty and friendliness.",metadata = {"source": "mammal-pets-doc"},),Document(page_content="Cats are independent pets that often enjoy their own space.",metadata={"source": "mammal-pets-doc"},),Document(page_content="Goldfish are popular pets for beginners, requiring relatively simple care.",metadata={"source": "fish-pets-doc"},),Document(page_content="Parrots are intelligent birds capable of mimicking human speech.",metadata={"source": "bird-pets-doc"},),Document(page_content="Rabbits are social animals that need plenty of space to hop around.",metadata={"source": "mammal-pets-doc"},),
]

step2 向量检索

向量检索是一种常见的存储和检索非结构化数据的方式,主要思路是存储文本的数据向量,给出一个查询,我们编码查询成同一个维度的数据向量,然后使用相似度去查找相关数据
LangChain VectorStore对象包含用于将文本和Document对象添加到存储区以及使用各种相似度指标查询它们的方法。它们通常使用嵌入模型进行初始化,这些模型决定了如何将文本数据转换为数字向量。

下面我是使用bce-embedding模型作为编码模型,地址下载

from langchain.embeddings import HuggingFaceEmbeddings
from langchain_community.vectorstores.utils import DistanceStrategy# init embedding model
model_kwargs = {'device': 'cuda'}
encode_kwargs = {'batch_size': 64, 'normalize_embeddings': True}embed_model = HuggingFaceEmbeddings(model_name=EMBEDDING_PATH,model_kwargs=model_kwargs,encode_kwargs=encode_kwargs)
vetorstore = Chroma.from_documents(documents,embedding=embed_model,
)vetorstore.similarity_search("cat")

输出结果为:

[Document(page_content=‘Cats are independent pets that often enjoy their own space.’, metadata={‘source’: ‘mammal-pets-doc’}),
Document(page_content=‘Goldfish are popular pets for beginners, requiring relatively simple care.’, metadata={‘source’:
‘fish-pets-doc’}),
Document(page_content=‘Dogs are great companions, known for their loyalty and friendliness.’, metadata={‘source’:‘mammal-pets-doc’}),
Document(page_content=‘Parrots are intelligent> birds capable of mimicking human speech.’, metadata={‘source’:‘bird-pets-doc’})]

搜索返回相似度分数

vetorstore.similarity_search_with_score("cat")

[(Document(page_content=‘Cats are independent pets that often enjoy their own space.’, metadata={‘source’: ‘mammal-pets-doc’}),
0.9107884),
(Document(page_content=‘Goldfish are popular pets for beginners, requiring relatively simple care.’, metadata={‘source’: ‘fish-pets-doc’}),
1.3231826),
(Document(page_content=‘Dogs are great companions, known for their loyalty and friendliness.’, metadata={‘source’: ‘mammal-pets-doc’}),
1.4060305),
(Document(page_content=‘Parrots are intelligent birds capable of mimicking human speech.’, metadata={‘source’: ‘bird-pets-doc’}),
1.4284585),
(Document(page_content=‘Rabbits are social animals that need plenty of space to hop around.’, metadata={‘source’: ‘mammal-pets-doc’}),
1.4566814)]

上面结果返回的score,越小表示越接近

基于向量查询

embedding = embed_model.embed_query("cat")
vetorstore.similarity_search_by_vector(embedding)

输出结果

[Document(page_content=‘Cats are independent pets that often enjoy their own space.’, metadata={‘source’: ‘mammal-pets-doc’}),
Document(page_content=‘Goldfish are popular pets for beginners, requiring relatively simple care.’, metadata={‘source’: ‘fish-pets-doc’}),
Document(page_content=‘Dogs are great companions, known for their loyalty and friendliness.’, metadata={‘source’: ‘mammal-pets-doc’}),
Document(page_content=‘Parrots are intelligent birds capable of mimicking human speech.’, metadata={‘source’: ‘bird-pets-doc’})]

step3 检索

LangChainVectorStore对象没有Runnable子类,因此不能立即集成到 LangChain 表达语言链中。

LangChain Retrievers是 Runnable,因此它们实现了一组标准方法(例如同步和异步invoke操作batch)并且旨在纳入 LCEL 链。

我们可以自己创建一个简单的版本,而无需子类化Retriever。如果我们选择要使用的方法检索文档,我们可以轻松创建一个可运行的程序。下面我们将围绕该similarity_search方法构建一个:

from typing import Listfrom langchain_core.documents import Document
from langchain_core.runnables import RunnableLambdaretriever = RunnableLambda(vetorstore.similarity_search).bind(k=1)print(retriever.invoke("cat"))
print(retriever.batch(["cat","dog"]))

输出结果

[Document(page_content=‘Cats are independent pets that often enjoy their own space.’, metadata={‘source’: ‘mammal-pets-doc’})]
[[Document(page_content=‘Cats are independent pets that often enjoy their own space.’, metadata={‘source’: ‘mammal-pets-doc’})], [Document(page_content=‘Dogs are great companions, known for their loyalty and friendliness.’, metadata={‘source’: ‘mammal-pets-doc’})]]

Vectorstore 实现了as_retriever一个生成 Retriever 的方法,特别是VectorStoreRetriever。这些检索器包括特定的search_type属性search_kwargs,用于标识要调用的底层向量存储的哪些方法以及如何参数化它们。

retriever = vetorstore.as_retriever(search_type="similarity",search_kwargs={"k": 1},
)retriever.batch(["cat", "shark"])

输出结果

[[Document(page_content=‘Cats are independent pets that often enjoy their own space.’, metadata={‘source’: ‘mammal-pets-doc’})],
[Document(page_content=‘Goldfish are popular pets for beginners, requiring relatively simple care.’, metadata={‘source’: ‘fish-pets-doc’})]]

检索器可以轻松地合并到更复杂的应用程序中,例如检索增强生成(RAG)应用程序,

from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthroughchat = ChatOpenAI()message = """
Answer this question using the provided context only.{question}Context:
{context}
"""retriever = vetorstore.as_retriever(search_type="similarity",search_kwargs={"k": 1},
)prompt = ChatPromptTemplate.from_messages([("human",message),]
)rag_chat = {"context":retriever,"question":RunnablePassthrough()} | prompt |chatresponse = rag_chat.invoke("tell me about cats")
print(response.content)

输出结果

Cats are independent pets that often enjoy their own space.

相关文章:

  • Java开发大厂面试第20讲:什么是分布式锁?Redi 怎样实现的分布式锁?
  • 如何为ChatGPT编写有效的提示词:软件开发者的指南
  • Servlet的response对象
  • 爬虫实训案例:中国大学排名
  • [保姆式教程]使用目标检测模型YOLO V8 OBB进行旋转目标的检测:训练自己的数据集(基于卫星和无人机的农业大棚数据集)
  • 大模型日报|今日必读的 13 篇大模型论文
  • 【html5】03-新表单元素及属性
  • VUE面试题(3)--vue常见面试题
  • 使用API有效率地管理Dynadot域名,进行域名邮箱的默认邮件转发设置
  • 如何解决vcruntime140.dll丢失问题,详细介绍5种靠谱的解决方法
  • 2001-2022年全国31省份互联网发展47个指标合集各省电信业务信息化软件信息技术服务业
  • chatgpt功能真的强大好用吗?
  • angular插值语法与属性绑定
  • 创建namespace级别权限
  • C++报错:没有与参数列表匹配的构造函数 (能确定类型是正确的)
  • 2017前端实习生面试总结
  • css系列之关于字体的事
  • Docker入门(二) - Dockerfile
  • Fundebug计费标准解释:事件数是如何定义的?
  • GDB 调试 Mysql 实战(三)优先队列排序算法中的行记录长度统计是怎么来的(上)...
  • Hibernate最全面试题
  • MySQL Access denied for user 'root'@'localhost' 解决方法
  • MySQL主从复制读写分离及奇怪的问题
  • Node + FFmpeg 实现Canvas动画导出视频
  • orm2 中文文档 3.1 模型属性
  • 阿里云Kubernetes容器服务上体验Knative
  • 对JS继承的一点思考
  • 工程优化暨babel升级小记
  • 工作中总结前端开发流程--vue项目
  • 开源地图数据可视化库——mapnik
  • 前端性能优化——回流与重绘
  • 使用 QuickBI 搭建酷炫可视化分析
  • 使用iElevator.js模拟segmentfault的文章标题导航
  • 腾讯大梁:DevOps最后一棒,有效构建海量运营的持续反馈能力
  • 为什么要用IPython/Jupyter?
  • 想晋级高级工程师只知道表面是不够的!Git内部原理介绍
  • JavaScript 新语法详解:Class 的私有属性与私有方法 ...
  • 机器人开始自主学习,是人类福祉,还是定时炸弹? ...
  • ​软考-高级-系统架构设计师教程(清华第2版)【第1章-绪论-思维导图】​
  • ​一、什么是射频识别?二、射频识别系统组成及工作原理三、射频识别系统分类四、RFID与物联网​
  • ​总结MySQL 的一些知识点:MySQL 选择数据库​
  • #!/usr/bin/python与#!/usr/bin/env python的区别
  • #Linux杂记--将Python3的源码编译为.so文件方法与Linux环境下的交叉编译方法
  • (13)DroneCAN 适配器节点(一)
  • (3)nginx 配置(nginx.conf)
  • (zz)子曾经曰过:先有司,赦小过,举贤才
  • (第9篇)大数据的的超级应用——数据挖掘-推荐系统
  • (三)SvelteKit教程:layout 文件
  • (四)Android布局类型(线性布局LinearLayout)
  • (五)大数据实战——使用模板虚拟机实现hadoop集群虚拟机克隆及网络相关配置
  • (转)Java socket中关闭IO流后,发生什么事?(以关闭输出流为例) .
  • .NET C#版本和.NET版本以及VS版本的对应关系
  • .NET Core IdentityServer4实战-开篇介绍与规划
  • .NET MVC、 WebAPI、 WebService【ws】、NVVM、WCF、Remoting
  • .net Stream篇(六)