以编程方式使用文档

>Qdrant (发音: quadrant) 是一个向量相似度搜索引擎。它提供了一个生产就绪的服务,具有方便的 API,用于存储、搜索和管理向量,并支持额外的负载和扩展过滤功能。这使得它适用于各种神经网络或基于语义的匹配、分面搜索和其他应用。

本文档演示了如何使用 Qdrant 与 LangChain 进行稠密(即基于嵌入的)、稀疏(即文本搜索)和混合检索。 QdrantVectorStore 类通过 Qdrant 的新 Query API支持多种检索模式。它需要您运行 Qdrant v1.10.0 或更高版本。

安装

运行 Qdrant有多种模式,根据所选模式会有一些细微差异。选项包括:

  • - 本地模式,无需服务器
  • - Docker 部署
  • - Qdrant Cloud

请参阅 Qdrant 安装说明.

pip install -qU langchain-qdrant

凭证

运行此笔记本中的代码不需要任何凭证。

如果您想获得最佳的模型调用自动追踪功能,您还可以设置您的 LangSmith API 密钥,取消下面的注释即可:

os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
os.environ["LANGSMITH_TRACING"] = "true"

初始化

本地模式

Python 客户端提供在本地模式下运行代码的选项,无需运行 Qdrant 服务器。这非常适合测试和调试,或仅存储少量向量。嵌入可以完全保存在内存中,也可以持久化到磁盘上。

In-memory

For some testing scenarios and quick experiments, you may prefer to keep all the data in-memory only, so it gets removed when the client is destroyed - usually at the end of your script/notebook.

# | output: false
# | echo: false
from langchain_openai import OpenAIEmbeddings

embeddings = OpenAIEmbeddings(model="text-embedding-3-large")
from langchain_qdrant import QdrantVectorStore
from qdrant_client import QdrantClient
from qdrant_client.http.models import Distance, VectorParams

client = QdrantClient(":memory:")

client.create_collection(
    collection_name="demo_collection",
    vectors_config=VectorParams(size=3072, distance=Distance.COSINE),
)

vector_store = QdrantVectorStore(
    client=client,
    collection_name="demo_collection",
    embedding=embeddings,
)

磁盘存储

本地模式,不使用 Qdrant 服务器,也可以将向量存储在磁盘上,以便在运行之间持久化。

client = QdrantClient(path="/tmp/langchain_qdrant")

client.create_collection(
    collection_name="demo_collection",
    vectors_config=VectorParams(size=3072, distance=Distance.COSINE),
)

vector_store = QdrantVectorStore(
    client=client,
    collection_name="demo_collection",
    embedding=embeddings,
)

本地服务器部署

无论您选择使用 Docker 容器 在本地启动 Qdrant,还是使用 官方 Helm chart选择 Kubernetes 部署,连接到此实例的方式都是相同的。您需要提供一个指向服务的 URL。

url = "<---qdrant url here --->"
docs = []  # put docs here
qdrant = QdrantVectorStore.from_documents(
    docs,
    embeddings,
    url=url,
    prefer_grpc=True,
    collection_name="my_documents",
)

Qdrant Cloud

如果您不想自己管理基础设施,可以选择在 Qdrant Cloud上设置一个完全托管的 Qdrant 集群。其中包含一个永久免费的 1GB 集群供试用。使用托管版 Qdrant 的主要区别在于,您需要提供 API 密钥以保护您的部署不被公开访问。该值也可以设置在 QDRANT_API_KEY 环境变量中。

url = "<---qdrant cloud cluster url here --->"
api_key = "<---api key here--->"
qdrant = QdrantVectorStore.from_documents(
    docs,
    embeddings,
    url=url,
    prefer_grpc=True,
    api_key=api_key,
    collection_name="my_documents",
)

使用现有集合

要获取 langchain_qdrant.Qdrant 的实例而不加载任何新文档或文本,您可以使用 Qdrant.from_existing_collection() method.

qdrant = QdrantVectorStore.from_existing_collection(
    embedding=embeddings,
    collection_name="my_documents",
    url="http://localhost:6333",
)

管理向量存储

创建向量存储后,我们可以添加和删除不同的项目来与之交互。

向向量存储添加项目

我们可以使用以下方式向向量存储中添加项目 add_documents function.

from uuid import uuid4

from langchain_core.documents import Document

document_1 = Document(
    page_content="I had chocolate chip pancakes and scrambled eggs for breakfast this morning.",
    metadata={"source": "tweet"},
)

document_2 = Document(
    page_content="The weather forecast for tomorrow is cloudy and overcast, with a high of 62 degrees Fahrenheit.",
    metadata={"source": "news"},
)

document_3 = Document(
    page_content="Building an exciting new project with LangChain - come check it out!",
    metadata={"source": "tweet"},
)

document_4 = Document(
    page_content="Robbers broke into the city bank and stole $1 million in cash.",
    metadata={"source": "news"},
)

document_5 = Document(
    page_content="Wow! That was an amazing movie. I can't wait to see it again.",
    metadata={"source": "tweet"},
)

document_6 = Document(
    page_content="Is the new iPhone worth the price? Read this review to find out.",
    metadata={"source": "website"},
)

document_7 = Document(
    page_content="The top 10 soccer players in the world right now.",
    metadata={"source": "website"},
)

document_8 = Document(
    page_content="LangGraph is the best framework for building stateful, agentic applications!",
    metadata={"source": "tweet"},
)

document_9 = Document(
    page_content="The stock market is down 500 points today due to fears of a recession.",
    metadata={"source": "news"},
)

document_10 = Document(
    page_content="I have a bad feeling I am going to get deleted :(",
    metadata={"source": "tweet"},
)

documents = [
    document_1,
    document_2,
    document_3,
    document_4,
    document_5,
    document_6,
    document_7,
    document_8,
    document_9,
    document_10,
]
uuids = [str(uuid4()) for _ in range(len(documents))]
vector_store.add_documents(documents=documents, ids=uuids)

从向量存储中删除项目

vector_store.delete(ids=[uuids[-1]])
True

查询向量存储

一旦创建了向量存储并添加了相关文档,您很可能希望在运行链或代理时对其进行查询。

直接查询

使用 Qdrant 向量存储的最简单场景是执行相似性搜索。在底层,我们的查询将被编码为向量嵌入,用于在 Qdrant 集合中查找相似的文档。

results = vector_store.similarity_search(
    "LangChain provides abstractions to make working with LLMs easy", k=2
)
for res in results:
    print(f"* {res.page_content} [{res.metadata}]")
* Building an exciting new project with LangChain - come check it out! [{'source': 'tweet', '_id': 'd3202666-6f2b-4186-ac43-e35389de8166', '_collection_name': 'demo_collection'}]
* LangGraph is the best framework for building stateful, agentic applications! [{'source': 'tweet', '_id': '91ed6c56-fe53-49e2-8199-c3bb3c33c3eb', '_collection_name': 'demo_collection'}]

QdrantVectorStore 支持 3 种相似性搜索模式。可以通过以下方式配置它们 retrieval_mode parameter.

  • - 密集向量搜索(默认)
  • - 稀疏向量搜索
  • - 混合搜索

密集向量搜索

密集向量搜索涉及通过基于向量的嵌入来计算相似度。仅使用密集向量进行搜索:

  • - 该 retrieval_mode 参数应设置为 RetrievalMode.DENSE。这是默认行为。
  • - A 密集嵌入 值应提供给 embedding parameter.
from langchain_qdrant import QdrantVectorStore, RetrievalMode
from qdrant_client import QdrantClient
from qdrant_client.http.models import Distance, VectorParams

# Create a Qdrant client for local storage
client = QdrantClient(path="/tmp/langchain_qdrant")

# Create a collection with dense vectors
client.create_collection(
    collection_name="my_documents",
    vectors_config=VectorParams(size=3072, distance=Distance.COSINE),
)

qdrant = QdrantVectorStore(
    client=client,
    collection_name="my_documents",
    embedding=embeddings,
    retrieval_mode=RetrievalMode.DENSE,
)

qdrant.add_documents(documents=documents, ids=uuids)

query = "How much money did the robbers steal?"
found_docs = qdrant.similarity_search(query)
found_docs

稀疏向量搜索

仅使用稀疏向量进行搜索:

  • - 该 retrieval_mode 参数应设置为 RetrievalMode.SPARSE.
  • - 必须提供使用任何稀疏嵌入提供程序的 SparseEmbeddings 接口实现作为 sparse_embedding parameter.

langchain-qdrant 包提供了一个内置的基于 FastEmbed 的实现。

要使用它,请安装 FastEmbed 包。

pip install -qU fastembed
from langchain_qdrant import FastEmbedSparse, QdrantVectorStore, RetrievalMode
from qdrant_client import QdrantClient, models
from qdrant_client.http.models import Distance, SparseVectorParams, VectorParams

sparse_embeddings = FastEmbedSparse(model_name="Qdrant/bm25")

# Create a Qdrant client for local storage
client = QdrantClient(path="/tmp/langchain_qdrant")

# Create a collection with sparse vectors
client.create_collection(
    collection_name="my_documents",
    vectors_config={"dense": VectorParams(size=3072, distance=Distance.COSINE)},
    sparse_vectors_config={
        "sparse": SparseVectorParams(index=models.SparseIndexParams(on_disk=False))
    },
)

qdrant = QdrantVectorStore(
    client=client,
    collection_name="my_documents",
    sparse_embedding=sparse_embeddings,
    retrieval_mode=RetrievalMode.SPARSE,
    sparse_vector_name="sparse",
)

qdrant.add_documents(documents=documents, ids=uuids)

query = "How much money did the robbers steal?"
found_docs = qdrant.similarity_search(query)
found_docs

混合向量搜索

要使用分数融合执行结合密集和稀疏向量的混合搜索,

  • - 该 retrieval_mode 参数应设置为 RetrievalMode.HYBRID.
  • - A 密集嵌入 值应提供给 embedding parameter.
  • - 必须提供使用任何稀疏嵌入提供程序的 SparseEmbeddings 接口实现作为 sparse_embedding parameter.

请注意,如果您已使用 HYBRID 模式添加了文档,则在搜索时可以切换到任何检索模式,因为集合中同时存在密集和稀疏向量。

from langchain_qdrant import FastEmbedSparse, QdrantVectorStore, RetrievalMode
from qdrant_client import QdrantClient, models
from qdrant_client.http.models import Distance, SparseVectorParams, VectorParams

sparse_embeddings = FastEmbedSparse(model_name="Qdrant/bm25")

# Create a Qdrant client for local storage
client = QdrantClient(path="/tmp/langchain_qdrant")

# Create a collection with both dense and sparse vectors
client.create_collection(
    collection_name="my_documents",
    vectors_config={"dense": VectorParams(size=3072, distance=Distance.COSINE)},
    sparse_vectors_config={
        "sparse": SparseVectorParams(index=models.SparseIndexParams(on_disk=False))
    },
)

qdrant = QdrantVectorStore(
    client=client,
    collection_name="my_documents",
    embedding=embeddings,
    sparse_embedding=sparse_embeddings,
    retrieval_mode=RetrievalMode.HYBRID,
    vector_name="dense",
    sparse_vector_name="sparse",
)

qdrant.add_documents(documents=documents, ids=uuids)

query = "How much money did the robbers steal?"
found_docs = qdrant.similarity_search(query)
found_docs

如果您想执行相似性搜索并获取相应的分数,可以运行:

results = vector_store.similarity_search_with_score(
    query="Will it be hot tomorrow", k=1
)
for doc, score in results:
    print(f"* [SIM={score:3f}] {doc.page_content} [{doc.metadata}]")
* [SIM=0.531834] The weather forecast for tomorrow is cloudy and overcast, with a high of 62 degrees. [{'source': 'news', '_id': '9e6ba50c-794f-4b88-94e5-411f15052a02', '_collection_name': 'demo_collection'}]

有关 QdrantVectorStore可用的所有搜索函数的完整列表,请参阅 API 参考

元数据过滤

Qdrant 具有 强大的过滤系统 ,支持丰富的类型。也可以通过向 similarity_search_with_scoresimilarity_search methods.

from qdrant_client import models

results = vector_store.similarity_search(
    query="Who are the best soccer players in the world?",
    k=1,
    filter=models.Filter(
        should=[
            models.FieldCondition(
                key="page_content",
                match=models.MatchValue(
                    value="The top 10 soccer players in the world right now."
                ),
            ),
        ]
    ),
)
for doc in results:
    print(f"* {doc.page_content} [{doc.metadata}]")
* The top 10 soccer players in the world right now. [{'source': 'website', '_id': 'b0964ab5-5a14-47b4-a983-37fa5c5bd154', '_collection_name': 'demo_collection'}]

Query by turning into retriever

您还可以将向量存储转换为检索器,以便在链中更方便地使用。

retriever = vector_store.as_retriever(search_type="mmr", search_kwargs={"k": 1})
retriever.invoke("Stealing from the bank is a crime")
[Document(metadata={'source': 'news', '_id': '50d8d6ee-69bf-4173-a6a2-b254e9928965', '_collection_name': 'demo_collection'}, page_content='Robbers broke into the city bank and stole $1 million in cash.')]

检索增强生成的使用方法

有关如何使用此向量存储进行检索增强生成 (RAG) 的指南,请参阅以下部分:

自定义 qdrant

您可以在 LangChain 应用中使用现有的 Qdrant 集合。在这种情况下,您可能需要定义如何将 Qdrant 点映射到 LangChain Document.

命名向量

Qdrant 支持 每个点多个向量 通过命名向量。如果您使用外部创建的集合,或希望使用不同名称的向量,可以通过提供其名称来进行配置。

from langchain_qdrant import RetrievalMode

QdrantVectorStore.from_documents(
    docs,
    embedding=embeddings,
    sparse_embedding=sparse_embeddings,
    location=":memory:",
    collection_name="my_documents_2",
    retrieval_mode=RetrievalMode.HYBRID,
    vector_name="custom_vector",
    sparse_vector_name="custom_sparse_vector",
)

元数据

Qdrant 将您的向量嵌入与可选的类 JSON 载荷一起存储。载荷是可选的,但由于 LangChain 假定嵌入是从文档生成的,我们会保留上下文数据,这样您也可以提取原始文本。

默认情况下,您的文档将按以下载荷结构存储:

{
    "page_content": "Lorem ipsum dolor sit amet",
    "metadata": {
        "foo": "bar"
    }
}

不过,您也可以为页面内容和元数据使用不同的键。如果您已有想要重用的集合,这将非常有用。

QdrantVectorStore.from_documents(
    docs,
    embeddings,
    location=":memory:",
    collection_name="my_documents_2",
    content_payload_key="my_page_content_key",
    metadata_payload_key="my_meta",
)

API 参考

有关所有 QdrantVectorStore 功能和配置的详细文档,请前往 API 参考