如需完整的文件索引,請參閱 llms.txt。在文件頁面的網址末尾加上 .md ,即可取得該頁面的 Markdown 版本。
主要導覽
主題

模型的結構化輸出

確保模型的文字回應符合你定義的 JSON 結構描述。

JSON 是全球應用程式交換資料時最常用的格式之一。

模型未拒絕請求且已完整產生回應時,結構化輸出可確保該回應符合你提供的 JSON 結構描述。應用程式仍須處理拒絕回應、不完整的回應及 API 錯誤,並確認輸出符合結構描述未涵蓋的所有業務規則。

結構化輸出的優點包括:

  1. 符合結構描述: 只要你提供的是支援的 JSON 結構描述,輸出就會包含所有必要欄位,列舉值也會符合結構描述的規定。
  2. 明確標示拒絕回應: 現在可以透過程式偵測模型是否基於安全考量拒絕請求。
  3. 提示詞更簡單: 無須在提示詞中反覆強調格式要求,就能取得格式一致的回應。

除了 REST API 支援 JSON 結構描述,OpenAI 的 Python 和 JavaScript 程式庫也分別支援使用 pydantic.BaseModel 和 z.object 定義物件的結構描述。下列範例示範如何從非結構化文字中擷取資訊,讓結果符合程式碼中定義的結構描述。

Ruby SDK 支援以 Sorbet T::Struct 定義的結構描述,並會傳回具有型別的解析結果。

取得結構化回應
from openai import OpenAI
from pydantic import BaseModel

client = OpenAI()


class CalendarEvent(BaseModel):
    name: str
    date: str
    participants: list[str]


response = client.responses.parse(
    model="gpt-6-astra",
    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,
)

event = response.output_parsed

支援的模型

從 GPT-4o 開始,我們的最新大型語言模型都支援結構化輸出。新專案建議從 gpt-6-astra 開始。gpt-4-turbo 及更早的模型則可改用 JSON 模式。

使用結構化輸出時,何時該用函式呼叫,何時該用 text.format

OpenAI API 提供兩種使用結構化輸出的方式:

  1. 使用函式呼叫
  2. 使用 json_schema 回應格式

如果你要讓模型使用應用程式提供的功能,函式呼叫就很適合。

舉例來說,你可以讓模型呼叫查詢資料庫的函式,藉此打造能協助使用者處理訂單的 AI 助理,也可以讓模型呼叫能與使用者介面互動的函式。

如果你要指定的是模型回覆使用者時應遵循的結構描述,而非模型呼叫工具時使用的結構描述,則較適合透過 response_format 使用結構化輸出。

例如,開發數學輔導應用程式時,你可以讓助理依照特定的 JSON 結構描述回覆使用者,這樣就能產生使用者介面,以不同方式呈現模型輸出的各個部分。

實際使用時:

  • 如果要讓模型使用系統中的工具、函式或資料等資源,請使用函式呼叫。如果要指定模型回覆使用者時的輸出結構,請使用結構化的 text.format。

本指南接下來將說明如何在 Responses API 中使用結構化輸出,適用於無須呼叫函式的情境。若想瞭解如何搭配函式呼叫使用結構化輸出,請參閱

函式呼叫

指南。

結構化輸出與 JSON 模式的差異

結構化輸出是 JSON 模式的進階版本。兩者都能確保產生有效的 JSON,但只有結構化輸出能確保結果符合指定的結構描述。Responses API、Chat Completions API、Assistants API、Fine-tuning API 和 Batch API 都支援結構化輸出與 JSON 模式。

只要可行,建議一律優先使用結構化輸出。

不過,透過 response_format: {type: "json_schema", ...} 使用結構化輸出時,只有 gpt-4o-mini、gpt-4o-mini-2024-07-18、gpt-4o-2024-08-06 及後續模型快照支援這項設定。

結構化輸出 JSON 模式
輸出有效的 JSON 是 是
符合結構描述 是(請參閱支援的結構描述) 否
相容模型 gpt-4o-mini、gpt-4o-2024-08-06 及後續模型 gpt-3.5-turbo、gpt-4-*、gpt-4o-* 及相容的 GPT-5 模型
啟用方式 text: { format: { type: "json_schema", "strict": true, "schema": ... } } text: { format: { type: "json_object" } }

範例

思路鏈

你可以要求模型以結構化格式逐步作答,引導使用者理解每個解題步驟。

在數學教學中以結構化輸出呈現思路鏈
from openai import OpenAI
from pydantic import BaseModel

client = OpenAI()


class Step(BaseModel):
    explanation: str
    output: str


class MathReasoning(BaseModel):
    steps: list[Step]
    final_answer: str


response = client.responses.parse(
    model="gpt-6-astra",
    input=[
        {
            "role": "system",
            "content": "You are a helpful math tutor. Guide the user through the solution step by step.",
        },
        {"role": "user", "content": "how can I solve 8x + 7 = -23"},
    ],
    text_format=MathReasoning,
)

math_reasoning = response.output_parsed

回應範例

{
  "steps": [
    {
      "explanation": "Start with the equation 8x + 7 = -23.",
      "output": "8x + 7 = -23"
    },
    {
      "explanation": "Subtract 7 from both sides to isolate the term with the variable.",
      "output": "8x = -23 - 7"
    },
    {
      "explanation": "Simplify the right side of the equation.",
      "output": "8x = -30"
    },
    {
      "explanation": "Divide both sides by 8 to solve for x.",
      "output": "x = -30 / 8"
    },
    {
      "explanation": "Simplify the fraction.",
      "output": "x = -15 / 4"
    }
  ],
  "final_answer": "x = -15 / 4"
}

如何搭配下列設定使用結構化輸出:text.format

在對話中變更回應格式

若要讓下一次回應改用新的結構描述,請先將 configuration_update 項目附加到 input,再附加下一則使用者訊息。每次發出請求時,都要保留原本的頂層 text.format 設定,讓先前的提示詞前綴仍符合提示詞快取的條件。

在支援這項功能的 GPT-6 及後續模型上,使用標準單一智慧體模式時,可以更新回應格式。

假設上一輪對話以純文字說明某批貨物包含 17 個紅色貨箱和 26 個藍色貨箱。請使用 previous_response_id 延續對話,並將下列陣列作為 input 傳入。

從純文字切換為以結構化格式傳回貨箱總數
from openai import OpenAI
from pydantic import BaseModel, ConfigDict


class CrateCount(BaseModel):
    model_config = ConfigDict(extra="forbid")
    total_crates: int


client = OpenAI()
model = "gpt-6-astra"

first = client.responses.create(
    model=model,
    input="Summarize this shipment in one sentence: 17 red crates and 26 blue crates.",
    store=True,
)

second = client.responses.parse(
    model=model,
    previous_response_id=first.id,
    input=[
        {
            "type": "configuration_update",
            "text": {
                "format": {
                    "type": "json_schema",
                    "name": "crate_count",
                    "schema": CrateCount.model_json_schema(),
                    "strict": True,
                }
            },
        },
        {"role": "user", "content": "How many crates are in the shipment?"},
    ],
    parse_as=CrateCount,
)

if second.status == "completed" and second.output_parsed is not None:
    print(second.output_parsed.total_crates)

預期的答案是 {"total_crates":43}。回應物件中的 text.format 仍會顯示原本在請求層級指定的格式。先確認模型沒有拒絕請求,且回應完整,再使用最近一次格式更新所指定的結構描述解析答案。

每次更新格式都會取代整個格式設定。更新後的格式會持續套用到後續各輪對話,即使你只更新 reasoning.effort 也一樣。若要切換回純文字,請附加 {"type":"configuration_update","text":{"format":{"type":"text"}}}。格式更新僅接受 json_schema 和 text。

如果你手動重播對話記錄,請將每個更新項目保留在原來的位置。明確執行壓縮後,請重新指定你變更過的每一項設定。詳見設定更新的相容性。

使用結構化輸出時的拒絕回應

使用結構化輸出處理使用者提供的輸入時,OpenAI 模型偶爾會基於安全考量拒絕執行請求。由於拒絕回應不一定符合你在 response_format 中提供的結構描述,API 回應會包含名為 refusal 的新欄位,表示模型已拒絕執行請求。

如果輸出物件中出現 refusal 屬性,你可以在使用者介面顯示拒絕訊息,或在處理回應的程式碼中加入條件判斷,以處理請求遭拒的情況。

class Step(BaseModel):
    explanation: str
    output: str


class MathReasoning(BaseModel):
    steps: list[Step]
    final_answer: str


response = client.responses.parse(
    model="gpt-6-astra",
    input=[
        {
            "role": "system",
            "content": "You are a helpful math tutor. Guide the user through the solution step by step.",
        },
        {"role": "user", "content": "how can I solve 8x + 7 = -23"},
    ],
    text_format=MathReasoning,
)

for output in response.output:
    if output.type != "message":
        continue

    for item in output.content:
        if item.type == "refusal":
            # If the model refuses to respond, you will get a refusal message
            print(item.refusal)
            continue

        if not item.parsed:
            raise Exception("Could not parse response")

        print(item.parsed)

模型拒絕請求時,API 回應會類似下列範例:

{
  "id": "resp_1234567890",
  "object": "response",
  "created_at": 1721596428,
  "status": "completed",
  "completed_at": 1721596429,
  "error": null,
  "incomplete_details": null,
  "input": [],
  "instructions": null,
  "max_output_tokens": null,
  "model": "gpt-4o-2024-08-06",
  "output": [{
    "id": "msg_1234567890",
    "type": "message",
    "role": "assistant",
    "content": [
      {
        "type": "refusal",
        "refusal": "I'm sorry, I cannot assist with that request."
      }
    ]
  }],
  "usage": {
    "input_tokens": 81,
    "output_tokens": 11,
    "total_tokens": 92,
    "output_tokens_details": {
      "reasoning_tokens": 0,
    }
  },
}

使用技巧與最佳做法

處理使用者提供的輸入

如果應用程式會處理使用者提供的輸入,請在提示詞中說明,當模型無法根據輸入產生有效回應時,應如何處理。

模型一律會嘗試遵循指定的結構描述,因此如果輸入與結構描述完全無關,模型可能會編造內容。

你可以在提示詞中明確要求模型,如果發現輸入與任務不相符,就傳回空的參數或指定的句子。

處理錯誤

結構化輸出的內容仍可能有誤。如果發現錯誤,可以試著調整指示、在系統指示中提供範例,或將任務拆分成較簡單的子任務。如需更多調整輸入的建議,請參閱提示工程指南。

避免 JSON 結構描述與型別不一致

為了讓 JSON 結構描述與程式語言中對應的型別保持一致,只要 SDK 有提供原生的結構描述輔助工具,我們就強烈建議使用。

如果你偏好直接指定 JSON 結構描述,可以新增 CI 規則,在有人修改 JSON 結構描述或底層資料物件時發出提醒。也可以新增 CI 步驟,根據型別定義自動產生 JSON 結構描述,或反過來從結構描述產生型別定義。

串流

當模型產生回應或函式呼叫引數時,你可以透過串流逐步處理這些內容,並將其解析為結構化資料。

這樣就能在收到完整回應前開始處理。 如果你想逐一顯示 JSON 欄位,或在收到函式呼叫引數時立即處理,串流就特別有用。

使用結構化輸出時,建議透過 SDK 處理串流。

from openai import OpenAI
from pydantic import BaseModel


class EntitiesModel(BaseModel):
    attributes: list[str]
    colors: list[str]
    animals: list[str]


client = OpenAI()

with client.responses.stream(
    model="gpt-6-astra",
    input=[
        {"role": "system", "content": "Extract entities from the input text"},
        {
            "role": "user",
            "content": "The quick brown fox jumps over the lazy dog with piercing blue eyes",
        },
    ],
    text_format=EntitiesModel,
) as stream:
    for event in stream:
        if event.type == "response.refusal.delta":
            print(event.delta, end="")
        elif event.type == "response.output_text.delta":
            print(event.delta, end="")
        elif event.type == "error":
            raise RuntimeError(event.message)
        elif event.type in ("response.failed", "response.incomplete"):
            response = event.response
            message = f"Response {response.status}"
            if response.error and response.error.message:
                message += f": {response.error.message}"
            elif response.incomplete_details and response.incomplete_details.reason:
                message += f": {response.incomplete_details.reason}"
            raise RuntimeError(message)
        elif event.type == "response.completed":
            print("Completed")  # print(event.response.output)

    final_response = stream.get_final_response()
    print(final_response)

支援的結構描述

結構化輸出支援 JSON Schema 語言的部分功能。

支援的型別

結構化輸出支援下列型別:

  • 字串
  • 數值
  • 布林值
  • 整數
  • 物件
  • 陣列
  • 列舉
  • anyOf

支援的屬性

除了指定屬性的型別,您也可以設定下列限制條件:

string 支援的屬性:

  • pattern — 字串必須符合的正規表示式。
  • format — 字串的預先定義格式。目前支援下列格式:
    • date-time
    • time
    • date
    • duration
    • email
    • hostname
    • ipv4
    • ipv6
    • uuid

number 支援的屬性:

  • multipleOf — 數值必須是此值的倍數。
  • maximum — 數值必須小於或等於此值。
  • exclusiveMaximum — 數值必須小於此值。
  • minimum — 數值必須大於或等於此值。
  • exclusiveMinimum — 數值必須大於此值。

array 支援的屬性:

  • minItems — 陣列的元素數量必須大於或等於此值。
  • maxItems — 陣列的元素數量必須小於或等於此值。

以下範例示範如何使用這些型別限制:

{
    "name": "user_data",
    "strict": true,
    "schema": {
        "type": "object",
        "properties": {
            "name": {
                "type": "string",
                "description": "The name of the user"
            },
            "username": {
                "type": "string",
                "description": "The username of the user. Must start with @",
                "pattern": "^@[a-zA-Z0-9_]+$"
            },
            "email": {
                "type": "string",
                "description": "The email of the user",
                "format": "email"
            }
        },
        "additionalProperties": false,
        "required": [
            "name", "username", "email"
        ]
    }
}

根層級必須是物件,且不得使用 anyOf

結構描述的根層級必須是物件,且不得使用 anyOf。以 Zod 為例,在根層級使用可辨識聯集會在最上層產生 anyOf,因此無法使用下列程式碼:

import { z } from "zod";
import { zodResponseFormat } from "openai/helpers/zod";

const BaseResponseSchema = z.object({
  status: z.literal("success"),
  data: z.string(),
});
const UnsuccessfulResponseSchema = z.object({
  status: z.literal("error"),
  error: z.string(),
});

const finalSchema = z.discriminatedUnion("status", [
  BaseResponseSchema,
  UnsuccessfulResponseSchema,
]);

// Invalid JSON Schema for Structured Outputs
const json = zodResponseFormat(finalSchema, "final_schema");

所有欄位都必須標示為 required

若要使用結構化輸出,必須將所有欄位或函式參數標示為 required。

{
    "name": "get_weather",
    "description": "Fetches the weather in the given location",
    "strict": true,
    "parameters": {
        "type": "object",
        "properties": {
            "location": {
                "type": "string",
                "description": "The location to get the weather for"
            },
            "unit": {
                "type": "string",
                "description": "The unit to return the temperature in",
                "enum": ["F", "C"]
            }
        },
        "additionalProperties": false,
        "required": ["location", "unit"]
    }
}

所有欄位都必填,模型也會為每個參數傳回一個值。若要模擬選用參數,您可以使用包含 null 的聯集型別。

{
    "name": "get_weather",
    "description": "Fetches the weather in the given location",
    "strict": true,
    "parameters": {
        "type": "object",
        "properties": {
            "location": {
                "type": "string",
                "description": "The location to get the weather for"
            },
            "unit": {
                "type": ["string", "null"],
                "description": "The unit to return the temperature in",
                "enum": ["F", "C"]
            }
        },
        "additionalProperties": false,
        "required": [
            "location", "unit"
        ]
    }
}

物件的巢狀深度與大小限制

一個結構描述中的物件屬性總數最多為 5,000 個,巢狀深度最多為 10 層。

字串總長度限制

在一個結構描述中,所有屬性名稱、定義名稱、列舉值和 const 值的字串長度合計不得超過 120,000 個字元。

列舉大小限制

一個結構描述中的所有列舉屬性合計最多可有 1,000 個列舉值。

若單一列舉屬性的值為字串,且列舉值超過 250 個,則該屬性所有列舉值的字串總長度不得超過 15,000 個字元。

每個物件都必須設定 additionalProperties: false

additionalProperties 決定物件能否包含 JSON 結構描述中未定義的額外鍵值對。

結構化輸出只支援產生已指定的鍵值對,因此開發人員必須設定 additionalProperties: false 才能啟用結構化輸出。

{
    "name": "get_weather",
    "description": "Fetches the weather in the given location",
    "strict": true,
    "schema": {
        "type": "object",
        "properties": {
            "location": {
                "type": "string",
                "description": "The location to get the weather for"
            },
            "unit": {
                "type": "string",
                "description": "The unit to return the temperature in",
                "enum": ["F", "C"]
            }
        },
        "additionalProperties": false,
        "required": [
            "location", "unit"
        ]
    }
}

鍵的順序

使用結構化輸出時,輸出中的鍵會依照結構描述中各鍵的順序排列。

尚未支援的型別專用關鍵字

  • 組合: allOf、not、dependentRequired、dependentSchemas、if、then、else

微調模型也不支援下列關鍵字:

  • 字串: minLength、maxLength、pattern、format
  • 數值: minimum、maximum、multipleOf
  • 物件: patternProperties
  • 陣列: minItems、maxItems

如果您設定 strict: true 以啟用結構化輸出,並在呼叫 API 時提供不受支援的 JSON 結構描述,API 就會傳回錯誤。

anyOf 中的每個巢狀結構描述都必須是符合此子集規範的有效 JSON 結構描述

以下是受支援的 anyOf 結構描述範例:

{
    "type": "object",
    "properties": {
        "item": {
            "anyOf": [
                {
                    "type": "object",
                    "description": "The user object to insert into the database",
                    "properties": {
                        "name": {
                            "type": "string",
                            "description": "The name of the user"
                        },
                        "age": {
                            "type": "number",
                            "description": "The age of the user"
                        }
                    },
                    "additionalProperties": false,
                    "required": [
                        "name",
                        "age"
                    ]
                },
                {
                    "type": "object",
                    "description": "The address object to insert into the database",
                    "properties": {
                        "number": {
                            "type": "string",
                            "description": "The number of the address. Eg. for 123 main st, this would be 123"
                        },
                        "street": {
                            "type": "string",
                            "description": "The street name. Eg. for 123 main st, this would be main st"
                        },
                        "city": {
                            "type": "string",
                            "description": "The city of the address"
                        }
                    },
                    "additionalProperties": false,
                    "required": [
                        "number",
                        "street",
                        "city"
                    ]
                }
            ]
        }
    },
    "additionalProperties": false,
    "required": [
        "item"
    ]
}

支援定義

您可以透過定義建立子結構描述,並在結構描述的各處參照這些子結構描述。以下是一個簡單的範例:

{
    "type": "object",
    "properties": {
        "steps": {
            "type": "array",
            "items": {
                "$ref": "#/$defs/step"
            }
        },
        "final_answer": {
            "type": "string"
        }
    },
    "$defs": {
        "step": {
            "type": "object",
            "properties": {
                "explanation": {
                    "type": "string"
                },
                "output": {
                    "type": "string"
                }
            },
            "required": [
                "explanation",
                "output"
            ],
            "additionalProperties": false
        }
    },
    "required": [
        "steps",
        "final_answer"
    ],
    "additionalProperties": false
}

支援遞迴結構描述

以下遞迴結構描述使用 # 參照根層級,以實現遞迴:

{
    "name": "ui",
    "description": "Dynamically generated UI",
    "strict": true,
    "schema": {
        "type": "object",
        "properties": {
            "type": {
                "type": "string",
                "description": "The type of the UI component",
                "enum": ["div", "button", "header", "section", "field", "form"]
            },
            "label": {
                "type": "string",
                "description": "The label of the UI component, used for buttons or form fields"
            },
            "children": {
                "type": "array",
                "description": "Nested UI components",
                "items": {
                    "$ref": "#"
                }
            },
            "attributes": {
                "type": "array",
                "description": "Arbitrary attributes for the UI component, suitable for any element",
                "items": {
                    "type": "object",
                    "properties": {
                        "name": {
                            "type": "string",
                            "description": "The name of the attribute, for example onClick or className"
                        },
                        "value": {
                            "type": "string",
                            "description": "The value of the attribute"
                        }
                    },
                    "additionalProperties": false,
                    "required": ["name", "value"]
                }
            }
        },
        "required": ["type", "label", "children", "attributes"],
        "additionalProperties": false
    }
}

以下是使用明確遞迴參照的結構描述範例:

{
    "type": "object",
    "properties": {
        "linked_list": {
            "$ref": "#/$defs/linked_list_node"
        }
    },
    "$defs": {
        "linked_list_node": {
            "type": "object",
            "properties": {
                "value": {
                    "type": "number"
                },
                "next": {
                    "anyOf": [
                        {
                            "$ref": "#/$defs/linked_list_node"
                        },
                        {
                            "type": "null"
                        }
                    ]
                }
            },
            "additionalProperties": false,
            "required": [
                "next",
                "value"
            ]
        }
    },
    "additionalProperties": false,
    "required": [
        "linked_list"
    ]
}

JSON 模式

JSON 模式是結構化輸出功能的基本版本。JSON 模式能確保模型輸出有效的 JSON,而結構化輸出還能確保模型輸出符合你指定的結構描述。如果你的使用情境支援結構化輸出,建議使用這項功能。

啟用 JSON 模式後,模型輸出可保證是有效的 JSON,但仍有少數例外情況,應用程式應偵測並妥善處理。

若要在 Responses API 中啟用 JSON 模式,可以將 text.format 設為 { "type": "json_object" }。使用函式呼叫時,JSON 模式一律會啟用。

重要注意事項:

  • 使用 JSON 模式時,務必在對話中的至少一則訊息(例如系統訊息)中,明確要求模型產生 JSON。如果沒有這項明確指示,模型可能會持續輸出空白字元,導致請求持續執行,直到達到 Token 上限。為避免遺漏這項指示,如果上下文中沒有出現「JSON」字串,API 就會擲出錯誤。
  • JSON 模式只能確保輸出是有效的 JSON,可以順利解析,無法保證輸出符合特定的結構描述。若要確保輸出符合指定的結構描述,請使用結構化輸出。如果無法使用這項功能,請使用驗證程式庫,並視需要重試,確保輸出符合預期的結構描述。
  • 應用程式必須偵測並處理可能導致模型輸出不完整 JSON 物件的例外情況(詳見下文)。

資源

若想進一步瞭解結構化輸出,建議參閱下列資源: