openai.BadRequestError: 参数无效:参数'temperature'的值不是有效数字:'hot'
openai.BadRequestError: Invalid parameter: value for parameter 'temperature' is not a valid number: 'hot'
ID: llm/function-call-argument-type-mismatch
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| openai==1.30.0 | active | — | — | — |
| python==3.11 | active | — | — | — |
根因分析
由于模式定义不明确或对参数类型的提示不足,LLM生成了错误数据类型的函数调用参数(例如字符串而非数字)。
English
LLM generated a function call argument with the wrong data type (e.g., string instead of number) due to ambiguous schema definitions or insufficient prompting for parameter types.
官方文档
https://platform.openai.com/docs/guides/function-calling解决方案
-
Add explicit type descriptions in the function schema's parameter descriptions: `'temperature': {'type': 'number', 'description': 'A float between 0 and 2, e.g., 0.7. Do NOT use words like hot or cold.'}` and use `enum` constraints if applicable: `'temperature': {'type': 'number', 'enum': [0.0, 0.5, 1.0, 1.5, 2.0]}` -
Implement a validation layer that catches type errors and retries the function call with a corrected prompt: `try: response = client.chat.completions.create(...); except BadRequestError as e: if 'not a valid number' in str(e): corrected_messages = messages + [{'role': 'assistant', 'content': None, 'function_call': ...}, {'role': 'function', 'name': 'validation_error', 'content': f'Type error: {e}'}]; response = retry(corrected_messages)`
无效尝试
常见但无效的做法:
-
65% 失败
LLMs are not reliably type-safe; they may ignore instructions if the schema is ambiguous or if the model's token distribution favors string outputs.
-
85% 失败
This is brittle and doesn't scale; the LLM may generate other invalid types (e.g., arrays instead of objects) that the regex cannot handle.
-
90% 失败
This defeats the purpose of structured tool use and introduces more parsing errors from free-form text.