llm config_error ai_generated true

openai.BadRequestError: response_format的schema无效:'properties'必须是字符串键的对象。

openai.BadRequestError: Invalid schema for response_format: 'properties' must be an object with string keys.

ID: llm/structured-output-schema-mismatch

其他格式: JSON · Markdown 中文 · English
90%修复率
90%置信度
1证据数
2023-11-20首次发现

版本兼容性

版本状态引入弃用备注
openai>=1.0.0 active
openai>=1.12.0 active

根因分析

response_format参数中提供的JSON schema格式错误,例如使用整数键或缺少必需的字段如'type'。

English

The JSON schema provided in the response_format parameter is malformed, e.g., using integer keys or missing required fields like 'type'.

generic

官方文档

https://platform.openai.com/docs/guides/structured-outputs

解决方案

  1. 使用Pydantic库自动生成并验证schema:
    from pydantic import BaseModel
    from openai import OpenAI
    
    class ResponseModel(BaseModel):
        name: str
        age: int
    
    client = OpenAI()
    schema = ResponseModel.model_json_schema()
    print(schema)  # 检查'properties'是否有字符串键
    response = client.chat.completions.create(
        model='gpt-4o-mini',
        messages=[{'role': 'user', 'content': '提取信息'}],
        response_format={
            'type': 'json_schema',
            'json_schema': {'name': 'response', 'schema': schema}
        }
    )
  2. 手动确保schema具有正确的结构:
    {
        'type': 'object',
        'properties': {
            'name': {'type': 'string'},
            'age': {'type': 'integer'}
        },
        'required': ['name', 'age']
    }

无效尝试

常见但无效的做法:

  1. 50% 失败

    OpenAI's schema validation is stricter than standard JSON; it requires specific keys like 'type': 'object' and 'properties' must be an object.

  2. 40% 失败

    Older models may not support the same schema features; the schema must comply with OpenAI's JSON Schema subset.