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

使用SimpleSequentialChain时出现KeyError: 'chains'问题求助

解决SimpleSequentialChain触发KeyError: 'chains'的问题

问题场景

使用WatsonxLLM类创建LLM后,运行代码时触发KeyError: 'chains',错误发生在validate_chains函数执行for chain in values["chains"]:语句时。原代码如下:

from langchain_core.prompts import PromptTemplate
from langchain.chains.sequential import SimpleSequentialChain

prompt_1 = PromptTemplate(
    input_variables=["topic"],
    template="Generate a random question about {topic}: Question: "
    )
prompt_2 = PromptTemplate(
    input_variables=["question"],
    template="Answer the following question: {question}",
    )

llm1 = flan_ul2_llm
prompt_to_flan_ul2 = prompt_1 | llm1
llm2 = flan_t5_llm
flan_to_t5 = prompt_2 | llm2
qa = SimpleSequentialChain(chains=[prompt_to_flan_ul2, flan_to_t5])
qa.invoke('weather')

原因分析

  1. 类型不匹配:用|运算符组合PromptTemplate和LLM得到的是Runnable对象,而SimpleSequentialChain要求传入的是Chain类型实例(如LLMChain),而非Runnable序列。
  2. 版本参数差异:部分LangChain版本中,SimpleSequentialChain的初始化参数逻辑有调整,直接传入Runnable列表会导致参数解析失败。

解决方案

方案1:改用RunnableSequence(推荐)

LangChain当前推荐使用Runnable体系组合组件,替代旧的Chain类,代码更简洁兼容:

from langchain_core.prompts import PromptTemplate

prompt_1 = PromptTemplate(
    input_variables=["topic"],
    template="Generate a random question about {topic}: Question: "
    )
prompt_2 = PromptTemplate(
    input_variables=["question"],
    template="Answer the following question: {question}",
    )

llm1 = flan_ul2_llm
prompt_to_flan_ul2 = prompt_1 | llm1
llm2 = flan_t5_llm
flan_to_t5 = prompt_2 | llm2

# 直接组合两个Runnable序列
qa = prompt_to_flan_ul2 | flan_to_t5
qa.invoke('weather')

方案2:用LLMChain包装后传入SimpleSequentialChain

如果坚持使用SimpleSequentialChain,需先将每个步骤包装为LLMChain实例:

from langchain_core.prompts import PromptTemplate
from langchain.chains.sequential import SimpleSequentialChain
from langchain.chains.llm import LLMChain

prompt_1 = PromptTemplate(
    input_variables=["topic"],
    template="Generate a random question about {topic}: Question: "
    )
prompt_2 = PromptTemplate(
    input_variables=["question"],
    template="Answer the following question: {question}",
    )

llm1 = flan_ul2_llm
# 将prompt和LLM包装为LLMChain
chain1 = LLMChain(llm=llm1, prompt=prompt_1)
llm2 = flan_t5_llm
chain2 = LLMChain(llm=llm2, prompt=prompt_2)

# 传入LLMChain列表初始化SimpleSequentialChain
qa = SimpleSequentialChain(chains=[chain1, chain2])
qa.invoke('weather')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 19:32:19