Skip to main content
Open In Colab在 GitHub 上打开

如何将参数从一个步骤传递到下一个步骤

在编写包含多个步骤的链时,有时您希望将前一步中的数据保持不变,以用作后续步骤的输入。这RunnablePassthroughclass 允许你这样做,并且通常与 RunnableParallel 结合使用,以将数据传递到你构建的链中的后续步骤。

请参阅以下示例:

%pip install -qU langchain langchain-openai

import os
from getpass import getpass

if "OPENAI_API_KEY" not in os.environ:
os.environ["OPENAI_API_KEY"] = getpass()
from langchain_core.runnables import RunnableParallel, RunnablePassthrough

runnable = RunnableParallel(
passed=RunnablePassthrough(),
modified=lambda x: x["num"] + 1,
)

runnable.invoke({"num": 1})
{'passed': {'num': 1}, 'modified': 2}

如上所示,passedkey 是使用RunnablePassthrough()就这样,它就这样过去了{'num': 1}.

我们还在 map 中设置了第二个键modified.这使用 lambda 设置一个将 num 加 1 的值,从而得到modifiedkey 的值为2.

检索示例

在下面的示例中,我们看到了一个更真实的用例,其中我们使用RunnablePassthrough以及RunnableParallel以正确格式化提示符的输入:

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}
"""
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.'

这里 prompt 的输入应该是键为 “context” 和 “question” 的 map。用户输入只是一个问题。因此,我们需要使用我们的检索器获取上下文,并在 “question” 键下传递用户输入。这RunnablePassthrough允许我们将用户的问题传递给 prompt 和 model。

后续步骤

现在,您已经了解了如何通过链传递数据,以帮助格式化流经链的数据。

要了解更多信息,请参阅本节中有关 runnables 的其他操作指南。