OutputParserException:解析由 'PydanticOutputParser' 生成的 LLM 输出失败。错误:WeatherResponse 的 1 个验证错误 temperature 输入应为有效数字 [type=float_type, input_value='72.5°F', input_type=str]
OutputParserException: Parsing LLM output produced by 'PydanticOutputParser' failed. Error: 1 validation error for WeatherResponse temperature Input should be a valid number [type=float_type, input_value='72.5°F', input_type=str]
ID: llm/langchain-output-parser-schema-mismatch
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| langchain 0.2.0 | active | — | — | — |
| langchain-openai 0.1.0 | active | — | — | — |
| pydantic 2.5.0 | active | — | — | — |
| GPT-4 Turbo | active | — | — | — |
| Claude 3 Opus | active | — | — | — |
根因分析
LLM 输出包含额外的非数字字符(例如单位 '°F'),Pydantic 输出解析器无法将其强制转换为预期的数字类型。
English
LLM output contains extra non-numeric characters (e.g., units like '°F') that the Pydantic output parser cannot coerce into the expected numeric type.
官方文档
https://python.langchain.com/docs/modules/model_io/output_parsers/解决方案
-
在解析前添加后处理步骤以去除单位。代码示例:`raw_output = llm_output.replace('°F', '').replace('°C', ''); parsed = parser.parse(raw_output)`。 -
使用明确禁止单位的自定义提示,例如 '将温度作为纯数字返回,不要包含 °F 或 °C 等单位。'
-
切换到 `JsonOutputParser` 并结合 Pydantic 进行后验证,允许更灵活地解析数字字段。
无效尝试
常见但无效的做法:
-
70% 失败
The issue is not randomness; the LLM is following its training to include units. Temperature 0 still produces units in many cases.
-
90% 失败
The output is complete but includes extra text; max_tokens does not affect the content format.
-
60% 失败
LangChain's PydanticOutputParser does not use OpenAI's response_format internally; it parses arbitrary text output. The JSON mode may not be compatible with the parser's prompt template.