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

为何在MultiPromptChain中无法用ChatPromptTemplate替代PromptTemplate创建路由提示

LangChain Multi Route Chain路由提示使用ChatPromptTemplate报错解析

问题重现

作为LangChain新手学习Multi Route Chain时,尝试用ChatPromptTemplate替代PromptTemplate创建路由提示,代码如下:

Router_temp = MULTI_PROMPT_ROUTER_TEMPLATE.format(destinations = destination_str)
router_prompt = ChatPromptTemplate(template = Router_temp, input_variables=["input"], output_parser= RouterOutputParser())
router_chain = LLMRouterChain.from_llm(llm =llm, prompt = router_prompt)

运行后抛出错误:KeyError: 'messages'

但此前在类似场景使用ChatPromptTemplate是正常的,示例代码如下:

beginner_phy_teach = """你是专注于基础物理概念的物理老师,名叫费曼,每次都要先自我介绍。用给五岁孩子讲知识的方式解释这些概念
主题如下:
{input}"""

advanced_phy_teach = """你是专注于高等物理概念的物理老师,名叫奥本海默,每次都要先自我介绍。用给有基础的听众讲知识的方式解释这些概念
主题如下:
{input}"""

prompt_info = [
    {"名称": "基础物理老师", "描述": "适合解答基础物理概念相关问题", "模板": beginner_phy_teach},
    {"名称": "高等物理老师", "描述": "适合解答高等物理概念相关问题", "模板": advanced_phy_teach}
]

destination_chains = {}
for p in prompt_info:
    name = p["名称"]
    template = p["模板"]
    chat_prompt = ChatPromptTemplate.from_template(template=template)
    chain = LLMChain(llm=llm, prompt=chat_prompt)
    destination_chains[name] = chain

报错原因

  • LLMRouterChain的内部实现依赖PromptTemplate的纯文本模板结构,它默认处理的是单文本输入;而ChatPromptTemplate本质是封装了多轮消息(系统/用户/助手)的结构,内部会将模板转换为messages格式的数据。
  • 当你直接通过ChatPromptTemplate(template=...)初始化并传给LLMRouterChain.from_llm时,链的底层逻辑会尝试访问prompt对象的messages属性,但这种初始化方式没有正确构建消息结构,导致抛出KeyError: 'messages'。

解决方案

方案1:改用PromptTemplate(官方推荐)

直接使用PromptTemplate创建路由提示,适配LLMRouterChain的设计要求:

from langchain.prompts import PromptTemplate

Router_temp = MULTI_PROMPT_ROUTER_TEMPLATE.format(destinations = destination_str)
router_prompt = PromptTemplate(
    template=Router_temp,
    input_variables=["input"],
    output_parser=RouterOutputParser()
)
router_chain = LLMRouterChain.from_llm(llm=llm, prompt=router_prompt)

方案2:规范使用ChatPromptTemplate

如果一定要用ChatPromptTemplate,需通过from_template方法或显式定义消息角色,确保messages属性正确生成:

# 方式1:使用from_template方法
router_prompt = ChatPromptTemplate.from_template(
    template=Router_temp,
    output_parser=RouterOutputParser()
)

# 方式2:显式构建系统消息模板
from langchain.prompts import SystemMessagePromptTemplate

router_prompt = ChatPromptTemplate(
    messages=[
        SystemMessagePromptTemplate.from_template(Router_temp)
    ],
    input_variables=["input"],
    output_parser=RouterOutputParser()
)

router_chain = LLMRouterChain.from_llm(llm=llm, prompt=router_prompt)

为什么之前的场景正常?

你之前的示例中用ChatPromptTemplate.from_template创建提示并传给LLMChain是正常的,原因在于:

  • LLMChain对ChatPromptTemplate的兼容性更好,能正确解析其内部的messages结构。
  • 而LLMRouterChain的设计初衷是配合简洁的文本路由模板,对ChatPromptTemplate的支持需要严格遵循消息结构要求,直接用template参数初始化会导致结构不完整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 20:21:00