Pinecone 混合搜索
Pinecone 是一个功能广泛的向量数据库。
这个笔记本介绍了如何使用一个幕后使用Pinecone和混合搜索的检索器。
该检索器的逻辑来自此文档
要使用Pinecone,您必须拥有API密钥和环境。 以下是从安装说明。
%pip install --upgrade --quiet pinecone pinecone-text pinecone-notebooks
# Connect to Pinecone and get an API key.
from pinecone_notebooks.colab import Authenticate
Authenticate()
import os
api_key = os.environ["PINECONE_API_KEY"]
from langchain_community.retrievers import (
PineconeHybridSearchRetriever,
)
我们想要使用OpenAIEmbeddings,所以我们必须获取OpenAI API密钥。
import getpass
if "OPENAI_API_KEY" not in os.environ:
os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")
设置 Pinecone
您只需执行此步骤一次。
import os
from pinecone import Pinecone, ServerlessSpec
index_name = "langchain-pinecone-hybrid-search"
# initialize Pinecone client
pc = Pinecone(api_key=api_key)
# create the index
if index_name not in pc.list_indexes().names():
pc.create_index(
name=index_name,
dimension=1536, # dimensionality of dense model
metric="dotproduct", # sparse values supported only for dotproduct
spec=ServerlessSpec(cloud="aws", region="us-east-1"),
)
WhoAmIResponse(username='load', user_label='label', projectname='load-test')
现在索引已经创建好了,我们可以使用它。
index = pc.Index(index_name)
获取嵌入和稀疏编码
嵌入用于密集向量,分词器用于稀疏向量
from langchain_openai import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
API 参考:OpenAI 嵌入
要将文本编码为稀疏值,您可以选择使用SPLADE或BM25。对于跨域任务,我们推荐使用BM25。
对于稀疏编码器的更多信息,您可以查阅pinecone-text库的文档。
from pinecone_text.sparse import BM25Encoder
# or from pinecone_text.sparse import SpladeEncoder if you wish to work with SPLADE
# use default tf-idf values
bm25_encoder = BM25Encoder().default()
上述代码使用了默认的tfids值。强烈建议您根据自己的语料库拟合tf-idf值。您可以按照以下方式进行操作:
corpus = ["foo", "bar", "world", "hello"]
# fit tf-idf values on your corpus
bm25_encoder.fit(corpus)
# store the values to a json file
bm25_encoder.dump("bm25_values.json")
# load to your BM25Encoder object
bm25_encoder = BM25Encoder().load("bm25_values.json")
Load Retriever
现在我们可以构建检索器了!
retriever = PineconeHybridSearchRetriever(
embeddings=embeddings, sparse_encoder=bm25_encoder, index=index
)
添加文本(如果需要)
我们也可以选择性地向检索器添加文本(如果它们尚未包含在其中)
retriever.add_texts(["foo", "bar", "world", "hello"])
100%|██████████| 1/1 [00:02<00:00, 2.27s/it]
使用检索器
我们现在已经可以使用检索器了!
result = retriever.invoke("foo")
result[0]
Document(page_content='foo', metadata={})