

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

# 人类克劳德工具的使用
<a name="model-parameters-anthropic-claude-messages-tool-use"></a>

**警告**  
如下文所示，部分功能目前以测试版形式提供。根据服务条款的定义，这些功能作为 “测试服务” AWS 提供给您。它受您的协议和 AWS 服务条款 AWS 以及适用的 EULA 范本的约束。

使用 Anthropic Claude 模型，您可以指定模型可以用来回复消息的工具。例如，您可以指定一种工具来获取电台热门歌曲。如果用户发出消息：*WZPZ 上的热门歌曲是什么？*，模型将判断您指定的工具是否可以帮助回答问题。在响应中，模型将请求您代表其运行该工具。然后，您运行该工具并将工具结果传递给模型，然后模型会生成对原始消息的响应。有关更多信息，请参阅 Anthropic Claude 文档中的[工具使用（函数调用）](https://docs.anthropic.com/en/docs/tool-use)。

**提示**  
建议您使用 Converse API 将工具使用集成到应用程序中。有关更多信息，请参阅 [使用工具完成 Amazon Bedrock 模型响应](tool-use.md)。

**重要**  
Claude Sonnet 4.5 现在会保留工具调用字符串参数中的自定义格式。此前，字符串参数中的尾随换行符有时会被错误地去除。此修复可确保需要精确格式的工具（如文本编辑器）能够完全按预期接收参数。这是一项后台优化，无需对 API 进行任何更改。不过，接收字符串参数的工具现在可能会收到带尾随换行符的值，而这类换行符之前将被去除。

**注意**  
Claude Sonnet 4.5 包含自动优化，能够提升模型性能。这些优化可能会在请求中增加少量词元，但您无需为这些由系统添加的词元付费。

您可以在 `tools` 字段中指定想供模型使用的工具。以下示例展示了一种用于获取电台热门歌曲的工具。

```
[
    {
        "name": "top_song",
        "description": "Get the most popular song played on a radio station.",
        "input_schema": {
            "type": "object",
            "properties": {
                "sign": {
                    "type": "string",
                    "description": "The call sign for the radio station for which you want the most popular song. Example calls signs are WZPZ and WKRP."
                }
            },
            "required": [
                "sign"
            ]
        }
    }
]
```

当模型需要工具来生成对消息的响应时，它会在消息 `content` 字段中返回有关所请求工具的信息以及对该工具的输入。它还会将响应的停止原因设置为 `tool_use`。

```
{
    "id": "msg_bdrk_01USsY5m3XRUF4FCppHP8KBx",
    "type": "message",
    "role": "assistant",
    "model": "claude-3-sonnet-20240229",
    "stop_sequence": null,
    "usage": {
        "input_tokens": 375,
        "output_tokens": 36
    },
    "content": [
        {
            "type": "tool_use",
            "id": "toolu_bdrk_01SnXQc6YVWD8Dom5jz7KhHy",
            "name": "top_song",
            "input": {
                "sign": "WZPZ"
            }
        }
    ],
    "stop_reason": "tool_use"
}
```

在代码中，您代表工具调用该工具。然后，您在用户消息中将工具结果 (`tool_result`) 传递给模型。

```
{
    "role": "user",
    "content": [
        {
            "type": "tool_result",
            "tool_use_id": "toolu_bdrk_01SnXQc6YVWD8Dom5jz7KhHy",
            "content": "Elemental Hotel"
        }
    ]
}
```

在其响应中，模型使用工具结果为原始消息生成响应。

```
{
    "id": "msg_bdrk_012AaqvTiKuUSc6WadhUkDLP",
    "type": "message",
    "role": "assistant",
    "model": "claude-3-sonnet-20240229",
    "content": [
        {
            "type": "text",
            "text": "According to the tool, the most popular song played on radio station WZPZ is \"Elemental Hotel\"."
        }
    ],
    "stop_reason": "end_turn"
}
```

## Fine-grained 工具直播
<a name="model-parameters-anthropic-claude-messages-fine-grained-tool-streaming"></a>

Fine-grained 工具流是Claude Sonnet 4.5、Claude Haiku 4.5Claude Sonnet 4、和 Claude Opus 4 中提供的AnthropicClaude模型功能。利用精细工具流，Claude 开发人员无需进行缓冲或 JSON 验证，即可流式传输工具使用参数，从而缩短开始接收大型参数的延迟。

**注意**  
在使用精细工具流时，您可能会收到无效的 JSON 输入或部分 JSON 输入。请务必在代码中处理这些边缘案例。

要使用此功能，只需向工具使用请求添加标头 `fine-grained-tool-streaming-2025-05-14` 即可。

以下示例说明如何指定精细工具流标头：

```
{
  "anthropic_version": "bedrock-2023-05-31",
  "max_tokens": 1024,
  "anthropic_beta": ["fine-grained-tool-streaming-2025-05-14"],
  "messages": [
    {
      "role": "user",
      "content": "Can you write a long poem and make a file called poem.txt?"
    }
  ],
  "tools": [
    {
      "name": "make_file",
      "description": "Write text to a file",
      "input_schema": {
        "type": "object",
        "properties": {
          "filename": {
            "type": "string",
            "description": "The filename to write text to"
          },
          "lines_of_text": {
            "type": "array",
            "description": "An array of lines of text to write to the file"
          }
        },
        "required": [
          "filename",
          "lines_of_text"
        ]
      }
    }
  ]
}
```

在此示例中，利用精细工具流，Claude 可以将一首长诗的各行内容流式传输到工具调用 `make_file` 中，无需进行缓冲来验证 `lines_of_text` 参数是否为有效的 JSON。这意味着您可以在参数流到达时查看它，而无需等待整个参数完成缓冲和验证。

借助精细工具流，工具使用块的流式传输启动速度更快，并且通常块会更长且包含的断字更少。此情况是由于分块行为的差异造成的。

例如，不使用精细流的情况下，延迟为 15 秒：

```
Chunk 1: '{"'
Chunk 2: 'query": "Ty'
Chunk 3: 'peScri'
Chunk 4: 'pt 5.0 5.1 '
Chunk 5: '5.2 5'
Chunk 6: '.3'
Chunk 8: ' new f'
Chunk 9: 'eatur'
...
```

使用精细流的情况下，延迟为 3 秒：

```
Chunk 1: '{"query": "TypeScript 5.0 5.1 5.2 5.3'
Chunk 2: ' new features comparison'
```

**注意**  
由于精细流在发送参数时无需进行缓冲或 JSON 验证，因此无法保证生成的流会以有效的 JSON 字符串形式完成传输。具体而言，如果触发了停止原因 `max_tokens`，流可能会在某个参数的传输过程中中途结束，导致参数不完整。通常，当触发 `max_tokens` 时，您必须编写特定的支持来处理此情况。

## 计算机使用（测试版）
<a name="model-parameters-anthropic-claude-messages-computer-use"></a>

计算机使用是一个用于自动执行图形用户界面 (GUI) 任务的AnthropicClaude工具系列（测试版）。有关概述、Amazon Bedrock-specific 请求形式和端到端示例，请参阅[使用 Amazon Bedrock 模型使用计算机使用工具自动执行 GUI 任务](computer-use.md)。要了解哪些型号支持在每个端点上使用计算机，请参阅每个型号中的*功能和特*性表[模型一览](model-cards.md)。

要允许根据请求使用计算机，请`anthropic_beta`将其设置为计算机使用版本并添加与该版本`type`匹配的工具条目。有效的配对是：


| 测试版标头 | 计算机工具类型 | 
| --- | --- | 
| computer-use-2025-11-24 | computer\_20251124 | 
| computer-use-2025-01-24 | computer\_20250124 | 
| computer-use-2024-10-22 | computer\_20241022 | 

每种工具类型仅适用于模型的特定子集。提交模型不支持的工具类型会返回`400 invalid_request_error`带有诸如之类的消息`'claude-opus-4-7' does not support tool types: computer_20241022`。在发送请求之前，请在模型的 “*功能和特性*” 表中确认支持。

有关底层工具协议、完整操作词汇和提示工程指导，请参阅文档中的[Anthropic计算机使用](https://docs.anthropic.com/en/docs/build-with-claude/computer-use)。

## Anthropic 定义的工具
<a name="model-parameters-anthropic-anthropic-defined-tools"></a>

Anthropic提供了一组预定义的工具，Claude模型可以使用这些工具与计算机进行交互。指定Anthropic定义的工具时，`description`和`tool_schema`字段不是必需的，也不允许使用和字段。模型不会自动执行这些工具；您必须运行每个请求的操作并返回`tool_result`到Claude。要了解每个模型接受哪些工具，请参阅模型中的*功能和特征*表[模型一览](model-cards.md)；提交模型不支持的工具类型会返回`400 invalid_request_error`。


| Tool | 注意 | 
| --- | --- | 
|  <pre>{ <br />    "type": "computer_20251124", <br />    "name": "computer" <br />}</pre>  | 最新的计算机使用工具。与 `"anthropic_beta": ["computer-use-2025-11-24"]` 结合使用。 | 
|  <pre>{ <br />    "type": "computer_20250124", <br />    "name": "computer" <br />}</pre>  | 与 `"anthropic_beta": ["computer-use-2025-01-24"]` 结合使用。 | 
|  <pre>{ <br />    "type": "computer_20241022", <br />    "name": "computer" <br />}</pre>  | 遗产。与 `"anthropic_beta": ["computer-use-2024-10-22"]` 结合使用。 | 
|  <pre>{ <br />    "type": "text_editor_20250124", <br />    "name": "str_replace_based_edit_tool" <br />}</pre>  | 更新现有`str_replace_editor`工具。与`"anthropic_beta": ["computer-use-2025-01-24"]`或一起使用`["computer-use-2025-11-24"]`。 | 
|  <pre>{ <br />    "type": "text_editor_20241022", <br />    "name": "str_replace_editor" <br />}</pre>  | 遗产。与 `"anthropic_beta": ["computer-use-2024-10-22"]` 结合使用。 | 
|  <pre>{ <br />    "type": "bash_20250124", <br />    "name": "bash" <br />}</pre>  | 与`"anthropic_beta": ["computer-use-2025-01-24"]`或一起使用`["computer-use-2025-11-24"]`。 | 
|  <pre>{ <br />    "type": "bash_20241022", <br />    "name": "bash" <br />}</pre>  | 遗产。与 `"anthropic_beta": ["computer-use-2024-10-22"]` 结合使用。 | 

该`type`字段用于识别工具及其参数以进行验证；该`name`字段是显示给模型的工具名称。

如果要提示模型使用其中某个工具，可通过 `name` 字段明确指定该工具。该`name`字段在工具列表中必须是唯一的；您不能在同`name`一 API 调用中使用与Anthropic定义的工具相同的工具来定义工具。

## 自动工具调用清理（测试版）
<a name="model-parameters-anthropic-claude-automatic-tool-call-clearing"></a>

**警告**  
根据服务条款的定义，自动工具呼叫清算作为 “测试 AWS 服务” 提供。

**注意**  
Claude Sonnet 4/4 .5、Claude Haiku 4.5 和 Claude Opus 目前支持此功能。 4/4 1/4.5。

自动清除工具调用是 Anthropic Claude 模型的一项功能（测试版）。借助此功能，Claude 可以在您接近令牌限制时自动清除旧工具使用结果，从而在多回合刀具使用场景中实现更有效的上下文管理。要使用工具使用清理功能，您需要在 anthropic\_beta 请求参数的测试版标头列表中添加 `context-management-2025-06-27`。您还需要指定以下配置选项的用法`clear_tool_uses_20250919`并从中进行选择。

以下是 `clear_tool_uses_20250919` 上下文管理策略的可用控制项。所有控制项均为可选配置，或具有默认值：


| **配置选项** | **描述** | 
| --- | --- | 
| `trigger`<br />默认值：100000 个输入词元 | 定义何时激活上下文编辑策略。当提示超过此阈值后，清理操作将开始执行。您可以在 input\_tokens 或 tool\_uses 中指定此值。 | 
| `keep`<br />默认值：3 次工具使用 | 定义清除后要保留多少个最近的工具 use/result 对。API 会首先移除最早的工具交互，保留最新的工具交互。当模型需要获取最新的工具交互以高效推进对话时，此配置选项非常有用。 | 
| `clear_at_least`（可选） | 确保策略每次激活时，都会清理所指定的最少数量的词元。如果 API 无法清理所指定的最少数量的词元，则不会应用此策略。在需要判断为清理上下文而中断提示缓存这一操作是否值得时，此配置选项十分有用。 | 
| `exclude_tools`（可选） | 永远不应清理其工具使用情况和结果的工具名称的列表。此配置选项对于保存重要上下文很有用。 | 
| `clear_tool_inputs`（可选，默认值为 false） | 控制是否将工具调用参数与工具结果一起清理。默认情况下，仅清理工具结果，同时保留 Claude 的原始工具调用可见，如此一来，即便结果已被移除，Claude 也能查看执行过的操作。 | 

**注意**  
如果前缀包含工具，则工具清理操作将使缓存失效。

**重要**  
Amazon Bedro `web_search_20250305` ck 不支持 Anthropic 服务器工具。

------
#### [ Request ]

```
from anthropic import AnthropicBedrock

client = AnthropicBedrock()

response = client.beta.messages.create(
    betas=["context-management-2025-06-27"],
    model="claude-sonnet-4-20250514",
    max_tokens=4096,
    messages=[
        {
            "role": "user",
            "content": "Create a simple command line calculator app using Python"
       }
    ],
    tools=[
        {
            "type": "text_editor_20250728",
            "name": "str_replace_based_edit_tool",
            "max_characters": 10000
        }
    ],
    extra_body={
        "context_management": {
            "edits": [
                {
                    "type": "clear_tool_uses_20250919",
                # The below parameters are OPTIONAL:
                    # Trigger clearing when threshold is exceeded
                    "trigger": {
                        "type": "input_tokens",
                        "value": 30000
                    },
                    # Number of tool uses to keep after clearing
                    "keep": {
                        "type": "tool_uses",
                        "value": 3
                    },
                    # Optional: Clear at least this many tokens
                    "clear_at_least": {
                        "type": "input_tokens",
                        "value": 5000
                    },
                    # Exclude these tools uses from being cleared
                    "exclude_tools": ["str_replace_based_edit_tool"]
                }
            ]
       }
    }
 )
```

------
#### [ Response ]

```
{
    "id": "msg_123",
    "type": "message",
    "role": "assistant",
    "content": [
        {
            "type": "tool_use",
            "id": "toolu_456",
            "name": "data_analyzer",
            "input": {
                "data": "sample data"
            }
        }
    ],
    "context_management": {
        "applied_edits": [
            {
                "type": "clear_tool_uses_20250919",
                "cleared_tool_uses": 8,  # Number of tool use/result pairs that were cleared
                "cleared_input_tokens": 50000  # Total number of input tokens removed from the prompt
            }
        ]
    }
    "stop_reason": "tool_use",
    "usage": {
        "input_tokens": 150,
        "output_tokens": 50
    }
}
```

------
#### [ Streaming Response ]

```
data: {"type": "message_start", "message": {"id": "msg_123", "type": "message", "role": "assistant"}}

data: {"type": "content_block_start", "index": 0, "content_block": {"type": "tool_use", "id": "toolu_456", "name": "data_analyzer", "input": {}}}

data: {"type": "content_block_delta", "index": 0, "delta": {"type": "input_json_delta", "partial_json": "{\"data\": \"sample"}}

data: {"type": "content_block_delta", "index": 0, "delta": {"type": "input_json_delta", "partial_json": " data\"}"}}

data: {"type": "content_block_stop", "index": 0}

data: {"type": "message_delta", "delta": {"stop_reason": "tool_use"}}

data: {"type": "message_stop"}

{
  "type": "message_delta",
  "delta": {
    "stop_reason": "end_turn",
    "stop_sequence": null,
  },
  "usage": {
    "output_tokens": 1024
  },
  "context_management": {
    "applied_edits": [...],
  }
}
```

------

**注意**  
Bedrock 目前不支持 CountTokens API 上的`clear_tool_uses_20250919`上下文管理。

## 记忆工具（测试版）
<a name="model-parameters-anthropic-claude-memory-tool"></a>

**警告**  
根据服务条款的定义，记忆工具作为 “测试 AWS 服务” 提供。

Claude Sonnet 4.5 包括一个新的记忆工具。此工具为您提供了一种管理对话记忆的方法。使用此功能，您可以允许 Claude 通过提供对本地目录的访问权限在上下文窗口之外检索信息。此功能在测试版中可用。要使用此功能，必须在`anthropic_beta`参数`context-management-2025-06-27`中包含。

工具定义：

```
{
  "type": "memory_20250818",
  "name": "memory"
}
```

示例请求：

```
{
    "max_tokens": 2048,
    "anthropic_version": "bedrock-2023-05-31",
    "anthropic_beta": ["context-management-2025-06-27"],
    "tools": [{
        "type": "memory_20250818",
        "name": "memory"
    }],
    "messages": [
        {
            "role": "user",
            "content": [{"type": "text", "text": "Remember that my favorite color is blue and I work at Amazon?"}]
        }
    ]
}
```

示例响应：

```
{
    "id": "msg_vrtx_014mQ5ficCRB6PEa5k5sKqHd",
    "type": "message",
    "role": "assistant",
    "model": "claude-sonnet-4-20250514",
    "content": [
        {
            "type": "text",
            "text": "I'll start by checking your memory directory and then record this important information about you."
        },
        {
            "type": "tool_use",
            "id": "toolu_vrtx_01EU1UrCDigyPMRntr3VYvUB",
            "name": "memory",
            "input": {
                "command": "view",
                "path": "/memories"
            }
        }
    ],
    "stop_reason": "tool_use",
    "stop_sequence": null,
    "usage": {
        "input_tokens": 1403,
        "cache_creation_input_tokens": 0,
        "cache_read_input_tokens": 0,
        "output_tokens": 87
    },
    "context_management": {
        "applied_edits": []
    }
}
```

## 工具使用的成本注意事项
<a name="model-parameters-anthropic-claude-tool-use-cost"></a>

工具使用请求的定价基于以下因素：

1. 发送到模型的输入词元总数（包含在 tools 参数中）。

1. 生成的输出词元数。

工具的定价与所有其他 Claude API 请求的定价标准一致，但每次请求会产生额外词元。工具使用产生的额外词元来自以下各项：
+ API 请求中的 `tools` 参数。例如，工具名称、描述和架构。
+ API 请求和响应中的任何 `tool_use` 内容块。
+ API 请求中的任何 `tool_result` 内容块。

当您使用工具时，Anthropic 模型会自动包含一个支持工具使用的专用系统提示。下表列出了每个模型所需的工具使用词元的数量。此表不包括前文所述的额外词元。请注意，此表假设提供了至少一种工具。如果未提供任何工具，且工具选择设为“无”，则不会产生额外的系统提示词元。


| 模型 | 工具选择 | 工具使用系统提示词元计数 | 
| --- | --- | --- | 
| Claude Opus4.5<br />Claude Opus4.1<br />Claude Opus 4<br />Claude Sonnet 4.5<br />Claude Haiku 4.5<br />Claude Sonnet 4<br />Claude 3.7 Sonnet<br />Claude 3.5 Sonnet v2 | auto 或 none | 346 | 
| Claude Opus4.5<br />Claude Opus4.1<br />Claude Opus 4<br />Claude Sonnet 4.5<br />Claude Haiku 4.5<br />Claude Sonnet 4<br />Claude 3.7 Sonnet<br />Claude 3.5 Sonnet v2 | any 或 tool | 313 | 
| Claude 3.5 Sonnet | auto 或 none | 294 | 
| Claude 3.5 Sonnet | any 或 tool | 261 | 
| Claude 3 Opus | auto 或 none | 530 | 
| Claude 3 Opus | any 或 tool | 281 | 
| Claude 3 Sonnet | auto 或 none | 159 | 
| Claude 3 Sonnet | any 或 tool | 235 | 
| Claude 3 Haiku | auto 或 none | 264 | 
| Claude 3 Haiku | any 或 tool | 340 | 

## 工具搜索工具（测试版）
<a name="model-parameters-anthropic-claude-tool-search-tool"></a>

Tool Search Tool Claude 允许使用数百甚至数千种工具，而无需预先将其所有定义加载到上下文窗口中。与其立即声明所有工具，不如使用工具搜索机制标记它们`defer_loading: true`，然后仅Claude查找和加载所需的工具。

要访问此功能，必须在`anthropic_beta`参数`tool-search-tool-2025-10-19`中包含。请注意，此功能目前只能通过[InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html)和 [InvokeModelWithResponseStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithResponseStream.html)API 使用。

工具定义：

```
{
    "type": "tool_search_tool_regex",
    "name": "tool_search_tool_regex"
}
```

请求示例：

```
{
    "anthropic_version": "bedrock-2023-05-31",
    "anthropic_beta": [
        "tool-search-tool-2025-10-19"
    ],
    "max_tokens": 4096,
    "tools": [{
            "type": "tool_search_tool_regex",
            "name": "tool_search_tool_regex"
        },
        {
            "name": "get_weather",
            "description": "Get current weather for a location",
            "input_schema": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"]
                    }
                },
                "required": ["location"]
            },
            "defer_loading": true
        },
        {
            "name": "search_files",
            "description": "Search through files in the workspace",
            "input_schema": {
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string"
                    },
                    "file_types": {
                        "type": "array",
                        "items": {
                            "type": "string"
                        }
                    }
                },
                "required": ["query"]
            },
            "defer_loading": true
        }
    ],
    "messages": [{
        "role": "user",
        "content": "What's the weather in Seattle?"
    }]
}
```

响应示例

```
{
    "role": "assistant",
    "content": [{
            "type": "text",
            "text": "I'll search for the appropriate tools to help with this task."
        },
        {
            "type": "server_tool_use",
            "id": "srvtoolu_01ABC123",
            "name": "tool_search_tool_regex",
            "input": {
                "pattern": "weather"
            }
        },
        {
            "type": "tool_search_tool_result",
            "tool_use_id": "srvtoolu_01ABC123",
            "content": {
                "type": "tool_search_tool_search_result",
                "tool_references": [{
                    "type": "tool_reference",
                    "tool_name": "get_weather"
                }]
            }
        },
        {
            "type": "text",
            "text": "Now I can check the weather."
        },
        {
            "type": "tool_use",
            "id": "toolu_01XYZ789",
            "name": "get_weather",
            "input": {
                "location": "Seattle",
                "unit": "fahrenheit"
            }
        }
    ],
    "stop_reason": "tool_use"
}
```

直播示例

```
# Event 1: content_block_start(with complete server_tool_use block) {
    "type": "content_block_start",
    "index": 0,
    "content_block": {
        "type": "server_tool_use",
        "id": "srvtoolu_01ABC123",
        "name": "tool_search_tool_regex"
    }
}

# Event 2: content_block_delta(input JSON streamed) {
    "type": "content_block_delta",
    "index": 0,
    "delta": {
        "type": "input_json_delta",
        "partial_json": "{\"regex\": \".*weather.*\"}"
    }
}

# Event 3: content_block_stop(tool_use complete) {
    "type": "content_block_stop",
    "index": 0
}

# Event 4: content_block_start(COMPLETE result in single chunk) {
    "type": "content_block_start",
    "index": 1,
    "content_block": {
        "type": "tool_search_tool_result",
        "tool_use_id": "srvtoolu_01ABC123",
        "content": {
            "type": "tool_search_tool_search_result",
            "tool_references": [{
                "type": "tool_reference",
                "tool_name": "get_weather"
            }]
        }
    }
}

# Event 5: content_block_stop(result complete) {
    "type": "content_block_stop",
    "index": 1
}
```

**自定义工具搜索工具**  
您可以通过定义返回`tool_reference`块的工具来实现自定义工具搜索工具（例如，使用嵌入式）。自定义工具必须有，`defer_loading: false`而其他工具则应有`defer_loading: true`。当你定义自己的工具搜索工具时，它应该返回一个工具结果，其中包含指向你Claude要使用的工具的`tool_reference`内容块。

预期的客户定义的工具搜索工具结果响应格式：

```
{
    "type": "tool_result",
    "tool_use_id": "toolu_01ABC123",
    "content": [{
            "type": "tool_reference",
            "tool_name": "get_weather"
        },
        {
            "type": "tool_reference",
            "tool_name": "weather_forecast"
        }
    ]
}
```

`tool_name`必须与请求中定义的工具相匹配`defer_loading: true`。然后，Claude 将可以访问这些工具的完整架构。

**自定义搜索工具-详细示例**  
您可以通过定义返回`tool_reference`块的工具来实现自定义工具搜索工具（例如，使用嵌入或语义搜索）。除了正则表达式匹配之外，这还支持复杂的工具发现机制。

请求带有自定义 TST 的示例：

```
{
    "model": "claude-sonnet-4-5-20250929",
    "anthropic_version": "bedrock-2023-05-31",
    "anthropic_beta": ["tool-search-tool-2025-10-19"],
    "max_tokens": 4096,
    "tools": [{
            "name": "semantic_tool_search",
            "description": "Search for available tools using semantic similarity. Returns the most relevant tools for the given query.",
            "input_schema": {
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "Natural language description of what kind of tool is needed"
                    },
                    "top_k": {
                        "type": "integer",
                        "description": "Number of tools to return (default: 5)"
                    }
                },
                "required": ["query"]
            },
            "defer_loading": false
        },
        {
            "name": "get_weather",
            "description": "Get current weather for a location",
            "input_schema": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"]
                    }
                },
                "required": ["location"]
            },
            "defer_loading": true
        },
        {
            "name": "search_flights",
            "description": "Search for available flights between locations",
            "input_schema": {
                "type": "object",
                "properties": {
                    "origin": {
                        "type": "string"
                    },
                    "destination": {
                        "type": "string"
                    },
                    "date": {
                        "type": "string"
                    }
                },
                "required": ["origin", "destination", "date"]
            },
            "defer_loading": true
        }
    ],
    "messages": [{
        "role": "user",
        "content": "What's the weather forecast in Seattle for the next 3 days?"
    }]
}
```

Claude的响应（调用自定义 TST）：

```
{
    "role": "assistant",
    "content": [{
            "type": "text",
            "text": "I'll search for the appropriate tools to help with weather information."
        },
        {
            "type": "tool_use",
            "id": "toolu_01ABC123",
            "name": "semantic_tool_search",
            "input": {
                "query": "weather forecast multiple days",
                "top_k": 3
            }
        }
    ],
    "stop_reason": "tool_use"
}
```

**Customer-provided 工具结果**  
在工具库上执行语义搜索后，客户会返回匹配的工具引用：

```
{
    "role": "user",
    "content": [{
        "type": "tool_search_tool_result",
        "tool_use_id": "toolu_01ABC123",
        "content": {
            "type": "tool_search_tool_search_result",
            "tool_references": [{
                "type": "tool_reference",
                "tool_name": "get_weather"
            }]
        }
    }]
}
```

Claude的后续行动（使用发现的工具）

```
{
    "role": "assistant",
    "content": [{
            "type": "text",
            "text": "I found the forecast tool. Let me get the weather forecast for Seattle."
        },
        {
            "type": "tool_use",
            "id": "toolu_01DEF456",
            "name": "get_weather",
            "input": {
                "location": "Seattle, WA"
            }
        }
    ],
    "stop_reason": "tool_use"
}
```

**错误处理**
+ 所有工具（包括工具搜索工具）的设置`defer_loading: true`将引发 400 错误。
+ 在没有相应工具定义`tool_reference`的情况下传递 a 将引发 400 错误

## 工具使用示例（测试版）
<a name="model-parameters-anthropic-claude-tool-use-examples"></a>

Claude Opus4.5 在工具定义中支持用户提供的示例，以提高Claude工具使用性能。您可以提供完整函数调用的示例，其格式与实际 LLM 输出完全相同，无需转换为另一种格式。要使用此功能，必须在`anthropic_beta`参数`tool-examples-2025-10-29`中包含。

工具定义示例：

```
{
    "name": "get_weather",
    "description": "Get the current weather in a given location",
    "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"]
    },
    "input_examples": [{
            "location": "San Francisco, CA",
            "unit": "fahrenheit"
        },
        {
            "location": "Tokyo, Japan",
            "unit": "celsius"
        },
        {
            "location": "New York, NY"
        }
    ]
}
```

**验证规则**
+ 架构一致性：根据工具的不同，中的每个示例都`input_examples`必须有效。`input_schema`
  + 必须至少在一个示例中包含必填字段。
  + 字段类型必须与架构相匹配。
  + 枚举值必须来自允许的集合。
  + 如果验证失败，则返回 400 错误，详细说明哪个示例验证失败。
+ 数组要求：`input_examples`必须是数组（可以为空）。
  + 空数组`[]`是有效的，等同于省略该字段。
  + 仍然必须将单个示例封装在数组中：`[{...}]`
  + 长度限制：从每个工具定义开始，限制为 20 个示例。

错误示例：

```
// Invalid: Example doesn't match schema (missing required field)
{
    "type": "invalid_request_error",
    "message": "Tool 'get_weather' input_examples[0] is invalid: Missing required property 'location'"
}

// Invalid: Example has wrong type for field
{
    "type": "invalid_request_error",
    "message": "Tool 'search_products' input_examples[1] is invalid: Property 'filters.price_range.min' must be a number, got string"
}

// Invalid: input_examples on server-side tool
{
    "type": "invalid_request_error",
    "message": "input_examples is not supported for server-side tool"
}
```