Skip to main content

动态选择多个检索器

本笔记本演示了如何使用RouterChain范例创建一个动态选择使用哪个检索系统的链。具体来说,我们展示了如何使用MultiRetrievalQAChain创建一个问答链,该链根据给定的问题动态选择最相关的检索QA链,然后使用它来回答问题。

from langchain.chains.router import MultiRetrievalQAChain  
from langchain.llms import OpenAI

from langchain.embeddings import OpenAIEmbeddings
from langchain.document_loaders import TextLoader
from langchain.vectorstores import FAISS

sou_docs = TextLoader('../../state_of_the_union.txt').load_and_split()
sou_retriever = FAISS.from_documents(sou_docs, OpenAIEmbeddings()).as_retriever()

pg_docs = TextLoader('../../paul_graham_essay.txt').load_and_split()
pg_retriever = FAISS.from_documents(pg_docs, OpenAIEmbeddings()).as_retriever()

personal_texts = [
"I love apple pie",
"My favorite color is fuchsia",
"My dream is to become a professional dancer",
"I broke my arm when I was 12",
"My parents are from Peru",
]
personal_retriever = FAISS.from_texts(personal_texts, OpenAIEmbeddings()).as_retriever()

retriever_infos = [
{
"name": "state of the union",
"description": "用于回答有关2023年国情咨文的问题",
"retriever": sou_retriever
},
{
"name": "pg essay",
"description": "用于回答有关Paul Graham职业生涯的问题",
"retriever": pg_retriever
},
{
"name": "personal",
"description": "用于回答有关我的问题",
"retriever": personal_retriever
}
]

chain = MultiRetrievalQAChain.from_retrievers(OpenAI(), retriever_infos, verbose=True)

print(chain.run("What did the president say about the economy?"))

print(chain.run("What is something Paul Graham regrets about his work?"))

print(chain.run("What is my background?"))

print(chain.run("What year was the Internet created in?"))

输出结果如下:

> 进入新的MultiRetrievalQAChain链...
state of the union: {'query': 'What did the president say about the economy in the 2023 State of the Union address?'}
> 链结束。
总统表示经济比一年前更强劲,美国救援计划帮助创造了创纪录的就业增长,并为数百万美国人提供了经济救济。他还提出了一项打击通货膨胀、降低家庭成本的计划,包括降低处方药和能源成本,为能源效率提供投资和税收抵免,以及增加儿童保育和学前教育的机会。

> 进入新的MultiRetrievalQAChain链...
pg essay: {'query': 'What is something Paul Graham regrets about his work?'}
> 链结束。
Paul Graham后悔在出售公司后没有休假,而是立即开始绘画。

> 进入新的MultiRetrievalQAChain链...
personal: {'query': 'What is my background?'}
> 链结束。
你的背景是秘鲁的。

> 进入新的MultiRetrievalQAChain链...
None: {'query': 'What year was the Internet created in?'}
> 链结束。
互联网是通过一个名为ARPANET的项目于1969年创建的,该项目由美国国防部资助。然而,经常与互联网混淆的万维网是由英国计算机科学家蒂姆·伯纳斯-李于1989年创建的。