如何并行调用可运行对象
本指南假设您熟悉以下概念:
The RunnableParallel 原语本质上是一个字典,其值为可运行对象(或可转换为可运行对象的内容,如函数)。它并行执行所有值,并将每个值用 RunnableParallel 的整体输入进行调用。最终的返回值是一个字典,其中包含每个值的结果及其对应的键。
使用 RunnableParallels
RunnableParallels 对于并行化操作很有用,但也可用于将一个 Runnable 的输出转换为与序列中下一个 Runnable 输入格式相匹配的格式。您可以使用它们来拆分或分支链,以便多个组件可以并行处理输入。随后,其他组件可以合并结果以合成最终响应。这种类型的链会创建一个如下所示的计算图:
Input
/ \
/ \
Branch1 Branch2
\ /
\ /
Combine
下面,提示的输入预期为一个带有键 "context" 和 "question" 的映射。用户输入仅是问题。因此,我们需要使用我们的检索器获取上下文,并将用户输入作为 "question" 键下的值传递。
from langchain_community.vectorstores import FAISS
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
vectorstore = FAISS.from_texts(
["harrison worked at kensho"], embedding=OpenAIEmbeddings()
)
retriever = vectorstore.as_retriever()
template = """Answer the question based only on the following context:
{context}
Question: {question}
"""
# The prompt expects input with keys for "context" and "question"
prompt = ChatPromptTemplate.from_template(template)
model = ChatOpenAI()
retrieval_chain = (
{"context": retriever, "question": RunnablePassthrough()}
| prompt
| model
| StrOutputParser()
)
retrieval_chain.invoke("where did harrison work?")
'Harrison worked at Kensho.'
请注意,当将 RunnableParallel 与其他 Runnable 组合时,我们甚至不需要将字典包装在 RunnableParallel 类中——类型转换会自动处理。在链的上下文中,以下两者是等价的:
{"context": retriever, "question": RunnablePassthrough()}
RunnableParallel({"context": retriever, "question": RunnablePassthrough()})
RunnableParallel(context=retriever, question=RunnablePassthrough())
请参阅有关强制转换的章节以获取更多信息。
使用 itemgetter 作为简写
请注意,您可以使用 Python 的 itemgetter 作为简写,在与 RunnableParallel 结合时从映射中提取数据。您可以在 Python 文档 中找到有关 itemgetter 的更多信息。
在下面的示例中,我们使用 itemgetter 从映射中提取特定的键:
from operator import itemgetter
from langchain_community.vectorstores import FAISS
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
vectorstore = FAISS.from_texts(
["harrison worked at kensho"], embedding=OpenAIEmbeddings()
)
retriever = vectorstore.as_retriever()
template = """Answer the question based only on the following context:
{context}
Question: {question}
Answer in the following language: {language}
"""
prompt = ChatPromptTemplate.from_template(template)
chain = (
{
"context": itemgetter("question") | retriever,
"question": itemgetter("question"),
"language": itemgetter("language"),
}
| prompt
| model
| StrOutputParser()
)
chain.invoke({"question": "where did harrison work", "language": "italian"})
'Harrison ha lavorato a Kensho.'
并行化步骤
RunnableParallels 使并行执行多个 Runnable 并返回这些 Runnable 的输出(以映射形式)变得简单。
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableParallel
from langchain_openai import ChatOpenAI
model = ChatOpenAI()
joke_chain = ChatPromptTemplate.from_template("tell me a joke about {topic}") | model
poem_chain = (
ChatPromptTemplate.from_template("write a 2-line poem about {topic}") | model
)
map_chain = RunnableParallel(joke=joke_chain, poem=poem_chain)
map_chain.invoke({"topic": "bear"})
{'joke': AIMessage(content="Why don't bears like fast food? Because they can't catch it!", response_metadata={'token_usage': {'completion_tokens': 15, 'prompt_tokens': 13, 'total_tokens': 28}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': 'fp_d9767fc5b9', 'finish_reason': 'stop', 'logprobs': None}, id='run-fe024170-c251-4b7a-bfd4-64a3737c67f2-0'),
'poem': AIMessage(content='In the quiet of the forest, the bear roams free\nMajestic and wild, a sight to see.', response_metadata={'token_usage': {'completion_tokens': 24, 'prompt_tokens': 15, 'total_tokens': 39}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': 'fp_c2295e73ad', 'finish_reason': 'stop', 'logprobs': None}, id='run-2707913e-a743-4101-b6ec-840df4568a76-0')}
并行处理
RunnableParallel 对于并行运行独立进程也很有用,因为映射中的每个 Runnable 都会并行执行。例如,我们可以看到我们之前的 joke_chain、poem_chain 和 map_chain 的运行时间大致相同,尽管 map_chain 执行了另外两个。
%%timeit
joke_chain.invoke({"topic": "bear"})
610 ms ± 64 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%%timeit
poem_chain.invoke({"topic": "bear"})
599 ms ± 73.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%%timeit
map_chain.invoke({"topic": "bear"})
643 ms ± 77.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
下一步
您现在了解了一些使用 RunnableParallel 来格式化和并行化链步骤的方法。
要了解更多信息,请参阅本节中关于可运行对象的其它操操作指南。