本文根據 Claude 官方《Structured outputs》整理,資料核對於 2026-11-05。配圖為本站整理的示意圖,不是介面截圖。代碼裏的模型名取自官方當天示例,請以官方模型頁為準。本站(bigolab.com)不是 Anthropic 官方網站。API 是按用量計費的獨立服務,與 Claude 訂閱分開計算,Key 的獲取見 /guides/claude-api-key-console。
適用於誰
- 要把 Claude 的回答直接存進數據庫、餵給下游程序的開發者:抽取字段、分類、打標籤;
- 以前靠“請只輸出 JSON”加正則兜底,經常解析失敗的人;
- 在做工具調用,希望參數百分之百符合 schema 的人(工具基礎見 /guides/claude-tool-use-basics)。
結論先說
- 兩個功能:JSON 輸出(
output_config.format,類型json_schema)約束回答文字;嚴格工具調用(strict: true)約束工具名和參數。可以單用,也可以同時用。 - 舊的
output_format參數已棄用,改用output_config.format,現在不再需要 beta 請求頭。 - SDK 助手能省事:Python 用 Pydantic 加
messages.parse,TypeScript 用 Zod,結果直接是解析好的對象。 - 仍要處理兩種異常:
stop_reason為refusal(拒絕,輸出可能不符合 schema)和max_tokens(被截斷,JSON 可能不完整)。 - schema 只支持一個子集,用了不支持的特性會返回 400。

圖:本站根據 Claude 官方《Structured outputs》 整理的示意圖
一、直接寫 JSON schema
Python:
python
import json
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-5-5", # 以官方模型頁當天為準
max_tokens=1024,
messages=[
{
"role": "user",
"content": "提取資訊:張三([email protected])想要企業版並預約演示。",
}
],
output_config={
"format": {
"type": "json_schema",
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"email": {"type": "string"},
"plan_interest": {"type": "string"},
"demo_requested": {"type": "boolean"},
},
"required": ["name", "email", "plan_interest", "demo_requested"],
"additionalProperties": False,
},
}
},
)
text = next(b.text for b in response.content if b.type == "text")
data = json.loads(text)
print(data)
注意三點:
- 回答在
type為text的內容塊裏,是一段合法 JSON 字符串,自己json.loads; - 每個對象必須寫
additionalProperties: false; - 想要的字段都放進
required,下面講的屬性順序問題也會因此更好處理。
二、用 SDK 助手:Pydantic 與 Zod
寫類比寫 schema 更順手,SDK 會替你轉換:
python
from pydantic import BaseModel
import anthropic
client = anthropic.Anthropic()
class ContactInfo(BaseModel):
name: str
email: str
plan_interest: str
demo_requested: bool
response = client.messages.parse(
model="claude-opus-5-5",
max_tokens=1024,
messages=[{"role": "user", "content": "提取資訊:張三([email protected])想要企業版並預約演示。"}],
output_format=ContactInfo,
)
print(response.parsed_output)
注意:messages.parse 這個助手方法的參數仍叫 output_format,傳的是類;你直接調用 messages.create 時才用 output_config.format。官方還提醒,Python SDK 1.0 及之後,在 client.beta.messages.create() 裏傳舊的 output_format={...} 字典會拋 TypeError。
TypeScript 用 Zod:
typescript
import Anthropic from "@anthropic-ai/sdk";
import { z } from "zod";
import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";
const client = new Anthropic();
const ContactInfo = z.object({
name: z.string(),
email: z.string(),
plan_interest: z.string(),
demo_requested: z.boolean(),
});
const response = await client.messages.parse({
model: "claude-opus-5-5",
max_tokens: 1024,
messages: [{ role: "user", content: "提取資訊:張三([email protected])想要企業版並預約演示。" }],
output_config: { format: zodOutputFormat(ContactInfo) },
});
console.log(response.parsed_output);
不想用 Zod,可以用 @anthropic-ai/sdk/helpers/json-schema 的 jsonSchemaOutputFormat(),把 schema 聲明為 as const 還能得到類型推斷。
官方說明助手做的轉換:去掉不支持的約束(比如 minimum、maxLength)並把它們寫進字段說明裏;給所有對象補 additionalProperties: false;過濾字符串格式;如果助手帶校驗,會按原始約束在本地再檢查一次返回值。
三、schema 支持什麼、不支持什麼

圖:本站根據 Claude 官方《Structured outputs》 整理的示意圖
支持:object、array、string、integer、number、boolean、null;enum(只能是標量);const;anyOf、allOf(allOf 不能和 $ref 一起用);內部的 $ref、$defs、definitions;required;字符串的一批 format(如 date-time、date、email、uri、uuid 等);數組的 minItems,但只能是 0 或 1。
不支持:遞歸 schema;複雜類型的 enum;外部 $ref;minimum、maximum、multipleOf;minLength、maxLength;additionalProperties 取 false 以外的值。簡單的正則 pattern 可用,但後向引用、環視、\b 不行。用了不支持的特性會返回 400。
四、無效輸出的兩種情況
即使有 schema 約束,下面兩種情況的輸出也可能不是你想要的:
stop_reason: "refusal":Claude 出於安全原因拒絕。返回仍是 200,也照常計費,但輸出可能不符合 schema。官方還提醒:如果在 schema 裏要求“逐步推理”的字段,可能觸發reasoning_extraction類的拒絕,改成要“簡短解釋”更穩;stop_reason: "max_tokens":輸出被截斷,JSON 可能不完整,把max_tokens調大再試。
另外兩個官方提到的細節:枚舉值有時只有大小寫不同(例如返回 “Conversation Topic 3” 而不是 “Conversation topic 3”),比較時忽略大小寫,並避免設計只靠大小寫區分的枚舉;屬性順序是先必填、後可選,各自按 schema 順序,如果順序重要就都設為必填。
五、延遲、緩存與複雜度
- 第一次用一個新 schema 會有編譯延遲;編譯結果自最後一次使用起緩存 24 小時。改變 schema 結構(或和工具搭配時改變工具集合)會使緩存失效,只改工具的名稱或描述則不會;
- 系統會注入一段描述輸出格式的提示,多佔一些輸入 token;
- 更改
output_config.format會使該對話的提示詞緩存失效(緩存見 /guides/claude-prompt-caching); - 複雜度限制:每個請求最多 20 個嚴格工具;所有嚴格工具和 JSON schema 合計最多 24 個可選參數;最多 16 個聯合類型(
anyOf或類型數組)參數。超限會返回 400,資訊類似 “Schema is too complex for compilation”,編譯超時是 180 秒。降低複雜度的辦法:只給關鍵工具加 strict,參數盡量設為必填,把嵌套對象攤平,把任務拆成多次請求。
六、和別的功能的關係
- 官方 Errors 頁寫明,Claude 4.6 及之後的模型不支持預填助手消息,會返回 400,官方建議用結構化輸出、系統提示或
output_config.format代替; - 批處理可以和結構化輸出一起用,官方寫明仍享受批量折扣,批量寫法見 /guides/claude-api-message-batches;
- token 計數接口也支持,見 /guides/claude-api-count-tokens;
- 和流式、引用等其他功能能不能同時用,官方這一頁的兼容性清單我們沒讀到,請到官方頁面核對。
常見問題
Q:為什麼返回 400,說 schema 不支持?
對照第三節:多半是用了 minimum、maxLength、遞歸、外部 $ref,或對象缺了 additionalProperties: false。用 SDK 助手能自動處理一部分。
Q:JSON 還是解析失敗?
先看 stop_reason:是 max_tokens 就加大額度,是 refusal 就要處理拒絕的情況。
Q:計費有變化嗎?
官方這一頁沒有單獨列出結構化輸出的費用,但格式提示會增加輸入 token,價格以官方價格頁當天為準。
參考資料
- Claude 官方:Structured outputs — https://platform.claude.com/docs/en/build-with-claude/structured-outputs
- Claude 官方:Claude API errors — https://platform.claude.com/docs/en/api/errors
0 條評論
還沒有評論,來搶沙發~