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

如何在LangChain最终输出中获取中间链步骤的输出?

解决LangChain链输出格式混乱问题

要实现保留所有输入及中间步骤结果的扁平JSON输出,核心是用RunnablePassthrough.assign()来逐步合并结果,它的作用就像Python的dict.update(),能把新生成的键值对添加到原有上下文字典中,避免嵌套。

修正后的代码

from langchain.prompts import PromptTemplate
from langchain.chat_models import ChatOpenAI
from langchain.output_parsers import SimpleJsonOutputParser
from langchain.schema.runnable import RunnablePassthrough

# 初始化LLM(根据实际使用的模型替换)
llm = ChatOpenAI(temperature=0)

# 修正第一个prompt模板,明确输出格式要求
first_prompt = PromptTemplate.from_template("""
从以下文本中提取所有人名,以JSON格式返回,仅包含`first_prompt_output`字段:
文本:{first_value}
""")

# 修正第二个prompt模板,简化输出要求
second_prompt = PromptTemplate.from_template("""
现有候选值列表:{possible_values},以及提取出的人名列表:{first_prompt_output}
找出同时存在于两个列表中的值,以JSON格式返回,仅包含`second_prompt_output`字段即可
""")

first_value = "Dave, John"
possible_values = ["John"]

# 第一步链:提取人名,输出含first_prompt_output的字典
first_chain = first_prompt | llm | SimpleJsonOutputParser()

# 第二步链:验证人名,输出含second_prompt_output的字典
second_chain = second_prompt | llm | SimpleJsonOutputParser()

# 构建完整链:先保留原始输入,再依次添加中间结果
chain = (
    RunnablePassthrough()  # 保留原始输入(first_value、possible_values)
    | RunnablePassthrough.assign(first_prompt_output=first_chain)  # 追加第一步提取结果
    | RunnablePassthrough.assign(second_prompt_output=second_chain)  # 追加第二步验证结果
)

# 调用链并查看结果
result = chain.invoke({"first_value": first_value, "possible_values": possible_values})
print(result)

预期输出示例

{
  "first_value": "Dave, John",
  "possible_values": ["John"],
  "first_prompt_output": ["Dave", "John"],
  "second_prompt_output": ["John"]
}

原代码格式混乱的原因

  1. 最初的链结构中,{"first_prompt_output": first_chain, "possible_values": RunnablePassthrough(), "first_value": RunnablePassthrough()} 会把整个原始输入字典赋值给possible_values和first_value,导致这两个字段的值是嵌套字典,而非原始输入值。
  2. 后续的RunnableParallel额外嵌套了result层级,进一步打乱了输出结构。

用RunnablePassthrough()先保留原始输入,再通过assign()依次添加中间结果,就能得到扁平的、包含所有输入和步骤结果的JSON输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 19:41:02