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

LangChain Agent输出解析异常求助(AWS Bedrock/Lambda环境)

解决AWS Bedrock+Lambda RAG中LangChain Agent解析错误的方案

核心问题定位

问题出在Bedrock模型偶尔输出重复的<|start_header_id|>标记,导致默认解析器崩溃,哪怕开启handle_parsing_errors=True也无法处理这种格式异常。


1. 给LLM输出做前置“清洁”

直接在LLM返回结果后清理重复标记,最简单的方式是添加回调处理器:

from langchain.callbacks.base import BaseCallbackHandler

class BedrockOutputCleaner(BaseCallbackHandler):
    def on_llm_end(self, response, **kwargs):
        # 将重复的header标记替换为单个正常标记
        cleaned_text = response.generations[0][0].text.replace("<|start_header_id|><|start_header_id|>", "<|start_header_id|>")
        response.generations[0][0].text = cleaned_text

# 初始化Bedrock LLM时挂载这个回调
llm = Bedrock(model_id="anthropic.claude-v2", callbacks=[BedrockOutputCleaner()])

也可以在Agent拿到LLM输出后直接执行文本替换,确保传入解析器的内容格式合规。

2. 替换为容错性更强的自定义解析器

默认解析器对格式异常容忍度极低,自己实现一个鲁棒性解析器,遇到解析失败直接返回内容而非报错:

from langchain.agents import AgentOutputParser
from langchain.schema import AgentAction, AgentFinish

class RobustOutputParser(AgentOutputParser):
    def parse(self, llm_output: str) -> AgentAction | AgentFinish:
        # 先清理异常标记
        cleaned_output = llm_output.replace("<|start_header_id|><|start_header_id|>", "<|start_header_id|>")
        try:
            # 遵循zero-shot-react-description的格式逻辑解析
            if "Final Answer:" in cleaned_output:
                return AgentFinish(
                    return_values={"output": cleaned_output.split("Final Answer:")[-1].strip()},
                    log=cleaned_output,
                )
            # 拆分Action与Action Input字段
            action_split = cleaned_output.split("Action:")
            if len(action_split) < 2:
                return AgentFinish(return_values={"output": cleaned_output.strip()}, log=cleaned_output)
            input_split = action_split[1].split("Action Input:")
            if len(input_split) < 2:
                return AgentFinish(return_values={"output": cleaned_output.strip()}, log=cleaned_output)
            return AgentAction(
                tool=input_split[0].strip(),
                tool_input=input_split[1].strip().strip('"'),
                log=cleaned_output
            )
        except Exception:
            # 任意解析错误发生时,直接返回清理后的内容
            return AgentFinish(return_values={"output": cleaned_output.strip()}, log=cleaned_output)

# 初始化Agent时指定自定义解析器
agent = initialize_agent(
    tools,
    llm,
    agent="zero-shot-react-description",
    agent_kwargs={"output_parser": RobustOutputParser()},
    handle_parsing_errors=True,
    verbose=True
)

3. 给Bedrock模型明确格式约束

在prompt末尾追加严格的格式要求,避免模型输出多余标记:

请严格按照以下格式输出,禁止添加任何额外的格式标记(比如<|start_header_id|>):
思考:你的推理过程
行动:工具名称
行动输入:工具输入内容
若无需调用工具,直接输出:Final Answer: 你的答案内容

4. 升级LangChain相关依赖包

旧版本LangChain对Bedrock的兼容性可能存在漏洞,升级到最新稳定版尝试修复:

pip install --upgrade langchain langchain-aws

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 19:52:35