如何在OpenAI Response API的 Create Response中使用结构化输出

人工智能 2026-07-10

Open AI API创建模型响应 表示它可以启用结构化输出,但找不到用于输出的JSON架构的方法。

配置 { "type": "json_schema" } 以启用结构化输出

Open AI文档 - 结构化模型输出parse 调用,但 Response API 没有这样的API。

response = client.responses.parse(
    model="gpt-4o-2024-08-06",
    input=[
        {"role": "system", "content": "Extract the event information."},
        {
            "role": "user",
            "content": "Alice and Bob are going to a science fair on Friday.",
        },
    ],
    text_format=CalendarEvent,
)

Responses API文档关于结构化输出的缺失 提到也没有可用的文档。

解决方案

This works.

from pydantic import BaseModel, Field, ConfigDict
from openai import OpenAI


class PythonSyntax(BaseModel):
    """Schema for the Python query answer"""
    specification: list[str] = Field(
        description="Python specifications referred to for the answer"
    )
    uri: list[str] = Field(
        description="URIs of the specifications referred"
    )
    answer: str = Field(
        description="Final answer to the query"
    )
    note: str = Field(
        description="Additional notes or clarifications"
    )
    model_config = ConfigDict(extra="forbid")  # adds additionalProperties: false


system_role: str = """
You are a meticulous coding assistant who does not answer without verifying the code with the Python specifications.
You reply the answer in the given Python JSON schema including:
* specificaition: Specification reference such as PEP 8.
* uri: URI of the specification
* answer: reply to the inquiry
* note: any other information for the note.
"""

client = OpenAI()
response = client.responses.create(
    model=MODEL,
    instructions=system_role,
    input="How do I check if a Python object is an instance of a class?",
    tools=[
        { "type": "web_search" }
    ],
    tool_choice="required",
    metadata={
        "user_id": "mon",
        "internal_project_id": "personal",
        "session_type": "personal"
    },
    temperature=0,
    max_output_tokens=1024,
    text={
        "format": {
            "name": "PythonSyntax",
            "type": "json_schema",
            "strict": True,
            "schema": PythonSyntax.model_json_schema()
        }
    },
    stream=False
)

有两个修复点。

  1. py "strinct": True
  2. py model_config = ConfigDict(extra="forbid")

参考文献

结构化输出仅支持生成指定的键/值,因此我们要求开发者将 additionalProperties: false 设置为开启结构化输出。

additionalProperties关键字用于控制对额外属性的处理,即那些名称未在properties关键字中列出,或不匹配patternProperties关键字中的正则表达式的属性。默认情况下,允许任何额外属性。

给每个类打上标签:
model_config = ConfigDict(extra='forbid')

没有明确的Pydantic文档说明 model_config = ConfigDict(extra="forbid") 在JSON架构中添加了 additionalProperties: false

Open AI API文档也没有涉及 "strict": True

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章