Amazon Bedrock 為 Anthropic Claude 模型新增結構化輸出支援
Structured outputs for Anthropic Claude models on Amazon Bedrock
Amazon Bedrock 現已在 bedrock-runtime 和 bedrock-mantle 端點,為服務可用的所有 Anthropic Claude 模型提供結構化輸出。
文章交代受限解碼、strict tool use 與文法快取的運作方式,並列出生成時不會強制執行的 schema 條件,有助掌握整合方法及驗證邊界。
Amazon Bedrock 現已在 bedrock-runtime 和 bedrock-mantle 端點上,支援所有 Anthropic Claude 模型的結構化輸出(適用於模型可用的情況)。
無論你透過 Boto3 和 bedrock-runtime API,還是透過 Messages API 和 bedrock-mantle 端點呼叫 Claude,現在都可以收到符合指定結構的 JSON 回應,並符合結構描述。你不再需要自訂解析、重試邏輯或事後處理。
實際應用
透過 Amazon Bedrock 上 Claude 的結構化輸出,你可以在各行各業自動執行可靠且符合結構描述的工作。例如,從財務業績報告和合規文件中提取所有必填欄位、將臨牀紀錄解析為電子健康紀錄 (EHR),以及以一致且經驗證的結果擴充產品目錄。你亦可以分析合約中的關鍵條款、當事方和責任,或為智能支援工單分流提供動力,確保意圖、情感和實體始終符合應用程式的資料模型。
Amazon Bedrock 結構化輸出帶來的改變
結構化輸出會在 token 生成期間使用受限解碼來強制套用 JSON 結構描述,而非事後才處理。模型不會產生違反結構描述的 token。這令輸出格式由機率性轉為確定性。
Amazon Bedrock 的兩個端點現均支援以下兩種互補機制:
| 功能 | 用途 | 使用情境 |
| JSON Schema 輸出格式 | 控制模型的回應結構 | 資料提取、報告生成、API 回應 |
| 嚴格工具呼叫 | 根據結構描述驗證工具參數 | Agent 型工作流程、函數呼叫、多步驟自動化 |
這對你有何意義
每個回應都是有效的 JSON,因此不會再遇到 JSON.parse() 錯誤或解析例外。回應亦具備型別安全性:系統會強制執行欄位型別,並確保必填欄位一律存在。由於輸出始終符合你的結構描述,你無須透過重試處理結構描述違規,令整合更可靠。結構化輸出亦會將回應限制在結構描述所定義的欄位內,減少輸出 token 數量,並有助降低高用量工作負載的推理成本。這些特性令結構化輸出已適合用於生產環境,你可以大規模部署,而無須額外編寫結構描述驗證程式碼。
支援的模型與可用情況
結構化輸出支援批次推理,讓你以非同步方式處理大量請求,同時仍可收到符合結構描述的輸出。在 bedrock-runtime 端點上,它亦支援跨區域推理,讓你無須額外設定即可在 AWS 區域之間使用。如需即時回應,你可以將結構化回應串流為具型別的事件。
運作方式
使用 JSON 結構描述提出請求時,系統會在幕後執行以下步驟:
- 結構描述驗證 – Amazon Bedrock 會根據受支援的 JSON Schema Draft 2020-12 子集驗證你的 JSON 結構描述。
- 文法編譯 – 對於新結構描述,Amazon Bedrock 會編譯文法產物(首次請求可能需時稍長)。
- 快取 – 編譯後的文法會快取 24 小時,令之後的請求更快。
- 受限生成 – 模型會生成能產生符合結構描述的有效 JSON 的 token。
效能考量
在效能方面,使用新結構描述的首次請求可能需要較長時間,因為 Amazon Bedrock 會在開始生成前編譯文法產物。首次編譯完成後,使用相同結構描述的後續請求所需的額外處理時間極少,因為已編譯的文法會快取。此快取以你的帳戶為範圍,自首次存取起有效 24 小時。變更 JSON 結構描述的結構會令快取失效,並觸發重新編譯;只變更名稱或描述欄位則不會影響已快取的文法。
入門:使用 InvokeModel API (bedrock-runtime) 的結構化輸出
InvokeModel API 使用 Anthropic 原生請求本文,因此結構描述應以 JSON 物件而非 JSON 字串的形式放在 output_config.format 中。以下範例展示如何使用 boto3 搭配 Anthropic Claude 模型,從客戶電郵擷取結構化的潛在客戶資料:
Python
import boto3
import json
REGION = "us-east-1" # Choose your preferred region
bedrock_runtime = boto3.client(service_name="bedrock-runtime", region_name=REGION)
# Define the JSON schema for structured output
schema = {
"type": "object",
"properties": {
"name": {"type": "string", "description": "Customer name"},
"email": {"type": "string", "description": "Customer email address"},
"plan_interest": {"type": "string", "description": "Product plan of interest"},
"demo_requested": {"type": "boolean", "description": "Whether a demo was requested"}
},
"required": ["name", "email", "plan_interest", "demo_requested"],
"additionalProperties": False
}
# Make a request with structured outputs via the InvokeModel API
# (reusing the schema defined for the Converse example)
response = bedrock_runtime.invoke_model(
modelId="global.anthropic.claude-sonnet-5-5",
body=json.dumps({
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 512,
"messages": [
{"role": "user", "content": (
"Paulo Santos (paulo@example.com) is interested in our Enterprise plan "
"and wants to schedule a demo for next Tuesday at 2pm."
)}
],
"output_config": {"format": {"type": "json_schema", "schema": schema}}
})
)
body = json.loads(response["body"].read())
# Check the stop reason before parsing
if body["stop_reason"] == "end_turn":
result_text = next(b["text"] for b in body["content"] if b["type"] == "text")
print(json.dumps(json.loads(result_text), indent=2))
elif body["stop_reason"] == "max_tokens":
print("Response truncated: increase max_tokens and retry.")JSON
{
"name": "Paulo Santos",
"email": "paulo@example.com",
"plan_interest": "Enterprise",
"demo_requested": true
}回應符合你的結構描述。無需額外驗證。
如需更多 API 使用範例,包括 Messages API,請參閲隨附的 範例筆記簿。
適用於 Agent 工作流程的嚴格工具使用
Amazon Bedrock Mantle 專為採用伺服器端工具、背景推理及有狀態對話的 Agent 式應用程式而設。在 bedrock-mantle 端點啟用嚴格工具使用後,你現在可以確保工具參數完全符合輸入結構描述。以下範例展示如何定義一個採用嚴格結構描述強制執行的工具:
Import json
from anthropic import AnthropicBedrockMantle
# Reusing the client created in the Messages API example
client = AnthropicBedrockMantle(aws_region="us-east-1")
message = client.messages.create(
model="anthropic.claude-sonnet-5",
max_tokens=512,
messages=[{"role": "user", "content": "What's the weather like in San Francisco?"}],
tools=[
{
"name": "get_weather",
"description": "Get the current weather for a specified 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"],
"description": "Temperature unit"
}
},
"required": ["location", "unit"],
"additionalProperties": False
}
}
]
)
#Tool inputs conform to the schema
for block in message.content:
if block.type == "tool_use":
print(f"Tool: {block.name}")
print(f"Input: {json.dumps(block.input, indent=2)}")設定 strict: true 可限制模型的工具輸入,使其完全符合你的結構描述。location 欄位一律為字串,而 unit 欄位則一律為 celsius 或 fahrenheit。模型不能加入結構描述以外的欄位,因此工具輸入只會包含結構描述指定的內容。
這對 Amazon Bedrock Mantle 上的 Agent 使用場景尤其有用,因為模型會運用網頁搜尋和程式碼解譯器等伺服器端工具,協調多步驟工作流程。
Claude 結構化輸出的主要使用場景
在以下三種常見模式中,結構化輸出最能減少錯誤處理的複雜程度:
- 資料擷取:從發票、合約、電郵和文字記錄中擷取欄位,轉換為一律符合結構描述的 JSON,以便載入資料庫或客戶關係管理 (CRM) 系統。
- 可靠的 Agent 工具呼叫:在生成時根據結構描述驗證工具引數,確保多步驟 Agent 工作流程不會因輸入格式錯誤而失敗。
- 大規模分類:按意圖、優先級和情感分類支援工單、潛在客戶或內容,以便進行路由、審核和評估。
Claude Haiku 5.5 能可靠處理摘要、內容壓縮、資料庫查詢和分類請求等快速且重複的工作負載。以下範例展示如何使用 Invoke API 和 Haiku 5.5 對傳入資料進行分類和路由:
import boto3
import json
REGION = "us-east-1" # Choose your preferred region
bedrock_runtime = boto3.client(service_name="bedrock-runtime", region_name=REGION)
# Classification schema: enums restrict output to a fixed set of labels
schema = {
"type": "object",
"properties": {
"category": {
"type": "string",
"enum": ["billing", "technical", "account", "sales", "other"],
"description": "Primary ticket category"
},
"priority": {
"type": "string",
"enum": ["low", "medium", "high", "urgent"],
"description": "Urgency based on business impact"
},
"sentiment": {
"type": "string",
"enum": ["positive", "neutral", "negative"],
"description": "Customer sentiment"
},
"escalate": {"type": "boolean", "description": "Whether a human should review immediately"},
"reason": {"type": "string", "description": "One-sentence justification for the classification"}
},
"required": ["category", "priority", "sentiment", "escalate", "reason"],
"additionalProperties": False
}
ticket = (
"Our production API calls have been failing with 500 errors since this morning. "
"We're losing orders every minute. This is the second outage this month!"
)
# Make a request with structured outputs via the InvokeModel API
response = bedrock_runtime.invoke_model(
modelId="global.anthropic.claude-haiku-5-5",
body=json.dumps({
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 512,
"system": "You are a support ticket classifier. Classify the ticket accurately.",
"messages": [
{"role": "user", "content": f"Classify this support ticket:\n\n{ticket}"}
],
"output_config": {"format": {"type": "json_schema", "schema": schema}}
})
)
body = json.loads(response["body"].read())
# Check the stop reason before parsing
if body["stop_reason"] == "end_turn":
result_text = next(b["text"] for b in body["content"] if b["type"] == "text")
result = json.loads(result_text)
print(json.dumps(result, indent=2))
# Route the ticket based on the guaranteed-valid labels
if result["escalate"]:
print(f"Escalating to on-call: {result['category']} / {result['priority']}")
elif body["stop_reason"] == "max_tokens":
print("Response truncated: increase max_tokens and retry.")要求和最佳做法
要在 Amazon Bedrock 上有效使用結構化輸出,請遵循以下指引:
- 為所有物件設定 additionalProperties: false:這是使用結構化輸出的必要條件。若未設定,系統便不會接受你的結構描述。
- 使用具描述性的欄位名稱和描述:模型會根據屬性名稱和描述瞭解要擷取哪些資料。清晰的名稱(例如
customer_email)比通用名稱(例如field1)更有效。 - 使用 enum 限定可選值:欄位的有效值數量有限時,請使用
enum限定選項。 - 先從基本結構開始,再逐步增加複雜度:先使用最低限度的必要欄位,再逐步增加複雜度。基本結構描述的編譯速度較快、較易除錯,亦可精簡請求內容,因為結構描述會計入 Converse API 的 payload 大小。
- 重用結構描述以善用快取:設計應用程式時,應在多個請求中重用結構描述。24 小時文法快取可提升重複查詢的效能。
- 每次回應都要檢查停止原因:有兩種情況會產生不符合要求的回應:拒絕(模型基於安全理由拒絕回應)和 token 限制(在完成前已達到
max_tokens)。請在程式碼中處理這兩種情況。 - 部署前使用具代表性的資料進行測試:使用能代表生產環境的輸入內容驗證結構描述。真實資料中的邊界情況往往會揭示結構描述設計上的問題。
如要了解其他最佳做法和結構描述設計建議,請參閲《Amazon Bedrock 使用者指南》中的結構化輸出。
支援的 JSON Schema 功能
- 所有基本類型:
object、array、string、integer、number、boolean、null。 enum(只限字串、數字、布林值或 null)。const、anyOf、allOf(有限制)。$ref、$def和definitions(只限內部參照)。- 字串格式:
date-time、time、date、duration、email、hostname、uri、ipv4、ipv6、uuid。 - 陣列
minItems(值只限 0 和 1)。
不支援
API 接受這些關鍵字,但在生成期間不會強制執行。包含這些關鍵字的請求仍會成功回應,而模型仍可能傳回違反相關限制的值。請在應用程式中驗證這些限制,不要依賴結構描述強制執行。
- 遞迴結構描述。
- 外部
$ref參照。 - 數值限制(
minimum、maximum、multipleOf)。 - 字串限制(
minLength、maxLength)。 additionalProperties設為 false 以外的任何值。
結語
Amazon Bedrock 上 Anthropic Claude 模型的結構化輸出,能提供生產環境 AI 應用所需的可靠性。這項功能現已在 bedrock-runtime 和 bedrock-mantle 端點推出。結合 JSON Schema 輸出格式與嚴格工具使用,你可以建立無需額外驗證的數據管道。你亦可以建立可靠的 Agent 工作流程和生產環境 AI 應用,無需自訂剖析或重試邏輯。
Amazon Bedrock 上 Claude 的結構化輸出現已正式推出。如要了解更多,請參閲Amazon Bedrock 文件,並瀏覽我們的範例筆記本。
經驗證且符合結構描述的 JSON,可以改善你所在機構的哪些工作流程?歡迎在留言中分享意見和問題。
作者簡介
Anshika Saxena
Anshika 是 AWS 的生成式 AI 數據科學家,專注於 Amazon Bedrock。她協助企業客戶加快採用生成式 AI 和 Agent 式 AI,並指導他們在 Amazon Bedrock 上建置及實施解決方案。她亦與 ISV 和初創公司合作,協助他們採用 Amazon Bedrock 上最新的 Anthropic 服務。
Dani Mitchell
Dani 是 AWS 的生成式 AI 資深專業解決方案架構師,負責 Anthropic 在 Amazon Bedrock 上的市場拓展工作。他協助全球各地的企業運用 Amazon Bedrock 上 Anthropic 的模型和功能,設計及部署生成式 AI 解決方案,以建置可擴展且適合生產環境使用的應用程式。
Alfredo Castillo
Alfredo 是 AWS 的生成式 AI 資深專業解決方案架構師,專注於在 Amazon Bedrock 上推動 Anthropic 模型的市場拓展。他與金融服務客戶合作,設計並擴展分散式系統中的生成式 AI 解決方案,並將生成式 AI 實驗轉化為正式投入生產的工作負載。工作以外,他熱愛家庭及耐力運動。
Aamna Najmi
Aamna 是生成式 AI 資深專業解決方案架構師,專注於 Anthropic 模型,以及在 Amazon Bedrock 上大規模實現生成式 AI 系統的營運化和治理。她協助獨立軟件供應商(ISV)解決挑戰、擁抱創新,並透過 Amazon Bedrock 開拓新的商機。
Sofian Hamiti
Sofian 是科技領袖,擁有超過 12 年構建 AI 解決方案,以及帶領高績效團隊以提升客戶成果的經驗。他熱衷於賦能多元人才,推動全球影響力,並助他們實現職業抱負。
Ayan Ray
Ayan 是 AWS 的首席合作夥伴解決方案架構師及 AI 技術主管,並擔任 AWS 的 Anthropic 全球技術主管。他專注於雲端架構與人工智能的交匯領域,協助機構在 AWS 上採用並擴展 Anthropic 的技術。
來源:AWS Machine Learning Blog · aws.amazon.com