Amazon Bedrock宣布在bedrock-runtime和bedrock-mantle两个端点为所有Claude模型支持结构化输出。开发者可通过JSON Schema输出格式和严格工具调用获取符合指定结构的JSON,减少自定义解析、重试与后处理。
Amazon Bedrock 现已为所有可用的 Anthropic Claude 模型提供结构化输出支持,覆盖 bedrock-runtime 和 bedrock-mantle 两个端点。
无论你通过 Boto3 和 bedrock-runtime API 调用 Claude,还是通过 Messages API 和 bedrock-mantle 端点调用,现在都能收到符合指定 schema 和结构的 JSON 响应。你不再需要自行编写解析、重试或后处理逻辑。
借助 Amazon Bedrock 上 Claude 的结构化输出,你可以在各行各业中,可靠地自动执行符合 schema 的任务。例如,从财报和合规文档中提取所有必需字段,将临床记录解析为电子健康记录(EHR),以及为产品目录补充一致且经过验证的信息。你还可以分析合同中的关键条款、当事方和义务,或者实现智能客服工单路由,确保意图、情感和实体始终符合应用的数据模型。
结构化输出通过约束解码,在生成 token 的过程中强制执行你的 JSON schema,而不是等生成完成后再检查。模型不会生成违反 schema 的 token。这让输出格式从概率性的结果变成了确定性的结果。
Amazon Bedrock 的两个端点现在都提供了两种互补机制:
每个响应都是有效的 JSON,因此你不会再遇到 JSON.parse() 错误或解析异常。响应也具备类型安全性:字段类型受到强制约束,必需字段始终存在。由于输出始终符合 schema,你无需为处理 schema 违规而重试,集成也会更加可靠。结构化输出还会将响应限制在 schema 定义的字段内,从而减少输出 token 数量,并可能降低高请求量工作负载的推理成本。这些特性让结构化输出具备了生产环境所需的能力,你可以直接大规模部署,无需额外编写 schema 验证代码。
结构化输出支持批量推理,因此你可以异步处理大量请求,同时仍然获得符合 schema 的输出。在 bedrock-runtime 端点上,它还支持跨 Region 推理,让你无需额外设置,就能跨 AWS Region 使用。如果需要实时响应,你可以通过带类型的事件流式接收结构化响应。
当你提交包含 JSON schema 的请求时,后台会依次执行以下步骤:
从性能上看,使用新 schema 的首次请求可能耗时更长,因为 Amazon Bedrock 需要在开始生成前编译语法产物。完成首次编译后,使用相同 schema 的后续请求只会产生极小的额外开销,因为编译后的语法已经缓存。该缓存以你的账户为作用域,从首次访问起保留 24 小时。修改 JSON schema 的结构会使缓存失效,并触发重新编译;如果只修改 name 或 description 字段,则不会影响已缓存的语法。
InvokeModel API 接收 Anthropic 原生格式的请求体,因此 schema 应以 JSON 对象的形式放在 output_config.format 中,而不是作为 JSON 字符串传入。下面的示例展示了如何通过 boto3 调用 Anthropic Claude 模型,从客户邮件中提取结构化的销售线索数据:
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.")
{
"name": "Paulo Santos",
"email": "paulo@example.com",
"plan_interest": "Enterprise",
"demo_requested": true
}
响应符合你定义的 schema,无需额外验证。
如需更多 API 使用示例,包括 Messages API 的示例,请参阅配套的示例 notebook。
Amazon Bedrock Mantle 专为 Agent 应用设计,支持服务端工具、后台推理和有状态对话。借助 bedrock-mantle 端点上的严格工具调用,你现在可以保证工具参数与输入 schema 完全一致。下面的示例展示了如何定义一个严格执行 schema 约束的工具:
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 后,模型的工具输入就会被约束为与你的 schema 完全一致。location 字段始终是字符串,unit 字段始终只能是 celsius 或 fahrenheit。模型无法添加 schema 之外的字段,因此工具输入只包含 schema 指定的内容。
这对 Amazon Bedrock Mantle 上的 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 上有效使用结构化输出,请遵循以下建议:
如需更多最佳实践和 schema 设计建议,请参阅《Amazon Bedrock 用户指南》中的“结构化输出”。
以下关键字会被 API 接受,但不会在生成过程中强制执行。包含这些关键字的请求会成功返回响应,但模型仍可能生成违反这些约束的值。请在应用中验证这些约束,不要依赖 schema 来强制执行。
Amazon Bedrock 上 Anthropic Claude 模型的结构化输出,提供了生产级 AI 应用所需的可靠性。该功能现已在 bedrock-runtime 和 bedrock-mantle 两个端点上线。结合 JSON Schema 输出格式和严格工具调用,你可以构建无需额外验证的数据流水线,也可以创建可靠的 Agent 工作流和生产级 AI 应用,无需自行编写解析或重试逻辑。
Amazon Bedrock 上 Claude 的结构化输出现已正式可用。如需了解更多信息,请参阅 Amazon Bedrock 文档,并查看我们的示例 notebook。
经过验证、符合 schema 的 JSON,能改善你所在组织的哪些工作流?欢迎在评论区分享反馈和问题。