Pinecone Hybrid Search

Pineconeopen in new window是一个具有广泛功能的向量数据库。

本文介绍了如何使用Pinecone和Hybrid Search的检索器。

此检索器的逻辑来自于此文档open in new window

要使用Pinecone,您必须拥有一个API密钥和一个环境。这里是安装说明open in new window

#!pip install pinecone-client pinecone-text
import os
import getpass

os.environ['PINECONE_API_KEY'] = getpass.getpass('Pinecone API Key:')
from langchain.retrievers import PineconeHybridSearchRetriever
os.environ['PINECONE_ENVIRONMENT'] = getpass.getpass('Pinecone Environment:')

我们想要使用OpenAIEmbeddings,所以我们需要获取OpenAI的API密钥。

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

设置 Pinecone

您只需要执行这部分操作一次。

注意:确保不对保存在元数据中的文档文本的"context"字段进行索引。目前,您需要明确指定要索引的字段。有关更多信息,请查阅Pinecone的文档open in new window

import os
import pinecone

api_key = os.getenv("PINECONE_API_KEY") or "PINECONE_API_KEY"
# 在Pinecone控制台中找到与API密钥相邻的环境
env = os.getenv("PINECONE_ENVIRONMENT") or "PINECONE_ENVIRONMENT"

index_name = "langchain-pinecone-hybrid-search"

pinecone.init(api_key=api_key, enviroment=env)
pinecone.whoami()
WhoAmIResponse(username='load', user_label='label', projectname='load-test')
# create the index
pinecone.create_index(
   name=index_name,
   dimension=1536,  # dimensionality of dense model
   metric="dotproduct",  # sparse values supported only for dotproduct
   pod_type="s1",
   metadata_config={"indexed": []}  # see explanation above
)

现在创建了索引,我们可以使用它。

index = pinecone.Index(index_name)

获取嵌入向量和稀疏编码器

嵌入向量用于表示密集向量,分词器用于表示稀疏向量。

from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()

要将文本编码为稀疏值,可以选择SPLADE或BM25。对于领域外的任务,建议使用BM25。

有关稀疏编码器的更多信息,请查看pinecone-text库的文档open in new window

from pinecone_text.sparse import BM25Encoder
# 或者 from pinecone_text.sparse import SpladeEncoder,如果您希望使用SPLADE

# 使用默认的tf-idf值
bm25_encoder = BM25Encoder().default()

上面的代码使用了默认的tf-idf值。强烈建议根据自己的语料库进行tf-idf值的拟合。您可以按照以下步骤进行操作:

corpus = ["foo", "bar", "world", "hello"]

# 在您的语料库上拟合tf-idf值
bm25_encoder.fit(corpus)

# 将值存储到json文件中
bm25_encoder.dump("bm25_values.json")

# 加载到您的BM25Encoder对象中
bm25_encoder = BM25Encoder().load("bm25_values.json")

加载检索器

现在我们可以构建检索器了!

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.get_relevant_documents("foo")
result[0]
Document(page_content='foo', metadata={})
Last Updated:
Contributors: 刘强