You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LangChain v0.2中如何在RunnableSequences间传递输入参数?

解决LangChain v0.2中RunnableSequences传递输入参数的问题

问题核心是code_chain的输出仅包含code字段,丢失了language参数,导致test_chain无法获取所需变量。以下是两种可行的解决方法:

方法一:用RunnablePassthrough.assign保留全部原始输入参数

通过RunnablePassthrough.assign()将code_chain的输出与原始输入参数合并,确保language能传递到test_chain:

from langchain_core.runnables import RunnablePassthrough

code_prompt = PromptTemplate.from_template("Write a very short {language} function that will {task}")
code_chain = code_prompt | llm | {"code": StrOutputParser()}

test_prompt = PromptTemplate.from_template("Write a test for the following {language} code:\n{code}")
test_chain = test_prompt | llm | {"test": StrOutputParser()}

# 合并原始输入和code_chain的输出,保留所有输入参数
chain = RunnablePassthrough.assign(code=code_chain) | test_chain

result = chain.invoke({
    "language": "python",
    "task": "reverse a string",
})

方法二:显式在code_chain中保留language参数

修改code_chain的结构,让它同时返回language和code两个字段,直接满足test_chain的参数需求:

code_prompt = PromptTemplate.from_template("Write a very short {language} function that will {task}")
# 显式传递language参数,同时生成code
code_chain = {
    "language": lambda x: x["language"],
    "code": code_prompt | llm | StrOutputParser()
}

test_prompt = PromptTemplate.from_template("Write a test for the following {language} code:\n{code}")
test_chain = test_prompt | llm | {"test": StrOutputParser()}

chain = code_chain | test_chain

result = chain.invoke({
    "language": "python",
    "task": "reverse a string",
})

两种方法的区别:

  • 方法一适合需要传递多个原始参数的场景,会保留所有输入变量;
  • 方法二更灵活,可精准控制要传递的参数,避免冗余数据。

内容的提问来源于stack exchange,提问作者halllo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 18:20:57