Structured Output
讓模型回傳便於程式解析和驗證的結構化資料。
Structured Output 用於讓模型按預期的資料結構回傳結果,便於程式擷取欄位、寫入資料庫或進入後續工作流。典型情境包括工單分類、表單擷取、內容審核結果和固定結構的分析報告。
Structured Output 和 Tool Calling 解決不同問題
如果你需要模型回傳一份結構化回答,使用 Structured Output;如果你需要模型選擇並請求應用執行某個函式,使用 Tool Calling。工具參數也可以由 Schema 約束,但它屬於工具呼叫循環。
先選擇合適的輸出方式
| 方式 | 能解決什麼問題 | 用戶端還要做什麼 |
|---|---|---|
| 在提示詞中要求 JSON | 為不支援專用欄位的模型提供基礎約束 | 擷取 JSON、解析、驗證並在失敗時重試 |
| JSON Object | 要求模型輸出合法 JSON 物件 | 驗證欄位、類型和業務規則 |
| JSON Schema | 在請求中提供目標結構 | 處理模型支援範圍、拒絕、截斷和驗證失敗 |
是否支援 JSON Object、JSON Schema 或嚴格遵循取決於目前模型和協議。不要僅因為請求回傳 200 就認定指定 Schema 已經生效。
定義一個小而明確的 Schema
下面的結構用於把客戶問題分類為工單:
{
"type": "object",
"properties": {
"category": {
"type": "string",
"enum": ["billing", "technical", "account"]
},
"priority": {
"type": "integer",
"minimum": 1,
"maximum": 3
},
"summary": {
"type": "string"
}
},
"required": ["category", "priority", "summary"],
"additionalProperties": false
}欄位名應穩定且易懂,枚舉值應與業務程式碼一致。避免一開始就使用過深巢狀、過多可選分支或難以解釋的正則約束。
使用 Chat Completions 回傳結構化結果
curl 'https://api.agtcloud.cn/v1/chat/completions' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer your-api-key' \
--data '{
"model": "MODEL_ID",
"messages": [
{
"role": "user",
"content": "我的 API Key 無法使用,請幫我分類。"
}
],
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "support_ticket",
"strict": true,
"schema": {
"type": "object",
"properties": {
"category": {
"type": "string",
"enum": ["billing", "technical", "account"]
},
"priority": {
"type": "integer",
"minimum": 1,
"maximum": 3
},
"summary": {"type": "string"}
},
"required": ["category", "priority", "summary"],
"additionalProperties": false
}
}
}
}'strict 是目標格式的一部分,但是否可用仍由模型決定。完整欄位見 Chat Completions Reference。
不同協議的欄位位置
Chat 在 response_format 中選擇 json_object 或 json_schema。使用 JSON Schema 時,Schema 位於 response_format.json_schema.schema。
{
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "support_ticket",
"schema": {"type": "object"}
}
}
}這些結構不能直接複製到另一種協議中。使用前分別檢視 Responses Reference 和 Gemini Generate Content Reference。
解析後仍要驗證
type SupportTicket = {
category: 'billing' | 'technical' | 'account';
priority: number;
summary: string;
};
function parseTicket(raw: string): SupportTicket {
const value: unknown = JSON.parse(raw);
if (
typeof value !== 'object' ||
value === null ||
!('category' in value) ||
!('priority' in value) ||
!('summary' in value)
) {
throw new Error('結構化結果缺少必要欄位');
}
return value as SupportTicket;
}上例只演示最小檢查。正式專案應使用與業務資料模型一致的 Schema 驗證器,並檢查枚舉、長度、數值範圍和跨欄位規則。
處理不完整和無效結果
| 現象 | 處理方式 |
|---|---|
| 回傳一般文字 | 確認模型支援目標格式,檢查欄位位置和請求是否被 SDK 改寫 |
| JSON 無法解析 | 儲存去識別化回應和停止原因,按業務策略在有限次數內重試 |
| 缺少必要欄位 | 視為驗證失敗,不用預設值靜默掩蓋關鍵資料缺失 |
| 輸出被截斷 | 調整輸出預算或簡化 Schema,不串接猜測缺失 JSON |
| 模型拒絕回答 | 單獨處理拒絕,不把拒絕文字當作業務物件 |
| Schema 能解析但業務無效 | 使用業務驗證回傳明確錯誤或進入人工處理 |
上線前檢查
- Schema 與應用中的類型定義由同一來源生成或保持同步。
- 模型切換前重新確認協議、Schema 子集和嚴格模式支援。
- 解析失敗、拒絕、截斷和空輸出都有獨立分支。
- 結構化結果在寫入資料庫或觸發業務動作前再次驗證。
- 記錄只儲存完成疑難排解所需的去識別化資訊。