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

如何用RouterChain适配多链不同输入?解决Missing input keys报错

解决LangChain MultiPromptChain路由链的参数匹配问题

核心问题分析

路由到team链时,Router返回的next_inputs仅包含原始问题文本(如input键),但team链需要明确的team参数,导致参数缺失错误。

标准实现方案

1. 调整Router的Prompt模板,明确参数提取要求

修改Router提示词,让LLM不仅返回目标链名称,还要从问题中提取目标链所需参数(如球队名称),并以JSON格式输出。

示例Prompt模板:

from langchain.prompts import PromptTemplate

router_template = """
给定用户问题,判断路由目标链并提取对应参数:
- 球队相关问题路由到"team_chain",提取球队名称作为"team"参数
- 其他问题路由到对应链

必须返回JSON格式,包含两个键:
- "destination": 目标链名称
- "next_inputs": 包含目标链所需参数的字典

用户问题:{input}
格式要求:{format_instructions}
"""

router_prompt = PromptTemplate(
    template=router_template,
    input_variables=["input"],
    partial_variables={"format_instructions": ""}
)

2. 用结构化输出解析器约束格式

使用JsonOutputParser强制LLM输出符合要求的JSON,避免格式混乱。

示例代码:

from langchain.output_parsers import JsonOutputParser
from pydantic import BaseModel, Field

# 定义输出结构约束
class RouteOutput(BaseModel):
    destination: str = Field(description="目标链名称")
    next_inputs: dict = Field(description="目标链所需参数字典")

parser = JsonOutputParser(pydantic_object=RouteOutput)

# 更新Prompt,加入格式说明
router_prompt.partial_variables["format_instructions"] = parser.get_format_instructions()

3. 构建Router链

将LLM、Prompt和解析器组合成Router链,确保输出为结构化字典。

示例代码:

from langchain.llms import OpenAI
from langchain.chains import LLMChain

llm = OpenAI(temperature=0)
router_chain = LLMChain(llm=llm, prompt=router_prompt, output_parser=parser)

4. 定义目标team链

明确team链的输入参数包含team和input:

team_template = """
已知球队联赛冠军数:
- 曼联: 20个
- 利物浦: 19个
- 阿森纳: 13个

回答用户问题:{input}
"""

team_prompt = PromptTemplate(
    template=team_template,
    input_variables=["team", "input"]
)
team_chain = LLMChain(llm=llm, prompt=team_prompt)

5. 组装MultiPromptChain

将Router链和目标链集合传入,确保参数匹配:

from langchain.chains.router import MultiPromptChain

chain_map = {
    "team_chain": team_chain,
    # 其他链...
}

multi_prompt_chain = MultiPromptChain(
    router_chain=router_chain,
    destination_chains=chain_map,
    verbose=True
)

6. 测试验证

调用链测试球队问题:

result = multi_prompt_chain.run("曼联赢得了多少个联赛冠军?")
print(result)

此时Router会返回{"destination": "team_chain", "next_inputs": {"team": "曼联", "input": "曼联赢得了多少个联赛冠军?"}},完全匹配team链的参数要求,不会触发缺失错误。

关键注意点

  • 在Router的Prompt中必须清晰说明每个目标链的参数提取规则
  • 用结构化解析器约束输出格式,避免LLM返回非标准内容
  • 目标链的input_variables要和Router返回的next_inputs键完全对应

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 16:17:47