跳到正文
AWS Machine Learning Blog·· 2026-10-20精选

Bedrock 为 Claude 模型提供结构化输出与严格工具调用

AI 导读

AWS 公告介绍通过 JSON Schema 和 strict tool use 约束输出结构,减少自行解析和修补格式的工作。结构符合约定并不保证业务内容正确,仍应保留数据与权限检查。

推荐理由

Codex 来源核对 · 原始技术资料,附实现与评估入口。

正文 · AI 翻译

Amazon Bedrock 现已为所有 Anthropic Claude 模型支持结构化输出,适用于提供相应模型的 bedrock-runtime 和 bedrock-mantle 两个端点。

无论你通过 Boto3 和 bedrock-runtime API 调用 Claude,还是通过 Messages API 和 bedrock-mantle 端点调用,现在都能收到符合所定义结构和模式的 JSON 响应。你不再需要自定义解析、重试逻辑或后处理。

实际应用

借助 Amazon Bedrock 上 Claude 的结构化输出,你可以在各行业中自动执行可靠且符合模式的任务。例如,从财务业绩报告和合规文件中提取所有必填字段,将临床记录解析为电子健康记录(EHR),以及使用一致且经过验证的结果丰富产品目录。你还可以分析合同中的关键条款、相关方和义务,或实现智能支持工单路由,确保意图、情感和实体始终符合应用的数据模型。

Amazon Bedrock 上的结构化输出带来了哪些变化

结构化输出使用约束解码,在生成 token 的过程中强制遵循你的 JSON 模式,而非事后处理。模型不会生成违反模式的 token。这使输出格式从概率性的变为确定性的。

Amazon Bedrock 的两个端点现在均提供两种互补机制:

功能 用途 使用场景
JSON Schema 输出格式 控制模型的响应结构 数据提取、报告生成、API 响应
严格工具使用 依据模式验证工具参数 智能体工作流、函数调用、多步骤自动化

这对你意味着什么

每个响应都是有效的 JSON,因此你不会再遇到 JSON.parse() 错误或解析异常。响应还具有类型安全性:字段类型受到强制约束,且必填字段始终存在。由于输出始终符合你的模式,你无需通过重试来处理模式违规问题,从而使集成更加可靠。结构化输出还会将响应限制为仅包含模式定义的字段,从而减少输出 token 数量,并可能降低高请求量工作负载的推理成本。这些特性使结构化输出具备生产环境可用性,让你无需额外的模式验证代码即可大规模部署。

支持的模型与可用性

结构化输出适用于批量推理,因此你可以异步处理大量请求,同时仍能获得符合模式的输出。在 bedrock-runtime 端点上,它还支持跨区域推理,让你无需额外设置即可跨 AWS 区域使用。如果需要实时响应,你可以将结构化响应作为带类型的事件进行流式传输。

工作原理

当你使用 JSON 模式发起请求时,后台会执行以下步骤:

  1. 模式验证 – Amazon Bedrock 根据所支持的 JSON Schema Draft 2020-12 子集验证你的 JSON 模式。
  2. 语法编译 – 对于新模式,Amazon Bedrock 会编译生成语法产物(首次请求可能稍慢)。
  3. 缓存 – 编译后的语法会缓存 24 小时,从而加快后续请求。
  4. 约束生成 – 模型生成的 token 会构成符合你的模式的有效 JSON。

性能注意事项

在性能方面,使用新模式的首次请求可能耗时更长,因为 Amazon Bedrock 会在开始生成之前编译生成语法产物。首次编译完成后,由于编译后的语法已缓存,使用相同模式的后续请求只会产生极少的额外开销。此缓存限定在你的账户范围内,自首次访问起保留 24 小时。更改 JSON 模式的结构会使缓存失效并触发重新编译,而仅更改 name 或 description 字段则会保留已缓存的语法。

入门:通过 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 的示例,请参阅配套的示例 notebook。

面向智能体工作流的严格工具使用

Amazon Bedrock Mantle 专为使用服务端工具、后台推理和有状态对话的智能体应用而设计。借助 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 上的智能体使用场景尤为有用,因为模型会借助网页搜索和代码解释器等服务端工具来编排多步骤工作流。

Claude 结构化输出的主要使用场景

结构化输出在以下三种常见模式中最能降低错误处理的复杂度:

  • 数据提取:从发票、合同、电子邮件和转录文本中提取字段,生成始终符合模式的 JSON,可直接载入数据库或客户关系管理(CRM)系统。
  • 可靠的智能体工具调用:在生成时依据工具参数的模式进行验证,让多步骤智能体工作流不会因输入格式错误而失败。
  • 大规模分类:按意图、优先级和情感对工单、销售线索或内容进行分类,用于路由、审核和评估。

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 上有效使用结构化输出,请遵循以下指南:

  1. 为所有对象设置 additionalProperties: false:这是结构化输出正常工作的必要条件。缺少此设置,你的模式将不会被接受。
  2. 使用具有描述性的字段名和描述:模型通过属性名称和描述来理解要提取哪些数据。像 customer_email 这样清晰的名称,比 field1 这样的通用名称效果更好。
  3. 使用 enum 限定取值:当某个字段的有效值范围有限时,使用 enum 来约束选项。
  4. 从基础开始,逐步增加复杂度:先使用最少的必填字段,再逐步增加复杂度。基础模式编译更快、更易于调试,也能保持较小的请求载荷,因为模式会计入 Converse API 的载荷大小。
  5. 复用模式以利用缓存:设计应用时,让不同请求复用模式。24 小时的语法缓存可提升重复查询的性能。
  6. 检查每个响应中的停止原因:两种情况可能产生不符合模式的响应:拒绝(模型出于安全原因拒绝请求)和 token 限制(尚未完成就达到 max_tokens)。请在代码中处理这两种情况。
  7. 部署前使用真实数据测试:使用能够代表生产环境的输入验证模式。真实数据中的边界情况往往会暴露模式设计问题。

如需更多最佳实践和模式设计建议,请参阅《Amazon Bedrock 用户指南》中的结构化输出。

支持的 JSON Schema 功能

  1. 所有基本类型:object、array、string、integer、number、boolean、null。
  2. enum(仅限字符串、数字、布尔值或 null 值)。
  3. const、anyOf、allOf(存在限制)。
  4. $ref、$def 和 definitions(仅限内部引用)。
  5. 字符串格式:date-time、time、date、duration、email、hostname、uri、ipv4、ipv6、uuid。
  6. 数组的 minItems(仅限值 0 和 1)。

不支持的功能

不支持以下功能:

  1. 递归模式。
  2. 外部 $ref 引用。
  3. 数值约束(minimum、maximum、multipleOf)。
  4. 字符串约束(minLength、maxLength)。
  5. 将 additionalProperties 设置为 false 以外的任何值。

结语

Amazon Bedrock 上 Anthropic Claude 模型的结构化输出提供了生产级 AI 应用所需的可靠性。该功能现已在 bedrock-runtime 和 bedrock-mantle 两个端点上提供。结合 JSON Schema 输出格式与严格工具使用,你可以构建无需额外验证的数据流水线,还可以创建可靠的智能体工作流和生产级 AI 应用,无需自定义解析或重试逻辑。

Amazon Bedrock 上 Claude 的结构化输出现已正式可用。如需了解更多,请参阅 Amazon Bedrock 文档并探索我们的示例 notebook。

经过验证且符合模式的 JSON 能改善你所在组织的哪些工作流?欢迎在评论区分享反馈和问题。


关于作者

来源:AWS Machine Learning Blog · aws.amazon.com