OutputParserException:由'StructuredOutputParser'生成的 LLM 输出解析失败——值'large'不在枚举['small', 'medium']中
OutputParserException: Parsing LLM output produced by 'StructuredOutputParser' failed — value 'large' not in enum ['small', 'medium']
ID: llm/langchain-output-parser-enum
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| langchain>=0.1.0 | active | — | — | — |
| langchain-core>=0.1.0 | active | — | — | — |
| pydantic>=2.0.0 | active | — | — | — |
根因分析
LLM 在使用 LangChain 的结构化输出解析器和 Pydantic 模型时生成了指定枚举约束之外的值,通常是由于提示不足或模型幻觉。
English
LLM generated a value outside the specified enum constraints when using LangChain's structured output parsers with Pydantic models, often due to insufficient prompting or model hallucination.
官方文档
https://python.langchain.com/docs/modules/model_io/output_parsers/structured解决方案
-
改进提示,显式列出允许的枚举值,并指示模型仅输出这些确切值:'大小必须恰好是以下之一:small, medium。不要输出任何其他值。'
-
在支持 JSON 模式的聊天模型上使用 LangChain 的 with_structured_output 方法,该方法在 API 级别强制模式约束,而不是依赖解析。
-
实现一个后处理回退,使用相似度启发式或手动映射将超出枚举的值映射到最接近的有效枚举成员。
无效尝试
常见但无效的做法:
-
70% 失败
This defeats the purpose of constrained output; the LLM may still generate unexpected values outside the expanded set
-
50% 失败
Even with temperature=0, LLMs can produce non-deterministic outputs due to floating-point rounding or model updates
-
80% 失败
Silent fallback masks errors and may produce incorrect downstream results, leading to hard-to-debug issues