跳到主要内容
Pinecone 是一个功能强大的向量数据库。
本笔记本介绍了如何使用一个底层使用 Pinecone 和混合搜索的检索器。 该检索器的逻辑取自此文档 要使用 Pinecone,您必须拥有 API 密钥和环境。以下是安装说明
pip install -qU  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()
要将文本编码为稀疏值,您可以选择 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()
上面的代码使用的是默认的 tfidf 值。强烈建议根据您自己的语料库调整 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")

加载检索器

我们现在可以构建检索器了!
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={})

以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.