Langchain中LLMRouterChain集成Agent时缺失text输出键报错求助
Agent与LLMRouterChain集成时「Missing some output keys: {'text'}」错误解决
报错核心原因
- 输出结构不匹配:LLMRouterChain本身的输出默认包含
destination(目标链名称)和next_inputs(传递给目标链的参数),而设置output_key='text'后,整个链路最终需要返回含text键的字典,但路由链与Agent的衔接环节未完成格式转换。 - Agent输出未正确映射:即使给Agent单独设置了
output_key='text',若Agent作为LLMRouterChain的目标链存在,路由链不会自动转换Agent的输出结构,需手动适配格式。 - 默认链输出不符合要求:若路由链未匹配到任何目标链,会调用默认链,若默认链输出无
text键,同样会触发报错。
具体解决步骤
1. 包装Agent为符合输出格式的链
将Agent包装成能返回text键的自定义链,确保路由链调用后拿到正确格式的输出:
from langchain.chains import Chain from typing import Dict, Any class AgentOutputWrapper(Chain): agent_executor: Any @property def input_keys(self): return self.agent_executor.input_keys @property def output_keys(self): return ["text"] def _call(self, inputs: Dict[str, Any]) -> Dict[str, Any]: # 调用Agent执行器 agent_result = self.agent_executor.invoke(inputs) # 提取Agent的输出内容(根据Agent实际输出键调整,比如有的是'output') return {"text": agent_result.get("output", "")} # 包装你的Agent执行器 wrapped_agent = AgentOutputWrapper(agent_executor=your_agent_executor) # 把wrapped_agent作为LLMRouterChain的目标链之一 destination_chains = { "agent_chain": wrapped_agent, # 其他目标链... }
2. 调整Agent的输出解析器
修改Agent的输出解析器,让它直接返回包含text键的结果:
from langchain.schema import AgentOutputParser class CustomTextOutputParser(AgentOutputParser): def parse(self, llm_output: str) -> Dict[str, Any]: # 将LLM输出内容直接放入text键 return {"text": llm_output.strip()} # 给Agent设置这个解析器 your_agent = your_agent.with_output_parser(CustomTextOutputParser()) # 重新初始化Agent执行器 agent_executor = AgentExecutor(agent=your_agent, tools=your_tools, verbose=True)
3. 确保默认链输出格式正确
如果路由链配置了默认链,需让它也返回text键:
from langchain.chains import LLMChain from langchain.prompts import PromptTemplate # 创建默认链,确保输出包含text键 default_prompt = PromptTemplate( input_variables=["input"], template="无法处理你的请求:{input}" ) default_chain = LLMChain(llm=your_llm, prompt=default_prompt, output_key="text") # 初始化路由链时传入默认链 router_chain = LLMRouterChain.from_llm( llm=your_llm, destination_chains=destination_chains, default_chain=default_chain, # 其他参数... )
内容的提问来源于stack exchange,提问作者Shravan K Subrahmanya
相关产品推荐
相关产品推荐

