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

如何将基于LLMChain与SequentialChain的LangChain代码迁移为管道(|)运算符实现

如何将基于LLMChain与SequentialChain的LangChain代码迁移为管道(|)运算符实现

嘿,我明白你的困惑!你遇到的TypeError是因为直接用|把两个链连起来时,第一个链输出的是字符串(比如解析后的国家名称),但第二个链的提示模板需要的是包含country和subject等键的字典映射,自然就报错了。

咱们一步步来重构你的代码,完全替换掉LLMChain和SequentialChain:

核心问题拆解

原来的SequentialChain会自动把前一个链的output_key(也就是country)和原始输入变量合并,传给下一个链。但用管道运算符时,得手动处理输入的传递和合并——这时候就要用到RunnablePassthrough.assign()来帮我们做这件事。

完整重构代码

import json

from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser, JsonOutputParser
from langchain_openai import ChatOpenAI
from langchain_core.runnables import RunnablePassthrough


api_key="sk-YOUR_OPENAI_API_KEY"

llm = ChatOpenAI(
      model="gpt-4o",
      temperature=0,
      max_tokens=None,
      timeout=None,
      max_retries=2,
      seed=42,
      api_key=api_key)

prompt_candidates = ChatPromptTemplate.from_template(
    """A trivia game has asked to which country does the town of '{town}' belong to, and the options are:

{country_options}

Only return the correct option chosen based on your knowledge, nothing more"""
)

prompt_finalists = ChatPromptTemplate.from_template(
    """Your task is to build OUTPUTWORD, follow these instructions:

1. Get CAPITAL CITY: It is the capital city of {country}
2. Get INITIAL LETTER: It is the initial letter of the CAPITAL CITY
3. Get OUTPUTWORD: Make a word starting with INITIAL LETTER and related with {subject}

Return the result in a JSON object with key `output` and OUTPUTWORD its correspondent output"""
)

# -------------------- 重构后的管道式实现 --------------------
# 第一个链:识别城镇所属国家,输出字符串
chain_a = prompt_candidates | llm | StrOutputParser()

# 合并输入:保留原始输入的subject等字段,同时将chain_a的结果赋值给country键
# 这样第二个链就能拿到{country}和{subject}所需的变量
combined_input = RunnablePassthrough.assign(country=chain_a)

# 第二个链:生成符合要求的单词,直接输出JSON(绑定LLM的JSON输出格式)
# 加上JsonOutputParser()可以直接得到Python字典,不用手动解析
chain_b = prompt_finalists | llm.bind(response_format={"type": "json_object"}) | JsonOutputParser()

# 组合成最终链
final_chain = combined_input | chain_b

# 调用链(输入格式和原来完全一致)
result = final_chain.invoke(
    {
        "town": "Puembo",
        "country_options": ["Ukraine", "Ecuador", "Uzbekistan"],
        "subject": "Biology"
    }
)

print(result)
# 输出示例:{'output': 'Ecosystem'}

关键细节说明

  1. RunnablePassthrough.assign()的作用:它会把原始输入(比如town、subject)原封不动地传下去,同时新增一个country键,值是chain_a的输出结果——完美匹配第二个提示模板的变量需求。
  2. JSON输出处理:llm.bind(response_format={"type": "json_object"})让LLM直接输出JSON格式的字符串,加上JsonOutputParser()后能直接得到Python字典,省去了手动解析的步骤。
  3. 管道的灵活性:这种方式比SequentialChain更灵活,你可以随时插入自定义的处理步骤(比如对country做额外校验),只要保证每个步骤的输出格式符合下一个步骤的输入要求就行。

备注:内容来源于stack exchange,提问作者David Espinosa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 08:39:29