

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 从模型中获取经过验证的 JSON 结果
<a name="structured-output"></a>

结构化输出是 Amazon Bedrock 上的一项功能，可确保模型响应符合用户定义的 JSON 架构和工具定义，从而减少生产 AI 部署中对自定义解析和验证机制的需求。

## 优势
<a name="structured-output-benefits"></a>

结构化输出解决了生产 AI 应用程序中的关键挑战：
+ **确保架构合规性** — 消除基于提示的方法中的错误率和重试循环
+ **降低开发复杂性** — 无需自定义解析和验证逻辑
+ **降低运营成本** — 减少失败的请求和重试次数
+ **生产可靠性** — 支持自信地部署需要可预测的机器可读输出的 AI 应用程序

## 工作原理
<a name="structured-output-how-it-works"></a>

结构化输出将模型响应限制为遵循特定架构，从而确保下游处理的输出有效、可解析。您可以通过两种互补机制使用结构化输出：

### JSON 架构输出格式
<a name="structured-output-json-schema"></a>

对于带有 Anthropic Claude 模型的 InvokeModel API，请使用`output_config.format`请求字段。对于开放式重量模型，请使用`response_format`请求字段。对于匡威 APIs，请使用`outputConfig.textFormat`请求字段。模型的响应将符合指定的 JSON 架构。

### 严格使用工具
<a name="structured-output-strict-tool-use"></a>

在工具定义中添加`strict: true`标志，以启用对工具名称和输入的架构验证。然后，模型的工具调用将遵循定义的工具输入架构。

这些机制可以单独使用，也可以在同一个请求中一起使用。有关更多详细信息，请参阅 [Bedrock API 文档](https://docs.aws.amazon.com/bedrock/latest/APIReference/welcome.html)。

### 请求工作流程
<a name="structured-output-request-workflow"></a>

以下内容介绍了 Amazon Bedrock 如何处理带有结构化输出的请求：

1. **初始请求** — 您可以通过`outputConfig.textFormat`、或`response_format`参数包含一个 JSON 架构`output_config.format`，或者在推理请求中加入带有`strict: true`标志的工具定义。

1. **架构验证** — Amazon Bedrock 根据支持的 2020-12 年 JSON 架构草案子集验证 JSON 架构格式。如果架构包含不支持的功能，Amazon Bedrock 会立即返回 400 错误。

1. **首次编译** — 对于新的架构，Amazon Bedrock 会编译语法，这可能需要几分钟。

1. **缓存** — 成功编译的语法将在首次访问后缓存 24 小时。缓存的语法使用 AWS 托管的密钥进行加密。

1. **后续请求** — 来自同一账户的相同架构使用缓存的语法，因此推理延迟与标准请求相当，开销最小。

1. **响应**-您会收到具有严格架构合规性的标准推理响应。

## 支持的 APIs 或功能
<a name="structured-output-supported-apis"></a>

您可以在以下 Amazon Bedrock 功能中使用结构化输出：

**Converse ConverseStream APIs** and — 使用结构化输出和 Converse ConverseStream APIs 进行对话推理。

**InvokeModel 和 InvokeModelWithResponseStream APIs** — 使用带 InvokeModel 和的结构化输出 InvokeModelWithResponseStream APIs 进行单圈推断。

**跨区域推理 — 在跨区域推理**中使用结构化输出，无需任何其他设置。

**Batch Inf** erence — 在批量推理中使用结构化输出，无需任何其他设置。

**注意**  
结构化输出与 Anthropic 模型的引文不兼容。如果您在使用结构化输出时启用引文，则模型将返回 400 错误。

## 支持的模型
<a name="structured-output-supported-models"></a>

要查看哪些模型支持结构化输出，请[快速浏览](model-cards.md)模型并选择您感兴趣的模型。

## 示例请求
<a name="structured-output-examples"></a>

### JSON 架构输出格式
<a name="structured-output-json-schema-examples"></a>

以下示例说明如何将 JSON 架构输出格式与结构化输出一起使用。

#### Converse API
<a name="json-schema-converse"></a>

##### 查看示例
<a name="w2aac15c32c35c13b3b5b3b1"></a>

```
{
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "text": "Given the following unstructured data, extract it into the provided structure."
        },
        {
          "text": "..."
        }
      ]
    }
  ],
  "outputConfig": {
    "textFormat": {
      "type": "json_schema",
      "structure": {
        "jsonSchema": {
          "schema": "{\"type\": \"object\", \"properties\": {\"title\": {\"type\": \"string\", \"description\": \"title\"}, \"summary\": {\"type\": \"string\", \"description\": \"summary\"}, \"next_steps\": {\"type\": \"string\", \"description\": \"next steps\"}}, \"required\": [\"title\", \"summary\", \"next_steps\"], \"additionalProperties\": false}",
          "name": "data_extraction",
          "description": "Extract structured data from unstructured text"
        }
      }
    }
  }
}
```

#### InvokeModel （人类 Claude）
<a name="json-schema-invokemodel-claude"></a>

##### 查看示例
<a name="w2aac15c32c35c13b3b7b3b1"></a>

```
{
  "anthropic_version": "bedrock-2023-05-31",
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "Given the following unstructured data, extract it into the provided structure."
        },
        {
          "type": "text",
          "text": "..."
        }
      ]
    }
  ],
  "max_tokens": 3000,
  "temperature": 1.0,
  "output_config": {
    "format": {
      "type": "json_schema",
      "schema": {
        "type": "object",
        "properties": {
          "title": {
            "type": "string",
            "description": "title"
          },
          "summary": {
            "type": "string",
            "description": "summary"
          },
          "next_steps": {
            "type": "string",
            "description": "next steps"
          }
        },
        "required": [
          "title",
          "summary",
          "next_steps"
        ],
        "additionalProperties": false
      }
    }
  }
}
```

#### InvokeModel （开放式重量款）
<a name="json-schema-invokemodel-openweight"></a>

##### 查看示例
<a name="w2aac15c32c35c13b3b9b3b1"></a>

```
{
  "messages": [
    {
      "role": "user",
      "content": "Given the following unstructured data, extract it into the provided structure."
    },
    {
      "role": "user",
      "content": "..."
    }
  ],
  "inferenceConfig": {
    "maxTokens": 3000,
    "temperature": 1.0
  },
  "response_format": {
    "json_schema": {
      "name": "summarizer",
      "schema": {
        "type": "object",
        "properties": {
          "title": {
            "type": "string",
            "description": "title"
          },
          "summary": {
            "type": "string",
            "description": "summary"
          },
          "next_steps": {
            "type": "string",
            "description": "next steps"
          }
        },
        "required": [
          "title",
          "summary",
          "next_steps"
        ],
        "additionalProperties": false
      }
    },
    "type": "json_schema"
  }
}
```

### 严格使用工具
<a name="structured-output-strict-tool-examples"></a>

以下示例说明如何在使用工具时使用严格字段。

#### Converse API
<a name="strict-tool-converse"></a>

##### 查看示例
<a name="w2aac15c32c35c13b5b5b3b1"></a>

```
{
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "text": "What's the weather like in New York?"
        }
      ]
    }
  ],
  "toolConfig": {
    "tools": [
      {
        "toolSpec": {
          "name": "get_weather",
          "description": "Get the current weather for a specified location",
          "strict": true,
          "inputSchema": {
            "json": {
              "type": "object",
              "properties": {
                "location": {
                  "type": "string",
                  "description": "The city and state, e.g. San Francisco, CA"
                },
                "unit": {
                  "type": "string",
                  "enum": [
                    "fahrenheit",
                    "celsius"
                  ],
                  "description": "The temperature unit to use"
                }
              },
              "required": [
                "location",
                "unit"
              ]
            }
          }
        }
      }
    ]
  }
}
```

#### InvokeModel （人类 Claude）
<a name="strict-tool-invokemodel-claude"></a>

##### 查看示例
<a name="w2aac15c32c35c13b5b7b3b1"></a>

```
{
  "anthropic_version": "bedrock-2023-05-31",
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "What's the weather like in San Francisco?"
        }
      ]
    }
  ],
  "max_tokens": 3000,
  "temperature": 1.0,
  "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": [
              "fahrenheit",
              "celsius"
            ],
            "description": "The temperature unit to use"
          }
        },
        "required": [
          "location",
          "unit"
        ],
        "additionalProperties": false
      }
    }
  ]
}
```

#### InvokeModel （开放式重量款）
<a name="strict-tool-invokemodel-openweight"></a>

##### 查看示例
<a name="w2aac15c32c35c13b5b9b3b1"></a>

```
{
  "messages": [
    {
      "role": "user",
      "content": "What's the weather like in San Francisco?"
    }
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "Get the current weather for a specified location",
        "strict": true,
        "parameters": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "The city and state, e.g. San Francisco, CA"
            },
            "unit": {
              "type": "string",
              "enum": [
                "fahrenheit",
                "celsius"
              ],
              "description": "The temperature unit to use"
            }
          },
          "required": [
            "location",
            "unit"
          ]
        }
      }
    }
  ],
  "tool_choice": "auto",
  "max_tokens": 2000,
  "temperature": 1.0
}
```