# ValidationError: ToolCall 的 1 个验证错误
value
  输入应为有效整数 [type=int_parsing, input_value='42.5', input_type=str]

- **ID:** `llm/tool-argument-type-coercion-failure`
- **领域:** llm
- **类别:** type_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

使用带有结构化输出的工具调用时，LLM 可能生成字符串形式的参数（例如 '42.5'）而不是预期的类型（例如整数），导致 Pydantic 或 JSON schema 验证在类型强制转换期间失败。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| pydantic==2.5.0 | active | — | — |
| pydantic==2.7.0 | active | — | — |
| openai==1.16.0 | active | — | — |
| gpt-4-turbo-2024-04-09 | active | — | — |

## 解决方案

1. ```
   使用 Pydantic 的 `BeforeValidator` 强制类型转换：`from pydantic import BeforeValidator; def coerce_int(v): return int(float(v)) if isinstance(v, str) else v; class ToolCall(BaseModel): value: Annotated[int, BeforeValidator(coerce_int)]`
   ```
2. ```
   在工具模式中，指定 `type: 'number'` 而不是 `type: 'integer'`，以接受字符串形式的整数和浮点数。
   ```
3. ```
   添加一个重试循环，并附带系统提示，指示 LLM 生成具有正确类型的有效 JSON：'确保所有数字字段是数字，而不是字符串。'
   ```

## 无效尝试

- **** — This may still fail if the string cannot be parsed as the target type (e.g., 'abc' for int) or produces unexpected values. (60% 失败率)
- **** — This can mask genuine errors like out-of-range values or non-numeric strings. (55% 失败率)
