結構化輸出將 Claude 的回應限制為遵循特定的結構描述,確保下游處理能獲得有效且可解析的輸出。提供兩種互補功能:
output_config.format):以特定 JSON 格式獲取 Claude 的回應strict: true):保證對工具名稱和輸入進行結構描述驗證這些功能可以獨立使用,也可以在同一請求中一起使用。
結構化輸出在 Claude API 和 Amazon Bedrock 上已正式推出,支援 Claude Opus 4.6、Claude Sonnet 4.6、Claude Sonnet 4.5、Claude Opus 4.5 和 Claude Haiku 4.5。結構化輸出在 Microsoft Foundry 上仍處於公開測試版階段。
This feature qualifies for Zero Data Retention (ZDR) with limited technical retention. See the Data retention section for details on what is retained and why.
從測試版遷移? output_format 參數已移至 output_config.format,且不再需要測試版標頭。舊的測試版標頭(structured-outputs-2025-11-13)和 output_format 參數將在過渡期間繼續運作。請參閱下方的程式碼範例以了解更新後的 API 結構。
若不使用結構化輸出,Claude 可能會產生格式錯誤的 JSON 回應或無效的工具輸入,從而破壞您的應用程式。即使經過仔細的提示設計,您仍可能遇到:
結構化輸出透過受限解碼保證符合結構描述的回應:
JSON.parse() 錯誤JSON 輸出控制 Claude 的回應格式,確保 Claude 返回符合您結構描述的有效 JSON。在以下情況下使用 JSON 輸出:
curl https://api.anthropic.com/v1/messages \
-H "content-type: application/json" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "claude-opus-4-6",
"max_tokens": 1024,
"messages": [
{
"role": "user",
"content": "Extract the key information from this email: John Smith ([email protected]) is interested in our Enterprise plan and wants to schedule a demo for next Tuesday at 2pm."
}
],
"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
}
}
}
}'回應格式: 在 response.content[0].text 中返回符合您結構描述的有效 JSON
{
"name": "John Smith",
"email": "[email protected]",
"plan_interest": "Enterprise",
"demo_requested": true
}定義您的 JSON 結構描述
建立一個描述您希望 Claude 遵循的結構的 JSON 結構描述。該結構描述使用標準 JSON Schema 格式,但有一些限制(請參閱 JSON Schema 限制)。
新增 output_config.format 參數
在您的 API 請求中包含 output_config.format 參數,設定 type: "json_schema" 及您的結構描述定義。
解析回應
Claude 的回應將是符合您結構描述的有效 JSON,在 response.content[0].text 中返回。
SDK 提供了輔助工具,使處理 JSON 輸出更加容易,包括結構描述轉換、自動驗證以及與常用結構描述庫的整合。
SDK 輔助方法(如 .parse() 和 Pydantic/Zod 整合)仍接受 output_format 作為便利參數。SDK 在內部處理轉換至 output_config.format 的工作。以下範例展示 SDK 輔助語法。
您可以使用語言中熟悉的結構描述定義工具,而不必撰寫原始 JSON 結構描述:
client.messages.parse() 的 Pydantic 模型zodOutputFormat() 的 Zod 結構描述outputFormat(Class<T>) 自動推導結構描述的純 Java 類別output_config: {format: Model} 的 Anthropic::BaseModel 類別output_config 傳遞的原始 JSON 結構描述from pydantic import BaseModel
from anthropic import Anthropic
class ContactInfo(BaseModel):
name: str
email: str
plan_interest: str
demo_requested: bool
client = Anthropic()
response = client.messages.parse(
model="claude-opus-4-6",
max_tokens=1024,
messages=[
{
"role": "user",
"content": "Extract the key information from this email: John Smith ([email protected]) is interested in our Enterprise plan and wants to schedule a demo for next Tuesday at 2pm.",
}
],
output_format=ContactInfo,
)
print(response.parsed_output)每個 SDK 都提供輔助工具,使處理結構化輸出更加容易。請參閱各個 SDK 頁面以了解完整詳情。
Python 和 TypeScript SDK 會自動轉換具有不支援功能的結構描述:
minimum、maximum、minLength、maxLength)additionalProperties: false這意味著 Claude 接收到簡化的結構描述,但您的程式碼仍透過驗證強制執行所有約束。
範例: 帶有 minimum: 100 的 Pydantic 欄位在發送的結構描述中變為純整數,但描述會更新為「必須至少為 100」,且 SDK 會根據原始約束驗證回應。
嚴格工具使用會驗證工具參數,確保 Claude 以正確類型的引數呼叫您的函數。在以下情況下使用嚴格工具使用:
建構可靠的代理系統需要保證結構描述符合性。沒有嚴格模式,Claude 可能返回不相容的類型("2" 而非 2)或缺少必填欄位,導致您的函數中斷並引發執行時錯誤。
嚴格工具使用保證類型安全的參數:
例如,假設訂票系統需要 passengers: int。沒有嚴格模式,Claude 可能提供 passengers: "two" 或 passengers: "2"。使用 strict: true,回應將始終包含 passengers: 2。
curl https://api.anthropic.com/v1/messages \
-H "content-type: application/json" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "claude-opus-4-6",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": "What is the weather in San Francisco?"}
],
"tools": [{
"name": "get_weather",
"description": "Get the current weather in a given location",
"strict": true,
"input_schema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"]
}
},
"required": ["location"],
"additionalProperties": false
}
}]
}'回應格式: 在 response.content[x].input 中帶有已驗證輸入的工具使用區塊
{
"type": "tool_use",
"name": "get_weather",
"input": {
"location": "San Francisco, CA"
}
}保證:
input 嚴格遵循 input_schemaname 始終有效(來自提供的工具或伺服器工具)定義您的工具結構描述
為您工具的 input_schema 建立 JSON 結構描述。結構描述使用標準 JSON Schema 格式,但有一些限制(請參閱 JSON Schema 限制)。
添加 strict: true
在您的工具定義中將 "strict": true 設定為頂層屬性,與 name、description 和 input_schema 並列。
處理工具呼叫
當 Claude 使用工具時,tool_use 區塊中的 input 欄位將嚴格遵循您的 input_schema,且 name 將始終有效。
JSON 輸出和嚴格工具使用解決不同的問題,可以一起使用:
結合使用時,Claude 可以使用保證有效的參數呼叫工具,並返回結構化的 JSON 回應。這對於需要可靠工具呼叫和結構化最終輸出的代理工作流程非常有用。
response = client.messages.create(
model="claude-opus-4-6",
max_tokens=1024,
messages=[
{"role": "user", "content": "Help me plan a trip to Paris for next month"}
],
# JSON outputs: structured response format
output_config={
"format": {
"type": "json_schema",
"schema": {
"type": "object",
"properties": {
"summary": {"type": "string"},
"next_steps": {"type": "array", "items": {"type": "string"}},
},
"required": ["summary", "next_steps"],
"additionalProperties": False,
},
}
},
# Strict tool use: guaranteed tool parameters
tools=[
{
"name": "search_flights",
"strict": True,
"input_schema": {
"type": "object",
"properties": {
"destination": {"type": "string"},
"date": {"type": "string", "format": "date"},
},
"required": ["destination", "date"],
"additionalProperties": False,
},
}
],
)結構化輸出使用帶有已編譯語法構件的受限採樣。這引入了一些需要注意的效能特性:
name 或 description 欄位不會使快取失效使用結構化輸出時,Claude 會自動收到一個額外的系統提示詞,說明預期的輸出格式。這意味著:
output_config.format 參數將使該對話執行緒的任何提示詞快取失效結構化輸出支援標準 JSON Schema,但有一些限制。JSON 輸出和嚴格工具使用共享這些限制。
Python 和 TypeScript SDK 可以透過移除不支援的功能並在欄位描述中添加約束,自動轉換包含不支援功能的結構描述。詳情請參閱 SDK 特定方法。
使用結構化輸出時,物件中的屬性會維持您結構描述中定義的順序,但有一個重要注意事項:必要屬性排在前面,可選屬性排在後面。
例如,給定此結構描述:
{
"type": "object",
"properties": {
"notes": { "type": "string" },
"name": { "type": "string" },
"email": { "type": "string" },
"age": { "type": "integer" }
},
"required": ["name", "email"],
"additionalProperties": false
}輸出將按以下順序排列屬性:
name(必要,按結構描述順序)email(必要,按結構描述順序)notes(可選,按結構描述順序)age(可選,按結構描述順序)這意味著輸出可能如下所示:
{
"name": "John Smith",
"email": "[email protected]",
"notes": "Interested in enterprise plan",
"age": 35
}如果輸出中的屬性順序對您的應用程式很重要,請確保所有屬性都標記為必要,或在您的解析邏輯中考慮此重新排序。
雖然結構化輸出在大多數情況下保證符合結構描述,但在某些情況下輸出可能與您的結構描述不符:
拒絕(stop_reason: "refusal")
Claude 即使在使用結構化輸出時也會維持其安全性和有用性。如果 Claude 出於安全原因拒絕請求:
stop_reason: "refusal"達到 Token 限制(stop_reason: "max_tokens")
如果回應因達到 max_tokens 限制而被截斷:
stop_reason: "max_tokens"max_tokens 值重試以獲取完整的結構化輸出結構化輸出透過將您的 JSON 結構描述編譯成限制 Claude 輸出的語法來運作。更複雜的結構描述會產生更大的語法,需要更長的編譯時間。為了防止過長的編譯時間,API 強制執行幾個複雜度限制。
以下限制適用於所有帶有 output_config.format 或 strict: true 的請求:
| 限制 | 值 | 描述 |
|---|---|---|
| 每個請求的嚴格工具數 | 20 | 帶有 strict: true 的工具最大數量。非嚴格工具不計入此限制。 |
| 可選參數 | 24 | 所有嚴格工具結構描述和 JSON 輸出結構描述中的可選參數總數。每個未列在 required 中的參數都計入此限制。 |
| 具有聯合類型的參數 | 16 | 在所有嚴格結構描述中使用 anyOf 或類型陣列(例如 "type": ["string", "null"])的參數總數。這些特別昂貴,因為它們會產生指數級的編譯成本。 |
這些限制適用於單個請求中所有嚴格結構描述的合計總數。例如,如果您有 4 個嚴格工具,每個有 6 個可選參數,即使沒有單個工具看起來很複雜,您也會達到 24 個參數的限制。
除了上述明確限制之外,還有對已編譯語法大小的額外內部限制。這些限制的存在是因為結構描述複雜度無法簡化為單一維度:可選參數、聯合類型、巢狀物件和工具數量等功能以可能使已編譯語法不成比例地增大的方式相互作用。
當超過這些限制時,您將收到帶有訊息「Schema is too complex for compilation」的 400 錯誤。這些錯誤意味著您的結構描述的組合複雜度超過了可以有效編譯的範圍,即使上述每個單獨的限制都已滿足。作為最後的保護措施,API 還強制執行 180 秒的編譯超時。通過所有明確檢查但產生非常大的已編譯語法的結構描述可能會達到此超時。
如果您遇到複雜度限制,請按順序嘗試以下策略:
僅將關鍵工具標記為嚴格。 如果您有許多工具,請將其保留給結構描述違規會造成真正問題的工具,並依賴 Claude 對較簡單工具的自然遵從。
減少可選參數。 盡可能將參數設為 required。每個可選參數大約使語法狀態空間的一部分翻倍。如果參數始終有合理的預設值,請考慮將其設為必要,並讓 Claude 明確提供該預設值。
簡化巢狀結構。 具有可選欄位的深度巢狀物件會加劇複雜度。盡可能扁平化結構。
拆分為多個請求。 如果您有許多嚴格工具,請考慮將它們拆分到不同的請求或子代理中。
對於有效結構描述的持續問題,請聯繫支援並提供您的結構描述定義。
使用結構化輸出時,提示詞和回應會透過 ZDR 處理。但是,JSON 結構描述本身會暫時快取最多 24 小時(從最後一次使用起)以用於最佳化目的。API 回應之後不會保留任何提示詞或回應資料。
有關所有功能的 ZDR 資格,請參閱 API 和資料保留。
可搭配使用:
output_config.format)和嚴格工具使用(strict: true)不相容:
output_config.format 中啟用引用,則返回 400 錯誤。語法範圍:語法僅適用於 Claude 的直接輸出,不適用於工具使用呼叫、工具結果或思考標籤(使用延伸思考時)。語法狀態在各節之間重置,允許 Claude 自由思考,同時在最終回應中仍然產生結構化輸出。
Was this page helpful?