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

LangChain中RunnableSequence初始化报错求助:TypeError类型不匹配

问题解决:LangChain RunnableSequence 初始化错误

错误原因

你遇到的TypeError是因为RunnableSequence不支持直接传入列表作为构造参数,新版本LangChain中,RunnableSequence的构造需要通过指定first/last/middle参数,或者直接传入多个步骤作为位置参数(而非列表),更推荐的方式是使用管道操作符|来串联Runnable组件。

同时代码里还有两个小问题:

  • get_openai_callback的上下文变量是CB,但最后打印的是小写cb,会导致未定义错误
  • 不需要用RunnableLambda包装PromptTemplate,因为PromptTemplate本身已经实现了Runnable接口

修改后的代码

import langchain, pydantic, transformers
from langchain import HuggingFacePipeline
from langchain_core.prompts import PromptTemplate
from langchain_core.runnables.base import RunnableSequence

from langchain.callbacks import get_openai_callback
from pydantic import BaseModel, Field
from langchain.output_parsers import PydanticOutputParser
from transformers import pipeline

class MedicalSpecialty(BaseModel):
    medical_specialty: str = Field(description="medical specialty the patient should go to")
    urgent: bool = Field(description="the patient should go to the hospital immediately")

parser = PydanticOutputParser(pydantic_object=MedicalSpecialty)

queries = ["i have ache in my chest and in my left arm. Which medical specialty should I go to?"]

template = """
Question: {question}
"""
prompt = PromptTemplate(template=template, input_variables=["question"])

llm = HuggingFacePipeline.from_model_id(
    model_id="bigscience/bloom-1b7",
    task="text-generation",
    model_kwargs={"max_length": 1024},
    device=-1  # Ensure it runs on CPU for macOS M1
)

# 方式1:使用管道操作符(推荐,更简洁)
sequence = prompt | llm

# 方式2:直接传入步骤作为位置参数
# sequence = RunnableSequence(prompt, llm)

# 方式3:通过first/last参数指定
# sequence = RunnableSequence(first=prompt, last=llm)

with get_openai_callback() as cb:
    for query in queries:
        result = sequence.invoke({"question": query})
        print(query)
        print(result)
        print("====================================")
    
    # 修正变量大小写问题
    print(cb)

关键修改点说明

  1. 移除不必要的RunnableLambda包装:PromptTemplate本身就是Runnable,直接使用即可,无需额外封装
  2. 正确创建RunnableSequence:三种方式任选其一,管道符|是LangChain推荐的链式调用写法,代码更直观
  3. 修正变量大小写错误:上下文变量cb保持一致,避免未定义异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 01:15:57