Conda Notebook中Langchain ConversationalAgent报OutputParserException错误求助
Langchain ConversationalAgent 输出解析错误解决方法
错误详情
运行代码时抛出以下解析异常:
File ~\.conda\envs\LLMS\lib\site-packages\langchain\agents\conversational\output_parser.py:26, in ConvoOutputParser.parse(self, text) 24 match = re.search(regex, text) 25 if not match: ---> 26 raise OutputParserException(f"Could not parse LLM output: `{text}`") 27 action = match.group(1) 28 action_input = match.group(2)
OutputParserException: Could not parse LLM output: ` Answer: "Hello, good morning. I am a helpful assistant. Have a normal` morning")`
问题分析
ConversationalAgent的默认ConvoOutputParser依赖正则表达式匹配LLM输出,要求输出必须符合明确的格式规范(要么是Answer: [内容]的直接回答,要么是Action: [工具名]\nAction Input: [输入]的工具调用格式)。但你的LLM输出存在格式混乱:未闭合的引号、换行错误、语法残缺,导致正则匹配失败,触发解析异常。
另外,你最后调用agent_chain.run("Hello, good ")`时输入存在未闭合的反引号,这也会干扰LLM的输出逻辑。
解决方案
1. 明确Prompt中的格式约束
修改prompt的prefix,清晰告知LLM必须遵循的输出格式,避免输出混乱:
prefix = """你是一个乐于助人的助手。和人类进行正常对话,你可以主动提供关于医生信息数据库的查询服务。请严格按照以下格式输出: - 无需调用工具时,直接回答:Answer: [你的完整回答内容] - 需要调用工具查询数据库时,输出: Action: Doctors Database System Action Input: [完整的查询问题] 你可以使用的工具:"""
2. 自定义容错输出解析器
实现自定义解析器,处理LLM格式不规范的情况,避免直接抛出异常:
from langchain.agents.conversational.output_parser import ConvoOutputParser from langchain.schema import OutputParserException import re class CustomConvoOutputParser(ConvoOutputParser): def parse(self, text: str) -> dict: try: # 优先尝试默认解析逻辑 return super().parse(text) except OutputParserException: # 尝试提取Answer字段内容 answer_match = re.search(r"Answer:\s*(.*)", text, re.DOTALL) if answer_match: return {"action": "Final Answer", "action_input": answer_match.group(1).strip().strip('"')} # 若匹配失败,直接返回清理后的原始文本作为最终回答 cleaned_text = text.strip().strip('"`') return {"action": "Final Answer", "action_input": cleaned_text} # 替换Agent的输出解析器 agent = ConversationalAgent( llm_chain=llm_chain, output_parser=CustomConvoOutputParser(), verbose=True )
3. 调整LLM生成参数降低随机性
在HuggingFaceEndpoint配置中增加参数,约束LLM输出的稳定性:
llm_hf = HuggingFaceEndpoint( endpoint_url="https://xxx", huggingfacehub_api_token="xxx", task="text-generation", model_kwargs={ "temperature": 0.1, # 降低随机性,让输出更可控 "max_new_tokens": 200, # 限制输出长度,避免冗余内容 "stop": ["\nQuestion:", "\nAction:", "\nAnswer:"] # 设置停止序列,截断多余输出 } )
4. 修复输入的完整性
确保调用agent_chain.run()时输入是完整有效的文本,比如:
agent_chain.run("Hello, good morning!")
内容的提问来源于stack exchange,提问作者user2940774
相关产品推荐
相关产品推荐

