核心模块(Modules)
数据连接(DataConnection)
向量存储(VectorStores)
Index

向量存储

注意:关于与第三方向量存储的内置集成,请前往 集成 (opens in a new tab)。

存储和搜索非结构化数据最常见的方式之一,是对其进行嵌入并存储生成的嵌入向量,然后在查询时嵌入非结构化查询,并检索与嵌入查询“最相似”的嵌入向量。向量存储负责为你存储嵌入数据并执行向量搜索。

示意图,说明向量存储的过程:1. 加载源数据,2. 查询向量存储,3. 检索“最相似”的结果。

入门

本次演练展示与向量存储相关的基本功能。使用向量存储的一个关键部分是创建要放入其中的向量,这通常通过嵌入来创建。因此,建议你在深入本节之前先熟悉 文本嵌入模型 接口。

import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem';

有许多很棒的向量存储选项,这里有几个免费、开源、完全在你的本地机器上运行的选项。查看所有集成可以了解许多很棒的托管方案。

本次演练使用 chroma 向量数据库,它作为库在你的本地机器上运行。

pip install langchain-chroma

我们想使用 OpenAIEmbeddings,所以必须获取 OpenAI API 密钥。

import os
import getpass
 
os.environ['OPENAI_API_KEY'] = getpass.getpass('OpenAI API Key:')
from langchain_community.document_loaders import TextLoader
from langchain_openai import OpenAIEmbeddings
from langchain_text_splitters import CharacterTextSplitter
from langchain_chroma import Chroma
 
# 加载文档,把它分割成块,嵌入每个块并加载到向量存储中。
raw_documents = TextLoader('../../../state_of_the_union.txt').load()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
documents = text_splitter.split_documents(raw_documents)
db = Chroma.from_documents(documents, OpenAIEmbeddings())

本次演练使用 FAISS 向量数据库,它利用了 Facebook AI 相似性搜索(FAISS)库。

pip install faiss-cpu

我们想使用 OpenAIEmbeddings,所以必须获取 OpenAI API 密钥。

import os
import getpass
 
os.environ['OPENAI_API_KEY'] = getpass.getpass('OpenAI API Key:')
from langchain_community.document_loaders import TextLoader
from langchain_openai import OpenAIEmbeddings
from langchain_text_splitters import CharacterTextSplitter
from langchain_community.vectorstores import FAISS
 
# 加载文档,把它分割成块,嵌入每个块并加载到向量存储中。
raw_documents = TextLoader('../../../state_of_the_union.txt').load()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
documents = text_splitter.split_documents(raw_documents)
db = FAISS.from_documents(documents, OpenAIEmbeddings())

本笔记本展示如何使用基于 Lance 数据格式的 LanceDB 向量数据库的相关功能。

pip install lancedb

我们想使用 OpenAIEmbeddings,所以必须获取 OpenAI API 密钥。

import os
import getpass
 
os.environ['OPENAI_API_KEY'] = getpass.getpass('OpenAI API Key:')
from langchain_community.document_loaders import TextLoader
from langchain_openai import OpenAIEmbeddings
from langchain_text_splitters import CharacterTextSplitter
from langchain_community.vectorstores import LanceDB
 
import lancedb
 
db = lancedb.connect("/tmp/lancedb")
table = db.create_table(
    "my_table",
    data=[
        {
            "vector": embeddings.embed_query("Hello World"),
            "text": "Hello World",
            "id": "1",
        }
    ],
    mode="overwrite",
)
 
# 加载文档,把它分割成块,嵌入每个块并加载到向量存储中。
raw_documents = TextLoader('../../../state_of_the_union.txt').load()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
documents = text_splitter.split_documents(raw_documents)
db = LanceDB.from_documents(documents, OpenAIEmbeddings())

相似性搜索

query = "What did the president say about Ketanji Brown Jackson"
docs = db.similarity_search(query)
print(docs[0].page_content)
    Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections.

    Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service.

    One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court.

    And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.

按向量进行相似性搜索

也可以使用 similarity_search_by_vector 搜索与给定嵌入向量相似的文档,它接受一个嵌入向量作为参数而不是字符串。

embedding_vector = OpenAIEmbeddings().embed_query(query)
docs = db.similarity_search_by_vector(embedding_vector)
print(docs[0].page_content)

查询相同,因此结果也相同。

    Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections.

    Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service.

    One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court.

    And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.

异步操作

向量存储通常作为需要一些 IO 操作的独立服务运行,因此它们可能被异步调用。这样可以带来性能收益,因为你不会浪费时间等待外部服务的响应。如果你使用异步框架(例如 FastAPI (opens in a new tab)),这也可能很重要。

LangChain 支持向量存储上的异步操作。所有方法都可以用它们的异步对应方法调用,前缀为 a,即 async。

Qdrant 是一个支持所有异步操作的向量存储,因此本次演练将使用它。

pip install qdrant-client
from langchain_community.vectorstores import Qdrant

异步创建向量存储

db = await Qdrant.afrom_documents(documents, embeddings, "http://localhost:6333")

相似性搜索

query = "What did the president say about Ketanji Brown Jackson"
docs = await db.asimilarity_search(query)
print(docs[0].page_content)
    Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections.

    Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service.

    One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court.

    And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.

按向量进行相似性搜索

embedding_vector = embeddings.embed_query(query)
docs = await db.asimilarity_search_by_vector(embedding_vector)

最大边际相关性搜索(MMR)

最大边际相关性同时针对与查询的相似性 以及 所选文档之间的多样性进行优化。它在异步 API 中同样受支持。

query = "What did the president say about Ketanji Brown Jackson"
found_docs = await qdrant.amax_marginal_relevance_search(query, k=2, fetch_k=10)
for i, doc in enumerate(found_docs):
    print(f"{i + 1}.", doc.page_content, "\n")
1. Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections.

Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service.

One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court.

And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.

2. We can’t change how divided we’ve been. But we can change how we move forward—on COVID-19 and other issues we must face together.

I recently visited the New York City Police Department days after the funerals of Officer Wilbert Mora and his partner, Officer Jason Rivera.

They were responding to a 9-1-1 call when a man shot and killed them with a stolen gun.

Officer Mora was 27 years old.

Officer Rivera was 22.

Both Dominican Americans who’d grown up on the same streets they later chose to patrol as police officers.

I spoke with their families and told them that we are forever in debt for their sacrifice, and we will carry on their mission to restore the trust and safety every community deserves.

I’ve worked on these issues a long time.

I know what works: Investing in crime prevention and community police officers who’ll walk the beat, who’ll know the neighborhood, and who can restore trust and safety.