Skip to main content

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

当组合包含多个步骤的链时,有时您会希望将先前步骤中的数据未经更改地传递,以作为后续步骤的输入。RunnablePassthrough 类允许您实现此目的,通常与 RunnableParallel 一起使用,以将数据传递到所构建链中的后续步骤。

让我们来看一个示例:

import {
RunnableParallel,
RunnablePassthrough,
} from "@langchain/core/runnables";

const runnable = RunnableParallel.from({
passed: new RunnablePassthrough<{ num: number }>(),
modified: (input: { num: number }) => input.num + 1,
});

await runnable.invoke({ num: 1 });
{ passed: { num: 1 }, modified: 2 }

如上所示,passed 键通过调用 RunnablePassthrough() 来执行,因此它直接传递了 {'num': 1}

我们还在映射中设置了第二个键 modified。这使用了一个 lambda 函数来设置一个值,将 num 的值加 1,最终得到 modified 键对应的值为 2

检索示例

在下面的示例中,我们将看到一个更贴近实际应用场景的用例:我们结合使用 RunnablePassthroughRunnableParallel 来正确地将输入格式化为提示词:

:::提示 请参阅安装集成包的一般说明部分。 :::

yarn add @langchain/openai @langchain/core
import { StringOutputParser } from "@langchain/core/output_parsers";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import {
RunnablePassthrough,
RunnableSequence,
} from "@langchain/core/runnables";
import { ChatOpenAI, OpenAIEmbeddings } from "@langchain/openai";
import { MemoryVectorStore } from "langchain/vectorstores/memory";

const vectorstore = await MemoryVectorStore.fromDocuments(
[{ pageContent: "harrison worked at kensho", metadata: {} }],
new OpenAIEmbeddings()
);

const retriever = vectorstore.asRetriever();

const template = `Answer the question based only on the following context:
{context}

Question: {question}
`;

const prompt = ChatPromptTemplate.fromTemplate(template);

const model = new ChatOpenAI({ model: "gpt-4o" });

const retrievalChain = RunnableSequence.from([
{
context: retriever.pipe((docs) => docs[0].pageContent),
question: new RunnablePassthrough(),
},
prompt,
model,
new StringOutputParser(),
]);

await retrievalChain.invoke("where did harrison work?");
"Harrison worked at Kensho."

这里的输入提示应该是一个包含键 "context""question" 的映射。用户的输入仅仅是问题。因此,我们需要使用检索器获取上下文,并将用户输入通过 "question" 键传递下去。RunnablePassthrough 使我们能够将用户的问题传递给提示和模型。## 后续步骤现在,你已经了解了如何在链中传递数据,以帮助格式化流经链的数据。要了解更多信息,请参阅本节中有关可运行对象的其他操作指南。


Was this page helpful?


You can also leave detailed feedback on GitHub.