Was this page helpful?
結構化輸出限制 Claude 的回應遵循特定的結構描述(schema),確保輸出有效、可解析,以供下游處理使用。有兩個互補的功能可用:
output_config.format):以特定 JSON 格式取得 Claude 的回應strict: true):保證工具名稱和輸入的結構描述驗證output_format 參數已移至 output_config.format。舊的 output_format 參數暫時仍可使用,但已被棄用,將在未來的 API 版本中移除。請更新您的程式碼以使用 output_config: {format: {...}}。
這些功能可以在同一個請求中獨立使用或一起使用。
結構化輸出已在 Claude API 和 Amazon Bedrock 上正式發布,支援 Claude Opus 4.6、Claude Sonnet 4.5、Claude Opus 4.5 和 Claude Haiku 4.5。結構化輸出在 Microsoft Foundry 上仍處於公開測試階段。
從測試版遷移? output_format 參數已移至 output_config.format,且不再需要測試版標頭。舊的測試版標頭(structured-outputs-2025-11-13)和 output_format 參數將在過渡期間繼續運作。請參閱下方的程式碼範例以了解更新後的 API 格式。
沒有結構化輸出,Claude 可能會生成格式錯誤的 JSON 回應或無效的工具輸入,導致您的應用程式崩潰。即使經過仔細的提示設計,您仍可能遇到:
結構化輸出透過受限解碼保證符合結構描述的回應:
JSON.parse() 錯誤JSON 輸出控制 Claude 的回應格式,確保 Claude 返回符合您結構描述的有效 JSON。當您需要以下功能時,請使用 JSON 輸出:
回應格式: 在 response.content[0].text 中返回符合您結構描述的有效 JSON
{
"name": "John Smith",
"email": "[email protected]",
"plan_interest": "Enterprise",
"demo_requested": true
}定義您的 JSON 結構描述
建立一個 JSON 結構描述,描述您希望 Claude 遵循的結構。該結構描述使用標準 JSON Schema 格式,但有一些限制(請參閱 JSON Schema 限制)。
新增 output_config.format 參數
在您的 API 請求中包含 output_config.format 參數,設定 type: "json_schema" 和您的結構描述定義。
解析回應
Claude 的回應將是符合您結構描述的有效 JSON,在 response.content[0].text 中返回。
Python 和 TypeScript SDK 提供了輔助工具,使 JSON 輸出的使用更加便捷,包括結構描述轉換、自動驗證以及與流行結構描述庫的整合。
SDK 輔助方法(如 .parse() 和 Pydantic/Zod 整合)仍接受 output_format 作為便利參數。SDK 會在內部處理轉換為 output_config.format。以下範例展示 SDK 輔助語法。
對於 Python 和 TypeScript 開發者,您可以使用熟悉的結構描述定義工具如 Pydantic 和 Zod,而不需要撰寫原始 JSON 結構描述。
Python:client.messages.parse()(推薦)
parse() 方法會自動轉換您的 Pydantic 模型、驗證回應,並返回 parsed_output 屬性。
Python:transform_schema() 輔助工具
當您需要在發送前手動轉換結構描述,或者想要修改 Pydantic 生成的結構描述時使用。與 client.messages.parse() 自動轉換提供的結構描述不同,這會給您轉換後的結構描述,以便您進一步自訂。
Python 和 TypeScript SDK 都會自動轉換包含不支援功能的結構描述:
minimum、maximum、minLength、maxLength)additionalProperties: false這意味著 Claude 接收的是簡化的結構描述,但您的程式碼仍透過驗證來強制執行所有約束。
範例: 帶有 minimum: 100 的 Pydantic 欄位在發送的結構描述中會變成普通整數,但描述會更新為「Must be at least 100」,且 SDK 會根據原始約束驗證回應。
嚴格工具使用驗證工具參數,確保 Claude 使用正確類型的引數呼叫您的函式。當您需要以下功能時,請使用嚴格工具使用:
建構可靠的代理系統需要保證結構描述的一致性。沒有嚴格模式,Claude 可能會返回不相容的類型("2" 而非 2)或缺少必要欄位,導致您的函式崩潰並產生執行時錯誤。
嚴格工具使用保證類型安全的參數:
例如,假設一個訂票系統需要 passengers: int。沒有嚴格模式,Claude 可能會提供 passengers: "two" 或 passengers: "2"。使用 strict: true,回應將始終包含 passengers: 2。
回應格式: 在 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 回應。這對於需要可靠工具呼叫和結構化最終輸出的代理工作流程非常有用。
結構化輸出使用帶有已編譯語法工件的受限取樣。這引入了一些需要注意的效能特性:
name 或 description 欄位不會使快取失效使用結構化輸出時,Claude 會自動接收一個額外的系統提示,說明預期的輸出格式。這意味著:
output_config.format 參數將使該對話線程的任何提示快取失效結構化輸出支援標準 JSON Schema,但有一些限制。JSON 輸出和嚴格工具使用共享這些限制。
Python 和 TypeScript SDK 可以自動轉換包含不支援功能的結構描述,方法是移除這些功能並將約束新增到欄位描述中。詳情請參閱 SDK 特定方法。
雖然結構化輸出在大多數情況下保證符合結構描述,但在某些情境下輸出可能不符合您的結構描述:
拒絕(stop_reason: "refusal")
即使使用結構化輸出,Claude 仍會維持其安全性和有用性特性。如果 Claude 因安全原因拒絕請求:
stop_reason: "refusal"達到 token 限制(stop_reason: "max_tokens")
如果回應因達到 max_tokens 限制而被截斷:
stop_reason: "max_tokens"max_tokens 值重試以獲取完整的結構化輸出如果您的結構描述使用不支援的功能或過於複雜,您將收到 400 錯誤:
「Too many recursive definitions in schema」
「Schema is too complex」
strict: true 的工具數量對於有效結構描述的持續問題,請聯繫支援並提供您的結構描述定義。
相容:
output_config.format)和嚴格工具使用(strict: true)不相容:
output_config.format,將返回 400 錯誤。語法範圍:語法僅適用於 Claude 的直接輸出,不適用於工具使用呼叫、工具結果或思考標籤(使用延伸思考時)。語法狀態在各區段之間重置,允許 Claude 自由思考,同時在最終回應中仍產生結構化輸出。
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
}
}
}
}'from pydantic import BaseModel
from anthropic import Anthropic, transform_schema
class ContactInfo(BaseModel):
name: str
email: str
plan_interest: str
demo_requested: bool
client = Anthropic()
# 使用 .create() - 需要 transform_schema()
response = client.messages.create(
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": transform_schema(ContactInfo),
}
}
)
print(response.content[0].text)
# 使用 .parse() - 可以直接傳入 Pydantic 模型
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)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 = 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 輸出:結構化回應格式
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
}
}
},
# 嚴格工具使用:保證工具參數
tools=[{
"name": "search_flights",
"strict": True,
"input_schema": {
"type": "object",
"properties": {
"destination": {"type": "string"},
"date": {"type": "string", "format": "date"}
},
"required": ["destination", "date"],
"additionalProperties": False
}
}]
)