Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >【LangChain系列】第四节:向量数据库与嵌入

【LangChain系列】第四节:向量数据库与嵌入

原创
作者头像
Freedom123
发布于 2024-05-20 10:08:59
发布于 2024-05-20 10:08:59
56806
代码可运行
举报
文章被收录于专栏:AIGCAIGC
运行总次数:6
代码可运行

toc


在这篇博文中,我们将探讨向量存储和嵌入,它们是构建聊天机器人和对数据语料库执行语义搜索的最重要组件。

一、工作流

回想一下检索增强生成 (RAG) 的整个工作流程:

我们从文档开始,创建这些文档的较小拆分,为这些拆分生成嵌入,然后将它们存储在矢量存储中。向量存储是一个数据库,您可以在以后轻松查找类似的向量。

二、安装

设置适当的环境变量并加载我们将要处理的文档 - cs229_lectures:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
import os
from langchain_openai import OpenAI
from dotenv import load_dotenv, find_dotenv
from langchain_community.document_loaders.pdf import PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter

_ = load_dotenv(find_dotenv())
client = OpenAI(
    api_key=os.getenv("OPENAI_API_KEY")
)
loaders = [
    PyPDFLoader("docs/cs229_lectures/MachineLearning-Lecture01.pdf"), # Duplicate documents on purpose - messy data
    PyPDFLoader("docs/cs229_lectures/MachineLearning-Lecture01.pdf"),
    PyPDFLoader("docs/cs229_lectures/MachineLearning-Lecture02.pdf"),
    PyPDFLoader("docs/cs229_lectures/MachineLearning-Lecture03.pdf"),
]
docs = []
for loader in loaders:
    docs.extend(loader.load())
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1500, chunk_overlap=150)
splits = text_splitter.split_documents(docs)
print("Length of splits: ", len(splits)) # Length of splits:  209

三、嵌入

现在,我们已经将文档拆分为更小的、语义上有意义的块,是时候为它们创建嵌入了。嵌入获取一段文本并创建该文本的数字表示,以便具有相似内容的文本在此数字空间中具有相似的向量。这使我们能够比较这些向量并找到相似的文本片段。

为了说明这一点,让我们尝试一些玩具示例:

代码语言:python
代码运行次数:5
运行
AI代码解释
复制
from langchain_openai import OpenAIEmbeddings
import numpy as np

embedding = OpenAIEmbeddings()
sentence1 = "i like dogs"
sentence2 = "i like canines"
sentence3 = "the weather is ugly outside"
embedding1 = embedding.embed_query(sentence1)
embedding2 = embedding.embed_query(sentence2)
embedding3 = embedding.embed_query(sentence3)
print(np.dot(embedding1, embedding2))  # 0.9631227500523609
print(np.dot(embedding1, embedding3))  # 0.7703257495981695
print(np.dot(embedding2, embedding3))  # 0.7591627401108028

不出所料,关于宠物的前两句话有非常相似的嵌入(点积为 0.96),而关于天气的句子与两个与宠物相关的句子不太相似(点积为 0.77 和 0.76)。

四、向量存储

接下来,我们将这些嵌入存储在向量存储中,这将使我们能够在以后尝试查找给定问题的相关文档时轻松查找类似的向量。

在本课中,我们将使用 Chroma 矢量存储,因为它是轻量级的,并且在内存中,因此很容易上手:

代码语言:python
代码运行次数:1
运行
AI代码解释
复制
from langchain.vectorstores import Chroma

persist_directory = "docs/chroma/"
# this code is only for ipynb files
# !rm -rf ./docs/chroma  # remove old database files if any 
vectordb = Chroma.from_documents(
    documents=splits, embedding=embedding, persist_directory=persist_directory
)
print(vectordb._collection.count())  # 209

五、相似性检索

相似性搜索是如何工作的:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
question = "is there an email i can ask for help"
docs = vectordb.similarity_search(question, k=3)
print("Length of context docs: ", len(docs))  # 3
print(docs[0].page_content)
代码语言:shell
AI代码解释
复制
cs229-qa@cs.stanford.edu. This goes to an acc ount that's read by all the TAs and me. So 
rather than sending us email individually, if you send email to this account, it will 
actually let us get back to you maximally quickly with answers to your questions.  
If you're asking questions about homework probl ems, please say in the subject line which 
assignment and which question the email refers to, since that will also help us to route 
your question to the appropriate TA or to me  appropriately and get the response back to 
you quickly.  
Let's see. Skipping ahead — let's see — for homework, one midterm, one open and term 
project. Notice on the honor code. So one thi ng that I think will help you to succeed and 
do well in this class and even help you to enjoy this cla ss more is if you form a study 
group.  
So start looking around where you' re sitting now or at the end of class today, mingle a 
little bit and get to know your classmates. I strongly encourage you to form study groups 
and sort of have a group of people to study with and have a group of your fellow students 
to talk over these concepts with. You can also  post on the class news group if you want to 
use that to try to form a study group.  
But some of the problems sets in this cla ss are reasonably difficult.  People that have 
taken the class before may tell you they were very difficult. And just I bet it would be 
more fun for you, and you'd probably have a be tter learning experience if you form a

这将返回提及 cs229-qa@cs.stanford.edu 电子邮件地址的相关块,用于询问有关课程材料的问题。

在此之后,让我们保留向量数据库以备将来使用:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
vectordb.persist()

六、故障模式

虽然基本的语义搜索效果很好,但可能会出现一些边缘情况和故障模式。让我们来探讨其中的一些。

1.重复文档

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
question = "what did they say about matlab?"
docs = vectordb.similarity_search(question, k=5)
print(docs[0].page_content)
# Document(page_content='those homeworks will be done in either MATLA B or in Octave, which is sort of — I \nknow some people call it a free ve rsion of MATLAB, which it sort  of is, sort of isn\'t.  \nSo I guess for those of you that haven\'t s een MATLAB before, and I know most of you \nhave, MATLAB is I guess part of the programming language that makes it very easy to write codes using matrices, to write code for numerical routines, to move data around, to \nplot data. And it\'s sort of an extremely easy to  learn tool to use for implementing a lot of \nlearning algorithms.  \nAnd in case some of you want to work on your  own home computer or something if you \ndon\'t have a MATLAB license, for the purposes of  this class, there\'s also — [inaudible] \nwrite that down [inaudible] MATLAB — there\' s also a software package called Octave \nthat you can download for free off the Internet. And it has somewhat fewer features than MATLAB, but it\'s free, and for the purposes of  this class, it will work for just about \neverything.  \nSo actually I, well, so yeah, just a side comment for those of you that haven\'t seen \nMATLAB before I guess, once a colleague of mine at a different university, not at \nStanford, actually teaches another machine l earning course. He\'s taught it for many years. \nSo one day, he was in his office, and an old student of his from, lik e, ten years ago came \ninto his office and he said, "Oh, professo r, professor, thank you so much for your', metadata={'page': 8, 'source': 'docs/cs229_lectures/MachineLearning-Lecture01.pdf'})
print(docs[1].page_content)
# Document(page_content='those homeworks will be done in either MATLA B or in Octave, which is sort of — I \nknow some people call it a free ve rsion of MATLAB, which it sort  of is, sort of isn\'t.  \nSo I guess for those of you that haven\'t s een MATLAB before, and I know most of you \nhave, MATLAB is I guess part of the programming language that makes it very easy to write codes using matrices, to write code for numerical routines, to move data around, to \nplot data. And it\'s sort of an extremely easy to  learn tool to use for implementing a lot of \nlearning algorithms.  \nAnd in case some of you want to work on your  own home computer or something if you \ndon\'t have a MATLAB license, for the purposes of  this class, there\'s also — [inaudible] \nwrite that down [inaudible] MATLAB — there\' s also a software package called Octave \nthat you can download for free off the Internet. And it has somewhat fewer features than MATLAB, but it\'s free, and for the purposes of  this class, it will work for just about \neverything.  \nSo actually I, well, so yeah, just a side comment for those of you that haven\'t seen \nMATLAB before I guess, once a colleague of mine at a different university, not at \nStanford, actually teaches another machine l earning course. He\'s taught it for many years. \nSo one day, he was in his office, and an old student of his from, lik e, ten years ago came \ninto his office and he said, "Oh, professo r, professor, thank you so much for your', metadata={'page': 8, 'source': 'docs/cs229_lectures/MachineLearning-Lecture01.pdf'})

注意,前两个结果是相同的。这是因为我们之前有意复制了第一讲的 PDF,导致相同的信息出现在两个不同的块中。理想情况下,我们希望检索不同的块。

2.未捕获结构化信息

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
question = "what did they say about regression in the third lecture?"
docs = vectordb.similarity_search(question, k=5)

for doc in docs:
    print(doc.metadata)
# {'page': 0, 'source': 'docs/cs229_lectures/MachineLearning-Lecture03.pdf'}
# {'page': 14, 'source': 'docs/cs229_lectures/MachineLearning-Lecture03.pdf'}
# {'page': 0, 'source': 'docs/cs229_lectures/MachineLearning-Lecture02.pdf'}
# {'page': 6, 'source': 'docs/cs229_lectures/MachineLearning-Lecture03.pdf'}
# {'page': 8, 'source': 'docs/cs229_lectures/MachineLearning-Lecture01.pdf'}
print(docs[4].page_content)
代码语言:shell
AI代码解释
复制
into his office and he said, "Oh, professo r, professor, thank you so much for your 
machine learning class. I learned so much from it. There's this stuff that I learned in your 
class, and I now use every day. And it's help ed me make lots of money, and here's a 
picture of my big house."  
So my friend was very excited. He said, "W ow. That's great. I'm glad to hear this 
machine learning stuff was actually useful. So what was it that you learned? Was it 
logistic regression? Was it the PCA? Was it the data ne tworks? What was it that you 
learned that was so helpful?" And the student said, "Oh, it was the MATLAB."  
So for those of you that don't know MATLAB yet, I hope you do learn it. It's not hard, 
and we'll actually have a short MATLAB tutori al in one of the discussion sections for 
those of you that don't know it.  
Okay. The very last piece of logistical th ing is the discussion s ections. So discussion 
sections will be taught by the TAs, and atte ndance at discussion sections is optional, 
although they'll also be recorded and televi sed. And we'll use the discussion sections 
mainly for two things. For the next two or th ree weeks, we'll use the discussion sections 
to go over the prerequisites to this class or if some of you haven't seen probability or 
statistics for a while or maybe algebra, we'll go over those in the discussion sections as a 
refresher for those of you that want one.

在这种情况下,我们期望所有检索到的文件都来自问题中指定的第三讲。但是,我们看到结果也包括来自其他讲座的块。这里的直觉是,关于仅查询第三讲的结构化信息并未在语义嵌入中捕获,语义嵌入更侧重于回归本身的概念。

小节

在这篇博文中,我们介绍了使用向量存储和嵌入进行语义搜索的基础知识,以及可能出现的一些边缘情况和故障模式。在下一篇博客中,我们将讨论如何解决这些故障模式并增强我们的检索能力,确保我们检索相关和不同的块,同时将结构化信息合并到搜索过程中。

小编是一名热爱人工智能的专栏作者,致力于分享人工智能领域的最新知识、技术和趋势。这里,你将能够了解到人工智能的最新应用和创新,探讨人工智能对未来社会的影响,以及探索人工智能背后的科学原理和技术实现。欢迎大家点赞,评论,收藏,让我们一起探索人工智能的奥秘,共同见证科技的进步!

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
【LangChain系列】第一节:文档加载
LangChain提供了一套强大的文档加载器,简化了从PDF、网站、YouTube视频和专有数据库(如Notion)等不同来源加载和标准化数据的过程。这篇博文我们将学习LangChain的文档加载功能,涵盖了各种加载器类型、实际应用和代码示例,使你能够轻松地将数据集成到你的机器学习工作流程中。
Freedom123
2024/05/15
6870
LangChain学习:Chat with Your Data
这块没有跑通,大概就是下载视频提取语音,调用OpenAIWhisperParser转成文字
Michael阿明
2023/07/25
1.5K0
LangChain学习:Chat with Your Data
【LangChain系列】第二节:文档拆分
在上一篇博客中,我们学习了如何使用LangChain的文档加载器将文档加载为标准格式。加载文档后,下一步是将它们拆分为更小的块。这个过程乍一看似乎很简单,但有一些微妙之处和重要的考虑因素会显着影响下游任务的性能和准确性。
Freedom123
2024/05/16
1.2K0
【腾讯云云上实验室】向量数据库+LangChain+LLM搭建智慧辅导系统实践
得益于深度学习的快速发展和数据规模的不断扩大,以GPT、混元、T5等为代表的大语言模型具备了前所未有的自然语言处理和生成能力,然而,在实际应用中,大语言模型的高效存储、检索和推理成为了一个新的挑战。
中杯可乐多加冰
2023/11/25
1.7K1
【LangChain系列7】【LangChain实战—客服机器人项目】
总结: LangChain是一个用于开发由LLM支持的应用程序的框架,通过提供标准化且丰富的模块抽象,构建LLM的输入输出规范,主要是利用其核心概念chains,可以灵活地链接整个应用开发流程。(即,其中的每个模块抽象,都是源于对大模型的深入理解和实践经验,由许多开发者提供出来的标准化流程和解决方案的抽象,再通过灵活的模块化组合,才得到了langchain)
Alice师傅的好宝宝
2025/01/14
5580
如何使用LangChain和OpenAI总结大型文档
大型语言模型让许多任务变得更加容易,例如制作聊天机器人、语言翻译、文本总结等。我们曾经编写模型来进行总结,然后总是存在性能问题。现在,我们可以使用大型语言模型 (LLM) 轻松地完成此操作。例如,最先进 (SOTA) 的 LLM 已经可以在其上下文窗口中处理整本书。但在总结非常大的文档时仍然存在一些限制。
云云众生s
2024/04/24
9230
【LangChain系列3】【检索模块详解】
总结: LangChain是一个用于开发由LLM支持的应用程序的框架,通过提供标准化且丰富的模块抽象,构建LLM的输入输出规范,主要是利用其核心概念chains,可以灵活地链接整个应用开发流程。(即,其中的每个模块抽象,都是源于对大模型的深入理解和实践经验,由许多开发者提供出来的标准化流程和解决方案的抽象,再通过灵活的模块化组合,才得到了langchain)
Alice师傅的好宝宝
2025/01/07
2810
Langchain 和 RAG 最佳实践
这是一篇关于LangChain和RAG的快速入门文章,主要参考了由Harrison Chase和Andrew Ng讲授的Langchain chat with your data课程。你可以在rag101仓库中查看完整代码。本文翻译自我的英文博客,最新修订内容可随时参考:LangChain 与 RAG 最佳实践。
timerring
2025/03/05
800
【RAG入门教程05】Langchian框架-Vector Stores
向量存储旨在高效处理大量向量,提供根据特定标准添加、查询和检索向量的功能。它可用于支持语义搜索等应用程序,在这些应用程序中,您可以查找与给定查询在语义上相似的文本段落或文档。
致Great
2024/06/10
5890
【RAG入门教程05】Langchian框架-Vector Stores
在 LangChain 尝试了 N 种可能后,我发现了分块的奥义!
分块(Chunking)是构建检索增强型生成(RAG)(https://zilliz.com.cn/use-cases/llm-retrieval-augmented-generation)应用程序中最具挑战性的问题。分块是指切分文本的过程,虽然听起来非常简单,但要处理的细节问题不少。根据文本内容的类型,需要采用不同的分块策略。
Zilliz RDS
2023/11/09
1K0
在 LangChain 尝试了 N 种可能后,我发现了分块的奥义!
LangChain大模型应用开发
LangChain作为一个新兴的框架,旨在简化大模型应用的开发过程。它提供了一套工具和接口,帮助开发者将大模型无缝集成到各种应用场景中。通过LangChain,开发者可以更专注于业务逻辑的实现,而不必过多关注底层模型的复杂性。
@小森
2024/12/04
2151
LangChain大模型应用开发
用 LangChain 构建文档问答助手
随着大语言模型(LLM)的广泛应用,越来越多企业和个人希望利用它来实现“基于文档的智能问答”功能。例如:
IT蜗壳-Tango
2025/04/09
1980
RAG:如何与您的数据对话
在我之前的文章中,我们讨论了如何使用 ChatGPT 进行主题建模。我们的任务是分析客户对不同连锁酒店的评论,并确定每家酒店提到的主要主题。
大数据杂货铺
2024/01/16
8720
RAG:如何与您的数据对话
向量数据库Chroma极简教程
向量数据库其实最早在传统的人工智能和机器学习场景中就有所应用。在大模型兴起后,由于目前大模型的token数限制,很多开发者倾向于将数据量庞大的知识、新闻、文献、语料等先通过嵌入(embedding)算法转变为向量数据,然后存储在Chroma等向量数据库中。当用户在大模型输入问题后,将问题本身也embedding,转化为向量,在向量数据库中查找与之最匹配的相关知识,组成大模型的上下文,将其输入给大模型,最终返回大模型处理后的文本给用户,这种方式不仅降低大模型的计算量,提高响应速度,也降低成本,并避免了大模型的tokens限制,是一种简单高效的处理手段。此外,向量数据库还在大模型记忆存储等领域发挥其不可替代的作用。
Rude3Knife的公众号
2023/11/08
2.2K0
向量数据库Chroma极简教程
大模型开发实战:(二)使用 LangChain 构建本地知识库应用
检索增强生成(Retrieval-Augmented Generation,RAG)是一种优化大型语言模型输出的方法,允许模型在生成回答前,从外部知识库中检索相关信息,而非仅依赖模型内部训练的知识。通过引用外部知识库的信息来生成更准确、实时且可靠的内容,并解决知识过时和幻觉的问题。下面将介绍使用 LangChain 和 Ollama 实现一个本地知识库应用。
张高兴
2025/05/21
7290
大模型开发实战:(二)使用 LangChain 构建本地知识库应用
告别人工提示,用DSPy编程
DSPy 框架旨在通过优先考虑声明式、系统化编程而不是手动编写提示来解决一致性和可靠性问题。
云云众生s
2024/07/12
3460
RAG实操教程langchain+Milvus向量数据库创建你的本地知识库
RAG 是retrieval-augmented-generation的缩写,翻译为中文的意思就检索增强,以基于最新,最准确的数据建立LLM 的语料知识库。
用户1418987
2024/09/06
1.8K0
RAG实操教程langchain+Milvus向量数据库创建你的本地知识库
Langchain中改进RAG能力的3种常用的扩展查询方法
有多种方法可以提高检索增强生成(RAG)的能力,其中一种方法称为查询扩展。我们这里主要介绍在Langchain中常用的3种方法
deephub
2024/01/31
9890
Langchain中改进RAG能力的3种常用的扩展查询方法
【LangChain系列】第八节:文档问答
在机器学习和自然语言处理的快速发展中,大型语言模型是处理各种任务的非常有用的工具。其中一项引起人们极大兴趣的任务是对文档进行问答,其中 LLM 用于根据 PDF、网页或公司内部文件等文档的内容提供准确的回答。这篇博文将深入探讨使用 LLM 对文档进行问答的迷人世界,探索嵌入和向量存储等关键概念。我们还将逐步完成整个过程,并向您介绍LangChain库,该库简化了这些技术的实现。
Freedom123
2024/05/24
2930
使用 LangChain 和 Elasticsearch 实现隐私优先的人工智能搜索
过去几个周末,我一直沉浸在“即时工程”的迷人世界中,学习Elasticsearch® 等向量数据库如何通过充当长期记忆和语义知识存储来增强 ChatGPT 等大型语言模型 (LLM)。然而,困扰我和许多其他经验丰富的数据架构师的一件事是,许多教程和演示完全依赖于向大型网络公司和基于云的人工智能公司发送您的私人数据。
点火三周
2023/07/25
2.8K0
使用 LangChain 和 Elasticsearch 实现隐私优先的人工智能搜索
推荐阅读
相关推荐
【LangChain系列】第一节:文档加载
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验