

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 從模型取得經過驗證的 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` 請求欄位。針對 Converse 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 會根據支援的 JSON 結構描述草稿 2020 年 12 月子集來驗證 JSON 結構描述格式。如果結構描述包含不支援的功能，Amazon Bedrock 會立即傳回 400 錯誤。

1. **第一次編譯** – 對於新的結構描述，Amazon Bedrock 會編譯文法，最多可能需要幾分鐘的時間。

1. **快取** – 成功編譯的文法會在第一次存取後快取 24 小時。快取文法會使用 AWS 受管金鑰加密。

1. **後續請求** – 來自相同帳戶的相同結構描述使用快取文法，導致推論延遲與具有最低額外負荷的標準請求相當。

1. **回應** – 您收到具有嚴格結構描述合規的標準推論回應。

## 支援的 JSON 結構描述功能
<a name="structured-output-supported-schema-features"></a>

支援下列 JSON 結構描述草稿 2020-12 功能：
+ 所有基本類型：`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)

*不支援*下列功能：
+ 遞迴結構描述
+ 外部`$ref`參考
+ 數值限制 (`minimum`、`maximum`、`multipleOf`)
+ 字串限制條件 (`minLength`、`maxLength`)
+ `additionalProperties` 設定為 以外的任何項目 `false`

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

您可以在下列 Amazon Bedrock 功能中使用結構化輸出：

**Converse 和 ConverseStream APIs** – 使用結構化輸出搭配 Converse 和 ConverseStream APIs 進行對話推論。

**InvokeModel 和 InvokeModelWithResponseStream APIs** – 將結構化輸出與 InvokeModel 和 InvokeModelWithResponseStream APIs搭配使用，以進行一次性推論。

**跨區域推論** – 在跨區域推論中使用結構化輸出，無需任何額外設定。

**批次推論** – 在批次推論中使用結構化輸出，無需任何額外設定。

**`bedrock-mantle` 端點上的 Anthropic Messages API** – Anthropic 樣式的 Messages API 路徑 () *不支援*結構化輸出`https://bedrock-mantle.{region}.api.aws/anthropic/v1/messages`。`output_config.format` 參數遭到拒絕，並出現 400 錯誤。若要搭配AnthropicClaude模型使用結構化輸出，請透過`bedrock-runtime`端點上的 Converse API 或 InvokeModel API 傳送請求。

**注意**  
結構化輸出與 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 Schema 輸出格式搭配結構化輸出。

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

##### 檢視範例
<a name="w2aac15c15c37c15b3b5b3b1"></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 (Anthropic Claude)
<a name="json-schema-invokemodel-claude"></a>

##### 檢視範例
<a name="w2aac15c15c37c15b3b7b3b1"></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 (Open-weight 模型）
<a name="json-schema-invokemodel-openweight"></a>

##### 檢視範例
<a name="w2aac15c15c37c15b3b9b3b1"></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="w2aac15c15c37c15b5b5b3b1"></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 (Anthropic Claude)
<a name="strict-tool-invokemodel-claude"></a>

##### 檢視範例
<a name="w2aac15c15c37c15b5b7b3b1"></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 (Open-weight 模型）
<a name="strict-tool-invokemodel-openweight"></a>

##### 檢視範例
<a name="w2aac15c15c37c15b5b9b3b1"></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
}
```