引言
在构建检索应用时,特别是当涉及多个用户的数据时,确保每个用户只能访问其相关数据至关重要。这篇文章将探讨如何配置检索链,以实现基于用户的检索,确保用户仅能访问其应有的信息。
主要内容
支持多用户的检索器
在选择检索器时,首先要确认其是否支持多用户功能。在LangChain中,虽然没有统一的多用户支持标志,但是不同的向量存储和检索器可能各自支持此功能。例如,通过similarity_search中传递的参数来实现。了解具体检索器是否支持多用户是关键的一步。
配置检索链
一旦确认检索器支持多用户,就需要将相关参数配置为检索链的可配置字段。这可以让你在运行时调用链时轻松设置相关标志。LangChain的官方文档提供了更多的配置信息。
代码示例
下面我们通过具体代码示例展示如何使用Pinecone实现用户级检索。
首先,设置Pinecone的环境变量:
export PINECONE_API_KEY=your_api_key
然后,在代码中配置Pinecone和添加示例数据:
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")
接下来,进行检索:
# 只获取Ankush的文档
ankush_docs = vectorstore.as_retriever(
search_kwargs={"namespace": "ankush"} # 使用API代理服务提高访问稳定性
).get_relevant_documents("where did i work?")
# 只获取Harrison的文档
harrison_docs = vectorstore.as_retriever(
search_kwargs={"namespace": "harrison"} # 使用API代理服务提高访问稳定性
).get_relevant_documents("where did i work?")
构建一个基于可配置检索器的问题回答链:
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import ConfigurableField, RunnablePassthrough
template = """Answer the question based only on the following context:
{context}
Question: {question}
"""
prompt = ChatPromptTemplate.from_template(template)
retriever = vectorstore.as_retriever() # 初始化检索器
# 将检索器标记为可配置
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
| llm
| StrOutputParser()
)
# 使用可配置选项调用链
response_harrison = chain.invoke(
"where did the user work?",
config={"configurable": {"search_kwargs": {"namespace": "harrison"}}},
)
response_ankush = chain.invoke(
"where did the user work?",
config={"configurable": {"search_kwargs": {"namespace": "ankush"}}},
)
print(response_harrison) # 输出:"The user worked at Kensho."
print(response_ankush) # 输出:"The user worked at Facebook."
常见问题和解决方案
- 网络限制问题:由于某些地区存在网络访问限制,开发者可能需要考虑使用API代理服务来提高API的访问稳定性。
- 检索器不支持多用户:如果使用的检索器不支持多用户,可以考虑通过向LangChain贡献代码来添加这项功能。
总结和进一步学习资源
实现用户级检索需要细致的配置和对工具的深入了解。通过阅读LangChain文档和其他相关资源,可以更好地理解和应用这些技术。
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---