Skip to main content

Per-User Retrieval

在构建检索应用程序时,通常需要考虑多个用户。这意味着您可能不仅为一个用户存储数据,还为许多不同的用户存储数据,而它们不应该能够看到彼此的数据。这意味着您需要能够配置检索链以仅检索特定信息。这通常涉及两个步骤。

步骤 1:确保您正在使用的检索器支持多个用户

目前,在 LangChain 中还没有统一的标志或过滤器。相反,每个向量存储器和检索器可能有自己的标志或过滤器,并且可能被称为不同的名称空间、多租户等。对于向量存储器,这通常作为一个关键字参数公开,在进行相似性搜索时传递。通过阅读文档或源代码,找出您正在使用的检索器是否支持多用户,以及如果支持,如何使用它。

注意:为不支持(或未记录)多用户的检索器添加文档和/或支持是为LangChain做出贡献的一个绝佳方式。

第二步:将该参数添加为链的可配置字段。

这将允许您在运行时轻松调用链并配置任何相关标志。有关配置的更多信息,请参阅此文档。

步骤3:使用该可配置字段调用链。

现在,在运行时,您可以使用可配置字段调用此链。

Code Example

让我们看一个具体的例子,看看这在代码中是什么样子。我们将在这个例子中使用Pinecone。

配置Pinecone,请设置以下环境变量:

  • 松果API密钥: 您的松果API密钥
from langchain_openai import OpenAIEmbeddings
from langchain_pinecone import PineconeVectorStore
embeddings = OpenAIEmbeddings()
vectorstore = PineconeVectorStore(index_name="test-example", embedding=embeddings)

vectorstore.add_texts(["i worked at kensho"], namespace="harrison")
vectorstore.add_texts(["i worked at facebook"], namespace="ankush")
['ce15571e-4e2f-44c9-98df-7e83f6f63095']

“pinecone”参数用于命名空间,可用于分离文档。

# This will only get documents for Ankush
vectorstore.as_retriever(search_kwargs={"namespace": "ankush"}).get_relevant_documents(
"where did i work?"
)
[Document(page_content='i worked at facebook')]
# This will only get documents for Harrison
vectorstore.as_retriever(
search_kwargs={"namespace": "harrison"}
).get_relevant_documents("where did i work?")
[Document(page_content='i worked at kensho')]

我们现在可以创建用于问题回答的链条。

from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import (
ConfigurableField,
RunnableBinding,
RunnableLambda,
RunnablePassthrough,
)
from langchain_openai import ChatOpenAI, OpenAIEmbeddings

这是基本的问答链设置。

template = """Answer the question based only on the following context:
{context}
Question: {question}
"""
prompt = ChatPromptTemplate.from_template(template)

model = ChatOpenAI()

retriever = vectorstore.as_retriever()

我们将检索器标记为具有可配置字段。所有的矢量存储检索器都有 `search_kwargs` 作为一个字段。这只是一个字典,包含了矢量存储特定的字段。

configurable_retriever = retriever.configurable_fields(
search_kwargs=ConfigurableField(
id="search_kwargs",
name="Search Kwargs",
description="The search kwargs to use",
)
)

我们现在可以使用我们可配置的检索器来创建这个链条。

chain = (
{"context": configurable_retriever, "question": RunnablePassthrough()}
| prompt
| model
| StrOutputParser()
)

我们现在可以使用可配置选项调用该链。 search_kwargs 是可配置字段的id。该值是用于Pinecone的搜索参数。

chain.invoke(
"where did the user work?",
config={"configurable": {"search_kwargs": {"namespace": "harrison"}}},
)
'The user worked at Kensho.'
chain.invoke(
"where did the user work?",
config={"configurable": {"search_kwargs": {"namespace": "ankush"}}},
)
'The user worked at Facebook.'

请参考特定页面,如 Milvus,了解更多关于多用户的 vectorstore 实现。


Help us out by providing feedback on this documentation page: