跳至主要內容
AISeeker

搜尋

搜尋報導、主題、公司…

CH.05教學
閱讀時間 3 分鐘
訊號強度: 3/5重要
已查證 · 4 資料來源

結構化輸出與工具呼叫的正確做法:schema、嚴格模式與失敗處理

Claude 與 OpenAI 都已內建 schema 約束解碼。真正會出問題的是 schema 設計、拒答、截斷與工具迴圈的管理。

關鍵數字

20
Claude 單次請求嚴格工具上限
24
嚴格 schema 選填參數總上限
24h
編譯後文法快取時間

拜託模型「只能回傳 JSON」的時代已經過去。Anthropic 與 OpenAI 都提供文法約束解碼:給 API 一份 JSON Schema,輸出就保證符合,只有少數例外。困難點因此從解析轉移到設計。本教學示範兩家 API 目前的請求格式、一套兩邊都適用的 schema 寫法,以及仍需自行處理的失敗情況。範例使用 Python 搭配 anthropic 與 openai SDK;請求格式依照兩家目前的官方文件。

1. 選對機制

需求Claude(Messages API)OpenAI(Responses API)
固定格式的最終答案output_config.format 或 messages.parse(output_format=Model)text.format 搭配 json_schema,或 responses.parse(text_format=Model)
模型以有效參數呼叫你的函式加上 strict: true 的工具加上 strict: true 的 function 工具
每回合都必須呼叫工具在提示詞中要求並檢查;在 Opus 5.5 與 Sonnet 5.5 上強制 tool_choice 會回傳 400tool_choice: "required" 或指定函式

經驗法則:擷取、分類與產生報告適合 JSON 輸出;有副作用或多步驟的工作適合工具。兩者也能並用:Claude 允許在同一個請求中同時使用 JSON 輸出與嚴格工具。

2. 用同一個 Pydantic 模型在兩家做擷取

schema 只定義一次。所有欄位都是必填;可能缺值的欄位設為可為 null,而不是選填。這樣既符合 OpenAI 的嚴格模式,也不會占用 Claude 的選填參數額度。

python
from typing import Literal
from pydantic import BaseModel

class LineItem(BaseModel):
    description: str
    quantity: int
    unit_price_cents: int

class Invoice(BaseModel):
    vendor: str
    invoice_date: str                      # ISO 8601, e.g. "2026-10-02"
    currency: Literal["USD", "EUR", "JPY", "TWD"]
    items: list[LineItem]
    po_number: str | None                  # required key, may be null

Claude:

python
import anthropic

claude = anthropic.Anthropic()
resp = claude.messages.parse(
    model="claude-opus-5-5",
    max_tokens=16000,
    messages=[{"role": "user", "content": f"Extract this invoice:\n\n{text}"}],
    output_format=Invoice,
)
if resp.stop_reason in ("refusal", "max_tokens"):
    raise RuntimeError(f"no usable output: {resp.stop_reason}")
invoice = resp.parsed_output

OpenAI:

python
from openai import OpenAI

oai = OpenAI()
resp = oai.responses.parse(
    model=OPENAI_MODEL,
    input=[{"role": "user", "content": f"Extract this invoice:\n\n{text}"}],
    text_format=Invoice,
)
if resp.status == "incomplete":
    raise RuntimeError(f"truncated: {resp.incomplete_details.reason}")
invoice = resp.output_parsed   # None if the model refused

Anthropic SDK 會把模型轉成 output_config.format 並驗證回覆;OpenAI 的輔助函式則送出 type: "json_schema"、strict: true 的 text.format。不用輔助函式時,就自行送出原始 schema,再用 json.loads 解析文字區塊。

3. 嚴格工具與正確的工具迴圈

在 Claude 上,strict: true 與 name、input_schema 並列,且 schema 必須設定 additionalProperties: false:

json
{
  "name": "refund_order",
  "description": "Issue a refund for an order. Only call after confirming the order ID with the user.",
  "strict": true,
  "input_schema": {
    "type": "object",
    "properties": {
      "order_id": { "type": "string" },
      "amount_cents": { "type": "integer" },
      "reason": { "type": "string", "enum": ["damaged", "late", "other"] }
    },
    "required": ["order_id", "amount_cents", "reason"],
    "additionalProperties": false
  }
}

嚴格模式保證工具名稱存在、參數型別正確。但外圍的迴圈仍是你的責任:

  • 不保證一定會呼叫。 使用 auto 時,先確認收到 tool_use 區塊(Claude)或 function_call 項目(OpenAI),再往下處理。
  • 每個結果都要回傳。 在 Claude 上,同一回合的所有 tool_result 區塊要放在同一則 user 訊息中送回,失敗的用 is_error: true 標示,而不是直接丟掉。在 OpenAI 上,附加一個帶有對應 call_id 的 function_call_output 項目。
  • 要解析,不要比對字串。 OpenAI 以 JSON 字串回傳 arguments;Claude 不同模型的跳脫字元可能不同。請一律使用 JSON 解析器。
  • 把副作用關起來。 格式完全正確的 refund_order 呼叫,仍可能是錯誤的呼叫。確認步驟與金額上限要寫在程式裡,而不只是寫在描述中。

4. 設計解碼器處理得了的 schema

Claude 會把 schema 編譯成文法,因此有些限制要知道:

  • 不支援的功能: 遞迴 schema、oneOf(請改用 anyOf)、數值的 minimum/maximum、字串的 minLength/maxLength。SDK 輔助函式會把這些限制移到欄位描述中,並在本地重新檢查。
  • 每個請求的複雜度上限: 嚴格工具 20 個、選填參數 24 個、聯集型別參數 16 個,以所有嚴格 schema 合計。
  • 不能用任意鍵的字典。 因為 additionalProperties 必須為 false,dict 欄位只能回傳 {}。請改用由 key/value 物件組成的陣列。
  • 順序: 必填屬性先輸出,接著才是選填屬性。
  • 首次呼叫延遲: 新 schema 第一次使用時需要編譯;編譯後的文法自最後一次使用起快取 24 小時。

在 OpenAI 上,Responses API 會嘗試把函式 schema 正規化為嚴格模式,若做不到就悄悄退回非嚴格模式;除錯時請檢查回應中工具的 strict 旗標。

常見陷阱與下一步

  • 拒答與截斷會打破保證。 拒答或因 max_tokens 截斷時,輸出可能不符合 schema。務必先檢查停止原因或狀態。
  • 不要要求「推理過程」欄位。 在 Claude 上,要求逐步思考內容的屬性可能觸發 reasoning_extraction 拒答;改成要求一句話的理由即可。
  • enum 大小寫不保證。 Claude 可能改變多字 enum 值的大小寫;比較時請不分大小寫。
  • 在 Claude 上,引用功能不能與 JSON 輸出並用; API 會拒絕這種組合。
  • 有效不代表正確。 schema 無法判斷明細加總是否等於發票總額。請加上業務規則檢查與評測資料集。

先把一個脆弱的「請回傳 JSON」提示詞改成 Pydantic 模型,加上停止原因檢查,然後記錄一週內所有驗證失敗。這份紀錄會告訴你哪些欄位需要重新設計。

本文在編輯審閱下,以 AI 輔助進行研究與撰寫。如發現錯誤,請來信 support@aiseeker.dev。

資料來源

本報導綜合以下來源撰寫,並標示一手來源。

  1. [1]
    Structured outputs

    Anthropic (Claude Platform Docs)2026.11.28一手來源

  2. [2]
    Strict tool use

    Anthropic (Claude Platform Docs)2026.11.28一手來源

  3. [3]
    Structured model outputs

    OpenAI API Docs2026.11.28一手來源

  4. [4]
    Function calling

    OpenAI API Docs2026.11.28一手來源

返回教學 →