## 统计消息中的 token 数

**post** `/v1/messages/count_tokens`

统计消息中的 token 数量。

Token Count API 可用于统计消息中的 token 数量（包括工具、图像和文档），而无需实际创建消息。

在我们的[用户指南](https://docs.claude.com/en/docs/build-with-claude/token-counting)中了解更多关于 token 计数的信息

### 请求体参数

- `messages: array of MessageParam`

  输入消息。

  我们的模型经过训练，可处理交替的 `user` 和 `assistant` 对话轮次。创建新 `Message` 时，您通过 `messages` 参数指定先前的对话轮次，然后模型生成对话中的下一条 `Message`。请求中连续的 `user` 或 `assistant` 轮次将被合并为单个轮次。

  每条输入消息必须是包含 `role` 和 `content` 的对象。您可以指定单条 `user` 角色消息，也可以包含多条 `user` 和 `assistant` 消息。

  如果最后一条消息使用 `assistant` 角色，响应内容将直接从该消息的内容继续。这可用于约束模型的部分响应。

  单条 `user` 消息示例：

  ```json
  [{"role": "user", "content": "Hello, Claude"}]
  ```

  多轮对话示例：

  ```json
  [
    {"role": "user", "content": "Hello there."},
    {"role": "assistant", "content": "Hi, I'm Claude. How can I help you?"},
    {"role": "user", "content": "Can you explain LLMs in plain English?"},
  ]
  ```

  Claude 部分填充响应示例：

  ```json
  [
    {"role": "user", "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"},
    {"role": "assistant", "content": "The best answer is ("},
  ]
  ```

  每条输入消息的 `content` 可以是单个 `string` 或内容块数组，每个块具有特定的 `type`。使用 `string` 作为 `content` 是包含一个类型为 `"text"` 的内容块的数组的简写。以下输入消息是等效的：

  ```json
  {"role": "user", "content": "Hello, Claude"}
  ```

  ```json
  {"role": "user", "content": [{"type": "text", "text": "Hello, Claude"}]}
  ```

  详见[输入示例](https://docs.claude.com/en/api/messages-examples)。

  请注意，如果您想包含[系统提示](https://docs.claude.com/en/docs/system-prompts)，可以使用顶级 `system` 参数 -- Messages API 中输入消息没有 `"system"` 角色。

  单个请求最多可包含 100,000 条消息。

  - `content: string or array of ContentBlockParam`

    - `string`

    - `array of ContentBlockParam`

      - `TextBlockParam object { text, type, cache_control, citations }`

        - `text: string`

        - `type: "text"`

          - `"text"`

        - `cache_control: optional CacheControlEphemeral`

          在此内容块创建缓存控制断点。

          - `type: "ephemeral"`

            - `"ephemeral"`

          - `ttl: optional "5m" or "1h"`

            缓存控制断点的生存时间。

            这可能是以下值之一：

            - `5m`: 5 minutes
            - `1h`: 1 hour

            默认为 `5m`。

            - `"5m"`

            - `"1h"`

        - `citations: optional array of TextCitationParam`

          - `CitationCharLocationParam object { cited_text, document_index, document_title, 3 more }`

            - `cited_text: string`

            - `document_index: number`

            - `document_title: string`

            - `end_char_index: number`

            - `start_char_index: number`

            - `type: "char_location"`

              - `"char_location"`

          - `CitationPageLocationParam object { cited_text, document_index, document_title, 3 more }`

            - `cited_text: string`

            - `document_index: number`

            - `document_title: string`

            - `end_page_number: number`

            - `start_page_number: number`

            - `type: "page_location"`

              - `"page_location"`

          - `CitationContentBlockLocationParam object { cited_text, document_index, document_title, 3 more }`

            - `cited_text: string`

              引用块范围的完整文本，已连接。

              始终等于 `content[start_block_index:end_block_index]` 内容的连接。文本块是最小可引用单元；此字段永远不会是单个块的子字符串。不计入输出 token，在后续轮次中发回时也不计入输入 token。

            - `document_index: number`

            - `document_title: string`

            - `end_block_index: number`

              源 `content` 数组中引用块范围的排他性 0 基结束索引。

              始终大于 `start_block_index`；单块引用的 `end_block_index = start_block_index + 1`。

            - `start_block_index: number`

              源 `content` 数组中第一个引用块的 0 基索引。

            - `type: "content_block_location"`

              - `"content_block_location"`

          - `CitationWebSearchResultLocationParam object { cited_text, encrypted_index, title, 2 more }`

            - `cited_text: string`

            - `encrypted_index: string`

            - `title: string`

            - `type: "web_search_result_location"`

              - `"web_search_result_location"`

            - `url: string`

          - `CitationSearchResultLocationParam object { cited_text, end_block_index, search_result_index, 4 more }`

            - `cited_text: string`

              引用块范围的完整文本，已连接。

              始终等于 `content[start_block_index:end_block_index]` 内容的连接。文本块是最小可引用单元；此字段永远不会是单个块的子字符串。不计入输出 token，在后续轮次中发回时也不计入输入 token。

            - `end_block_index: number`

              源 `content` 数组中引用块范围的排他性 0 基结束索引。

              始终大于 `start_block_index`；单块引用的 `end_block_index = start_block_index + 1`。

            - `search_result_index: number`

              在请求中所有 `search_result` 内容块中引用搜索结果的 0 基索引，按其在消息和工具结果中出现的顺序排列。

              与 `document_index` 分开计数；服务器端 Web 搜索结果不包含在此计数中。

            - `source: string`

            - `start_block_index: number`

              源 `content` 数组中第一个引用块的 0 基索引。

            - `title: string`

            - `type: "search_result_location"`

              - `"search_result_location"`

      - `ImageBlockParam object { source, type, cache_control }`

        - `source: Base64ImageSource or URLImageSource`

          - `Base64ImageSource object { data, media_type, type }`

            - `data: string`

            - `media_type: "image/jpeg" or "image/png" or "image/gif" or "image/webp"`

              - `"image/jpeg"`

              - `"image/png"`

              - `"image/gif"`

              - `"image/webp"`

            - `type: "base64"`

              - `"base64"`

          - `URLImageSource object { type, url }`

            - `type: "url"`

              - `"url"`

            - `url: string`

        - `type: "image"`

          - `"image"`

        - `cache_control: optional CacheControlEphemeral`

          在此内容块创建缓存控制断点。

      - `DocumentBlockParam object { source, type, cache_control, 3 more }`

        - `source: Base64PDFSource or PlainTextSource or ContentBlockSource or URLPDFSource`

          - `Base64PDFSource object { data, media_type, type }`

            - `data: string`

            - `media_type: "application/pdf"`

              - `"application/pdf"`

            - `type: "base64"`

              - `"base64"`

          - `PlainTextSource object { data, media_type, type }`

            - `data: string`

            - `media_type: "text/plain"`

              - `"text/plain"`

            - `type: "text"`

              - `"text"`

          - `ContentBlockSource object { content, type }`

            - `content: string or array of ContentBlockSourceContent`

              - `string`

              - `ContentBlockSourceContent = array of ContentBlockSourceContent`

                - `TextBlockParam object { text, type, cache_control, citations }`

                - `ImageBlockParam object { source, type, cache_control }`

            - `type: "content"`

              - `"content"`

          - `URLPDFSource object { type, url }`

            - `type: "url"`

              - `"url"`

            - `url: string`

        - `type: "document"`

          - `"document"`

        - `cache_control: optional CacheControlEphemeral`

          在此内容块创建缓存控制断点。

        - `citations: optional CitationsConfigParam`

          - `enabled: optional boolean`

        - `context: optional string`

        - `title: optional string`

      - `SearchResultBlockParam object { content, source, title, 3 more }`

        - `content: array of TextBlockParam`

          - `text: string`

          - `type: "text"`

          - `cache_control: optional CacheControlEphemeral`

            在此内容块创建缓存控制断点。

          - `citations: optional array of TextCitationParam`

        - `source: string`

        - `title: string`

        - `type: "search_result"`

          - `"search_result"`

        - `cache_control: optional CacheControlEphemeral`

          在此内容块创建缓存控制断点。

        - `citations: optional CitationsConfigParam`

      - `ThinkingBlockParam object { signature, thinking, type }`

        - `signature: string`

        - `thinking: string`

        - `type: "thinking"`

          - `"thinking"`

      - `RedactedThinkingBlockParam object { data, type }`

        - `data: string`

        - `type: "redacted_thinking"`

          - `"redacted_thinking"`

      - `ToolUseBlockParam object { id, input, name, 3 more }`

        - `id: string`

        - `input: map[unknown]`

        - `name: string`

        - `type: "tool_use"`

          - `"tool_use"`

        - `cache_control: optional CacheControlEphemeral`

          在此内容块创建缓存控制断点。

        - `caller: optional DirectCaller or ServerToolCaller or ServerToolCaller20260120`

          直接来自模型的工具调用。

          - `DirectCaller object { type }`

            直接来自模型的工具调用。

            - `type: "direct"`

              - `"direct"`

          - `ServerToolCaller object { tool_id, type }`

            由服务器端工具生成的工具调用。

            - `tool_id: string`

            - `type: "code_execution_20250825"`

              - `"code_execution_20250825"`

          - `ServerToolCaller20260120 object { tool_id, type }`

            - `tool_id: string`

            - `type: "code_execution_20260120"`

              - `"code_execution_20260120"`

      - `ToolResultBlockParam object { tool_use_id, type, cache_control, 2 more }`

        - `tool_use_id: string`

        - `type: "tool_result"`

          - `"tool_result"`

        - `cache_control: optional CacheControlEphemeral`

          在此内容块创建缓存控制断点。

        - `content: optional string or array of TextBlockParam or ImageBlockParam or SearchResultBlockParam or 2 more`

          - `string`

          - `array of TextBlockParam or ImageBlockParam or SearchResultBlockParam or 2 more`

            - `TextBlockParam object { text, type, cache_control, citations }`

            - `ImageBlockParam object { source, type, cache_control }`

            - `SearchResultBlockParam object { content, source, title, 3 more }`

            - `DocumentBlockParam object { source, type, cache_control, 3 more }`

            - `ToolReferenceBlockParam object { tool_name, type, cache_control }`

              可包含在 tool_result 内容中的工具引用块。

              - `tool_name: string`

              - `type: "tool_reference"`

                - `"tool_reference"`

              - `cache_control: optional CacheControlEphemeral`

                在此内容块创建缓存控制断点。

        - `is_error: optional boolean`

      - `ServerToolUseBlockParam object { id, input, name, 3 more }`

        - `id: string`

        - `input: map[unknown]`

        - `name: "web_search" or "web_fetch" or "code_execution" or 4 more`

          - `"web_search"`

          - `"web_fetch"`

          - `"code_execution"`

          - `"bash_code_execution"`

          - `"text_editor_code_execution"`

          - `"tool_search_tool_regex"`

          - `"tool_search_tool_bm25"`

        - `type: "server_tool_use"`

          - `"server_tool_use"`

        - `cache_control: optional CacheControlEphemeral`

          在此内容块创建缓存控制断点。

        - `caller: optional DirectCaller or ServerToolCaller or ServerToolCaller20260120`

          直接来自模型的工具调用。

          - `DirectCaller object { type }`

            直接来自模型的工具调用。

          - `ServerToolCaller object { tool_id, type }`

            由服务器端工具生成的工具调用。

          - `ServerToolCaller20260120 object { tool_id, type }`

      - `WebSearchToolResultBlockParam object { content, tool_use_id, type, 2 more }`

        - `content: WebSearchToolResultBlockParamContent`

          - `WebSearchToolResultBlockItem = array of WebSearchResultBlockParam`

            - `encrypted_content: string`

            - `title: string`

            - `type: "web_search_result"`

              - `"web_search_result"`

            - `url: string`

            - `page_age: optional string`

          - `WebSearchToolRequestError object { error_code, type }`

            - `error_code: WebSearchToolResultErrorCode`

              - `"invalid_tool_input"`

              - `"unavailable"`

              - `"max_uses_exceeded"`

              - `"too_many_requests"`

              - `"query_too_long"`

              - `"request_too_large"`

            - `type: "web_search_tool_result_error"`

              - `"web_search_tool_result_error"`

        - `tool_use_id: string`

        - `type: "web_search_tool_result"`

          - `"web_search_tool_result"`

        - `cache_control: optional CacheControlEphemeral`

          在此内容块创建缓存控制断点。

        - `caller: optional DirectCaller or ServerToolCaller or ServerToolCaller20260120`

          直接来自模型的工具调用。

          - `DirectCaller object { type }`

            直接来自模型的工具调用。

          - `ServerToolCaller object { tool_id, type }`

            由服务器端工具生成的工具调用。

          - `ServerToolCaller20260120 object { tool_id, type }`

      - `WebFetchToolResultBlockParam object { content, tool_use_id, type, 2 more }`

        - `content: WebFetchToolResultErrorBlockParam or WebFetchBlockParam`

          - `WebFetchToolResultErrorBlockParam object { error_code, type }`

            - `error_code: WebFetchToolResultErrorCode`

              - `"invalid_tool_input"`

              - `"url_too_long"`

              - `"url_not_allowed"`

              - `"url_not_accessible"`

              - `"unsupported_content_type"`

              - `"too_many_requests"`

              - `"max_uses_exceeded"`

              - `"unavailable"`

            - `type: "web_fetch_tool_result_error"`

              - `"web_fetch_tool_result_error"`

          - `WebFetchBlockParam object { content, type, url, retrieved_at }`

            - `content: DocumentBlockParam`

            - `type: "web_fetch_result"`

              - `"web_fetch_result"`

            - `url: string`

              获取的内容 URL

            - `retrieved_at: optional string`

              获取内容时的 ISO 8601 时间戳

        - `tool_use_id: string`

        - `type: "web_fetch_tool_result"`

          - `"web_fetch_tool_result"`

        - `cache_control: optional CacheControlEphemeral`

          在此内容块创建缓存控制断点。

        - `caller: optional DirectCaller or ServerToolCaller or ServerToolCaller20260120`

          直接来自模型的工具调用。

          - `DirectCaller object { type }`

            直接来自模型的工具调用。

          - `ServerToolCaller object { tool_id, type }`

            由服务器端工具生成的工具调用。

          - `ServerToolCaller20260120 object { tool_id, type }`

      - `CodeExecutionToolResultBlockParam object { content, tool_use_id, type, cache_control }`

        - `content: CodeExecutionToolResultBlockParamContent`

          PFC + web_search 结果的带加密标准输出的代码执行结果。

          - `CodeExecutionToolResultErrorParam object { error_code, type }`

            - `error_code: CodeExecutionToolResultErrorCode`

              - `"invalid_tool_input"`

              - `"unavailable"`

              - `"too_many_requests"`

              - `"execution_time_exceeded"`

            - `type: "code_execution_tool_result_error"`

              - `"code_execution_tool_result_error"`

          - `CodeExecutionResultBlockParam object { content, return_code, stderr, 2 more }`

            - `content: array of CodeExecutionOutputBlockParam`

              - `file_id: string`

              - `type: "code_execution_output"`

                - `"code_execution_output"`

            - `return_code: number`

            - `stderr: string`

            - `stdout: string`

            - `type: "code_execution_result"`

              - `"code_execution_result"`

          - `EncryptedCodeExecutionResultBlockParam object { content, encrypted_stdout, return_code, 2 more }`

            PFC + web_search 结果的带加密标准输出的代码执行结果。

            - `content: array of CodeExecutionOutputBlockParam`

              - `file_id: string`

              - `type: "code_execution_output"`

            - `encrypted_stdout: string`

            - `return_code: number`

            - `stderr: string`

            - `type: "encrypted_code_execution_result"`

              - `"encrypted_code_execution_result"`

        - `tool_use_id: string`

        - `type: "code_execution_tool_result"`

          - `"code_execution_tool_result"`

        - `cache_control: optional CacheControlEphemeral`

          在此内容块创建缓存控制断点。

      - `BashCodeExecutionToolResultBlockParam object { content, tool_use_id, type, cache_control }`

        - `content: BashCodeExecutionToolResultErrorParam or BashCodeExecutionResultBlockParam`

          - `BashCodeExecutionToolResultErrorParam object { error_code, type }`

            - `error_code: BashCodeExecutionToolResultErrorCode`

              - `"invalid_tool_input"`

              - `"unavailable"`

              - `"too_many_requests"`

              - `"execution_time_exceeded"`

              - `"output_file_too_large"`

            - `type: "bash_code_execution_tool_result_error"`

              - `"bash_code_execution_tool_result_error"`

          - `BashCodeExecutionResultBlockParam object { content, return_code, stderr, 2 more }`

            - `content: array of BashCodeExecutionOutputBlockParam`

              - `file_id: string`

              - `type: "bash_code_execution_output"`

                - `"bash_code_execution_output"`

            - `return_code: number`

            - `stderr: string`

            - `stdout: string`

            - `type: "bash_code_execution_result"`

              - `"bash_code_execution_result"`

        - `tool_use_id: string`

        - `type: "bash_code_execution_tool_result"`

          - `"bash_code_execution_tool_result"`

        - `cache_control: optional CacheControlEphemeral`

          在此内容块创建缓存控制断点。

      - `TextEditorCodeExecutionToolResultBlockParam object { content, tool_use_id, type, cache_control }`

        - `content: TextEditorCodeExecutionToolResultErrorParam or TextEditorCodeExecutionViewResultBlockParam or TextEditorCodeExecutionCreateResultBlockParam or TextEditorCodeExecutionStrReplaceResultBlockParam`

          - `TextEditorCodeExecutionToolResultErrorParam object { error_code, type, error_message }`

            - `error_code: TextEditorCodeExecutionToolResultErrorCode`

              - `"invalid_tool_input"`

              - `"unavailable"`

              - `"too_many_requests"`

              - `"execution_time_exceeded"`

              - `"file_not_found"`

            - `type: "text_editor_code_execution_tool_result_error"`

              - `"text_editor_code_execution_tool_result_error"`

            - `error_message: optional string`

          - `TextEditorCodeExecutionViewResultBlockParam object { content, file_type, type, 3 more }`

            - `content: string`

            - `file_type: "text" or "image" or "pdf"`

              - `"text"`

              - `"image"`

              - `"pdf"`

            - `type: "text_editor_code_execution_view_result"`

              - `"text_editor_code_execution_view_result"`

            - `num_lines: optional number`

            - `start_line: optional number`

            - `total_lines: optional number`

          - `TextEditorCodeExecutionCreateResultBlockParam object { is_file_update, type }`

            - `is_file_update: boolean`

            - `type: "text_editor_code_execution_create_result"`

              - `"text_editor_code_execution_create_result"`

          - `TextEditorCodeExecutionStrReplaceResultBlockParam object { type, lines, new_lines, 3 more }`

            - `type: "text_editor_code_execution_str_replace_result"`

              - `"text_editor_code_execution_str_replace_result"`

            - `lines: optional array of string`

            - `new_lines: optional number`

            - `new_start: optional number`

            - `old_lines: optional number`

            - `old_start: optional number`

        - `tool_use_id: string`

        - `type: "text_editor_code_execution_tool_result"`

          - `"text_editor_code_execution_tool_result"`

        - `cache_control: optional CacheControlEphemeral`

          在此内容块创建缓存控制断点。

      - `ToolSearchToolResultBlockParam object { content, tool_use_id, type, cache_control }`

        - `content: ToolSearchToolResultErrorParam or ToolSearchToolSearchResultBlockParam`

          - `ToolSearchToolResultErrorParam object { error_code, type }`

            - `error_code: ToolSearchToolResultErrorCode`

              - `"invalid_tool_input"`

              - `"unavailable"`

              - `"too_many_requests"`

              - `"execution_time_exceeded"`

            - `type: "tool_search_tool_result_error"`

              - `"tool_search_tool_result_error"`

          - `ToolSearchToolSearchResultBlockParam object { tool_references, type }`

            - `tool_references: array of ToolReferenceBlockParam`

              - `tool_name: string`

              - `type: "tool_reference"`

              - `cache_control: optional CacheControlEphemeral`

                在此内容块创建缓存控制断点。

            - `type: "tool_search_tool_search_result"`

              - `"tool_search_tool_search_result"`

        - `tool_use_id: string`

        - `type: "tool_search_tool_result"`

          - `"tool_search_tool_result"`

        - `cache_control: optional CacheControlEphemeral`

          在此内容块创建缓存控制断点。

      - `ContainerUploadBlockParam object { file_id, type, cache_control }`

        表示要上传到容器的文件的内容块
        通过此块上传的文件将在容器的输入目录中可用。

        - `file_id: string`

        - `type: "container_upload"`

          - `"container_upload"`

        - `cache_control: optional CacheControlEphemeral`

          在此内容块创建缓存控制断点。

  - `role: "user" or "assistant"`

    - `"user"`

    - `"assistant"`

- `model: Model`

  将完成您的提示的模型。

  详见[模型](https://docs.anthropic.com/en/docs/models-overview)了解更多信息和选项。

  - `"claude-opus-4-7" or "claude-mythos-preview" or "claude-opus-4-6" or 14 more`

    将完成您的提示的模型。

    详见[模型](https://docs.anthropic.com/en/docs/models-overview)了解更多信息和选项。

    - `"claude-opus-4-7"`

      用于长时间运行的智能体和编程的前沿智能

    - `"claude-mythos-preview"`

      新一代智能，在编程和网络安全方面最强

    - `"claude-opus-4-6"`

      用于长时间运行的智能体和编程的前沿智能

    - `"claude-sonnet-4-6"`

      速度与智能的最佳组合

    - `"claude-haiku-4-5"`

      具有接近前沿智能的最快模型

    - `"claude-haiku-4-5-20251001"`

      具有接近前沿智能的最快模型

    - `"claude-opus-4-5"`

      结合最高智能与实用性能的高级模型

    - `"claude-opus-4-5-20251101"`

      结合最高智能与实用性能的高级模型

    - `"claude-sonnet-4-5"`

      用于智能体和编程的高性能模型

    - `"claude-sonnet-4-5-20250929"`

      用于智能体和编程的高性能模型

    - `"claude-opus-4-1"`

      用于专业复杂任务的卓越模型

    - `"claude-opus-4-1-20250805"`

      用于专业复杂任务的卓越模型

    - `"claude-opus-4-0"`

      用于复杂任务的强大模型

    - `"claude-opus-4-20250514"`

      用于复杂任务的强大模型

    - `"claude-sonnet-4-0"`

      具有扩展思考能力的高性能模型

    - `"claude-sonnet-4-20250514"`

      具有扩展思考能力的高性能模型

    - `"claude-3-haiku-20240307"`

      快速且经济高效的模型

  - `string`

- `cache_control: optional CacheControlEphemeral`

  顶级缓存控制自动将 cache_control 标记应用于请求中最后一个可缓存块。

- `output_config: optional OutputConfig`

  模型输出的配置选项，例如输出格式。

  - `effort: optional "low" or "medium" or "high" or 2 more`

    所有可用的努力级别。

    - `"low"`

    - `"medium"`

    - `"high"`

    - `"xhigh"`

    - `"max"`

  - `format: optional JSONOutputFormat`

    用于指定 Claude 响应输出格式的模式。详见[结构化输出](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)

    - `schema: map[unknown]`

      格式的 JSON 模式

    - `type: "json_schema"`

      - `"json_schema"`

- `system: optional string or array of TextBlockParam`

  系统提示。

  系统提示是一种向 Claude 提供上下文和指令的方式，例如指定特定目标或角色。请参阅我们的[系统提示指南](https://docs.claude.com/en/docs/system-prompts)。

  - `string`

  - `array of TextBlockParam`

    - `text: string`

    - `type: "text"`

    - `cache_control: optional CacheControlEphemeral`

      在此内容块创建缓存控制断点。

    - `citations: optional array of TextCitationParam`

- `thinking: optional ThinkingConfigParam`

  启用 Claude 扩展思考的配置。

  启用后，响应包含 `thinking` 内容块，显示 Claude 在最终答案之前的思考过程。需要最少 1,024 个 token 的预算，并计入您的 `max_tokens` 限制。

  详见[扩展思考](https://docs.claude.com/en/docs/build-with-claude/extended-thinking)了解更多详情。

  - `ThinkingConfigEnabled object { budget_tokens, type, display }`

    - `budget_tokens: number`

      确定 Claude 可用于其内部推理过程的 token 数量。较大的预算可以实现对复杂问题的更彻底分析，提高响应质量。

      必须 ≥1024 且小于 `max_tokens`。

      详见[扩展思考](https://docs.claude.com/en/docs/build-with-claude/extended-thinking)了解更多详情。

    - `type: "enabled"`

      - `"enabled"`

    - `display: optional "summarized" or "omitted"`

      控制思考内容在响应中的显示方式。设置为 `summarized` 时，正常返回思考内容。设置为 `omitted` 时，思考内容被编辑但返回签名以保持多轮连续性。默认为 `summarized`。

      - `"summarized"`

      - `"omitted"`

  - `ThinkingConfigDisabled object { type }`

    - `type: "disabled"`

      - `"disabled"`

  - `ThinkingConfigAdaptive object { type, display }`

    - `type: "adaptive"`

      - `"adaptive"`

    - `display: optional "summarized" or "omitted"`

      控制思考内容在响应中的显示方式。设置为 `summarized` 时，正常返回思考内容。设置为 `omitted` 时，思考内容被编辑但返回签名以保持多轮连续性。默认为 `summarized`。

      - `"summarized"`

      - `"omitted"`

- `tool_choice: optional ToolChoice`

  模型应如何使用提供的工具。模型可以使用特定工具、任何可用工具、自行决定或完全不使用工具。

  - `ToolChoiceAuto object { type, disable_parallel_tool_use }`

    模型将自动决定是否使用工具。

    - `type: "auto"`

      - `"auto"`

    - `disable_parallel_tool_use: optional boolean`

      是否禁用并行工具使用。

      默认为 `false`。如果设置为 `true`，模型将最多输出一个工具使用。

  - `ToolChoiceAny object { type, disable_parallel_tool_use }`

    模型将使用任何可用工具。

    - `type: "any"`

      - `"any"`

    - `disable_parallel_tool_use: optional boolean`

      是否禁用并行工具使用。

      默认为 `false`。如果设置为 `true`，模型将恰好输出一个工具使用。

  - `ToolChoiceTool object { name, type, disable_parallel_tool_use }`

    模型将使用 `tool_choice.name` 指定的工具。

    - `name: string`

      要使用的工具的名称。

    - `type: "tool"`

      - `"tool"`

    - `disable_parallel_tool_use: optional boolean`

      是否禁用并行工具使用。

      默认为 `false`。如果设置为 `true`，模型将恰好输出一个工具使用。

  - `ToolChoiceNone object { type }`

    模型将不被允许使用工具。

    - `type: "none"`

      - `"none"`

- `tools: optional array of MessageCountTokensTool`

  模型可能使用的工具定义。

  如果您在 API 请求中包含 `tools`，模型可能会返回表示模型使用这些工具的 `tool_use` 内容块。然后，您可以使用模型生成的工具输入运行这些工具，并可选地使用 `tool_result` 内容块将结果返回给模型。

  有两种类型的工具：**客户端工具**和**服务器端工具**。以下描述的行为适用于客户端工具。有关[服务器端工具](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview#server-tools)，请参阅其各自的文档，因为每个工具都有自己的行为（例如 [Web 搜索工具](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool)）。

  每个工具定义包括：

  * `name`: 工具名称。
  * `description`: 可选但强烈推荐的工具描述。
  * `input_schema`：工具 `input` 形状的 [JSON schema](https://json-schema.org/draft/2020-12)，模型将在 `tool_use` 输出内容块中生成该形状。

  例如，如果您将 `tools` 定义为：

  ```json
  [
    {
      "name": "get_stock_price",
      "description": "Get the current stock price for a given ticker symbol.",
      "input_schema": {
        "type": "object",
        "properties": {
          "ticker": {
            "type": "string",
            "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
          }
        },
        "required": ["ticker"]
      }
    }
  ]
  ```

  然后询问模型"今天标普 500 指数是多少？"，模型可能会在响应中生成如下 `tool_use` 内容块：

  ```json
  [
    {
      "type": "tool_use",
      "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
      "name": "get_stock_price",
      "input": { "ticker": "^GSPC" }
    }
  ]
  ```

  然后您可以使用 `{"ticker": "^GSPC"}` 作为输入运行您的 `get_stock_price` 工具，并在后续 `user` 消息中将以下内容返回给模型：

  ```json
  [
    {
      "type": "tool_result",
      "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
      "content": "259.75 USD"
    }
  ]
  ```

  工具可用于包含运行客户端工具和函数的工作流，或更一般地说，当您希望模型生成特定 JSON 结构的输出时。

  详见我们的[指南](https://docs.claude.com/en/docs/tool-use)了解更多详情。

  - `Tool object { input_schema, name, allowed_callers, 7 more }`

    - `input_schema: object { type, properties, required }`

      此工具输入的 [JSON schema](https://json-schema.org/draft/2020-12)。

      这定义了您的工具接受和模型将生成的 `input` 的形状。

      - `type: "object"`

        - `"object"`

      - `properties: optional map[unknown]`

      - `required: optional array of string`

    - `name: string`

      工具名称。

      这是模型和 `tool_use` 块中调用工具的方式。

    - `allowed_callers: optional array of "direct" or "code_execution_20250825" or "code_execution_20260120"`

      - `"direct"`

      - `"code_execution_20250825"`

      - `"code_execution_20260120"`

    - `cache_control: optional CacheControlEphemeral`

      在此内容块创建缓存控制断点。

    - `defer_loading: optional boolean`

      如果为 true，工具不会包含在初始系统提示中。仅在通过工具搜索的 tool_reference 返回时加载。

    - `description: optional string`

      此工具的功能描述。

      工具描述应尽可能详细。模型拥有的关于工具功能和使用方式的信息越多，其表现就越好。您可以使用自然语言描述来强调工具输入 JSON 模式的重要方面。

    - `eager_input_streaming: optional boolean`

      为此工具启用即时输入流。当为 true 时，工具输入参数将在生成时增量流式传输，类型将即时推断，而不是缓冲完整的 JSON 输出。当为 false 时，即使细粒度工具流 beta 处于活动状态，也会禁用此工具的流。当为 null（默认）时，使用基于 beta 头的默认行为。

    - `input_examples: optional array of map[unknown]`

    - `strict: optional boolean`

      当为 true 时，保证对工具名称和输入进行模式验证

    - `type: optional "custom"`

      - `"custom"`

  - `ToolBash20250124 object { name, type, allowed_callers, 4 more }`

    - `name: "bash"`

      工具名称。

      这是模型和 `tool_use` 块中调用工具的方式。

      - `"bash"`

    - `type: "bash_20250124"`

      - `"bash_20250124"`

    - `allowed_callers: optional array of "direct" or "code_execution_20250825" or "code_execution_20260120"`

      - `"direct"`

      - `"code_execution_20250825"`

      - `"code_execution_20260120"`

    - `cache_control: optional CacheControlEphemeral`

      在此内容块创建缓存控制断点。

    - `defer_loading: optional boolean`

      如果为 true，工具不会包含在初始系统提示中。仅在通过工具搜索的 tool_reference 返回时加载。

    - `input_examples: optional array of map[unknown]`

    - `strict: optional boolean`

      当为 true 时，保证对工具名称和输入进行模式验证

  - `CodeExecutionTool20250522 object { name, type, allowed_callers, 3 more }`

    - `name: "code_execution"`

      工具名称。

      这是模型和 `tool_use` 块中调用工具的方式。

      - `"code_execution"`

    - `type: "code_execution_20250522"`

      - `"code_execution_20250522"`

    - `allowed_callers: optional array of "direct" or "code_execution_20250825" or "code_execution_20260120"`

      - `"direct"`

      - `"code_execution_20250825"`

      - `"code_execution_20260120"`

    - `cache_control: optional CacheControlEphemeral`

      在此内容块创建缓存控制断点。

    - `defer_loading: optional boolean`

      如果为 true，工具不会包含在初始系统提示中。仅在通过工具搜索的 tool_reference 返回时加载。

    - `strict: optional boolean`

      当为 true 时，保证对工具名称和输入进行模式验证

  - `CodeExecutionTool20250825 object { name, type, allowed_callers, 3 more }`

    - `name: "code_execution"`

      工具名称。

      这是模型和 `tool_use` 块中调用工具的方式。

      - `"code_execution"`

    - `type: "code_execution_20250825"`

      - `"code_execution_20250825"`

    - `allowed_callers: optional array of "direct" or "code_execution_20250825" or "code_execution_20260120"`

      - `"direct"`

      - `"code_execution_20250825"`

      - `"code_execution_20260120"`

    - `cache_control: optional CacheControlEphemeral`

      在此内容块创建缓存控制断点。

    - `defer_loading: optional boolean`

      如果为 true，工具不会包含在初始系统提示中。仅在通过工具搜索的 tool_reference 返回时加载。

    - `strict: optional boolean`

      当为 true 时，保证对工具名称和输入进行模式验证

  - `CodeExecutionTool20260120 object { name, type, allowed_callers, 3 more }`

    具有 REPL 状态持久化的代码执行工具（守护进程模式 + gVisor 检查点）。

    - `name: "code_execution"`

      工具名称。

      这是模型和 `tool_use` 块中调用工具的方式。

      - `"code_execution"`

    - `type: "code_execution_20260120"`

      - `"code_execution_20260120"`

    - `allowed_callers: optional array of "direct" or "code_execution_20250825" or "code_execution_20260120"`

      - `"direct"`

      - `"code_execution_20250825"`

      - `"code_execution_20260120"`

    - `cache_control: optional CacheControlEphemeral`

      在此内容块创建缓存控制断点。

    - `defer_loading: optional boolean`

      如果为 true，工具不会包含在初始系统提示中。仅在通过工具搜索的 tool_reference 返回时加载。

    - `strict: optional boolean`

      当为 true 时，保证对工具名称和输入进行模式验证

  - `MemoryTool20250818 object { name, type, allowed_callers, 4 more }`

    - `name: "memory"`

      工具名称。

      这是模型和 `tool_use` 块中调用工具的方式。

      - `"memory"`

    - `type: "memory_20250818"`

      - `"memory_20250818"`

    - `allowed_callers: optional array of "direct" or "code_execution_20250825" or "code_execution_20260120"`

      - `"direct"`

      - `"code_execution_20250825"`

      - `"code_execution_20260120"`

    - `cache_control: optional CacheControlEphemeral`

      在此内容块创建缓存控制断点。

    - `defer_loading: optional boolean`

      如果为 true，工具不会包含在初始系统提示中。仅在通过工具搜索的 tool_reference 返回时加载。

    - `input_examples: optional array of map[unknown]`

    - `strict: optional boolean`

      当为 true 时，保证对工具名称和输入进行模式验证

  - `ToolTextEditor20250124 object { name, type, allowed_callers, 4 more }`

    - `name: "str_replace_editor"`

      工具名称。

      这是模型和 `tool_use` 块中调用工具的方式。

      - `"str_replace_editor"`

    - `type: "text_editor_20250124"`

      - `"text_editor_20250124"`

    - `allowed_callers: optional array of "direct" or "code_execution_20250825" or "code_execution_20260120"`

      - `"direct"`

      - `"code_execution_20250825"`

      - `"code_execution_20260120"`

    - `cache_control: optional CacheControlEphemeral`

      在此内容块创建缓存控制断点。

    - `defer_loading: optional boolean`

      如果为 true，工具不会包含在初始系统提示中。仅在通过工具搜索的 tool_reference 返回时加载。

    - `input_examples: optional array of map[unknown]`

    - `strict: optional boolean`

      当为 true 时，保证对工具名称和输入进行模式验证

  - `ToolTextEditor20250429 object { name, type, allowed_callers, 4 more }`

    - `name: "str_replace_based_edit_tool"`

      工具名称。

      这是模型和 `tool_use` 块中调用工具的方式。

      - `"str_replace_based_edit_tool"`

    - `type: "text_editor_20250429"`

      - `"text_editor_20250429"`

    - `allowed_callers: optional array of "direct" or "code_execution_20250825" or "code_execution_20260120"`

      - `"direct"`

      - `"code_execution_20250825"`

      - `"code_execution_20260120"`

    - `cache_control: optional CacheControlEphemeral`

      在此内容块创建缓存控制断点。

    - `defer_loading: optional boolean`

      如果为 true，工具不会包含在初始系统提示中。仅在通过工具搜索的 tool_reference 返回时加载。

    - `input_examples: optional array of map[unknown]`

    - `strict: optional boolean`

      当为 true 时，保证对工具名称和输入进行模式验证

  - `ToolTextEditor20250728 object { name, type, allowed_callers, 5 more }`

    - `name: "str_replace_based_edit_tool"`

      工具名称。

      这是模型和 `tool_use` 块中调用工具的方式。

      - `"str_replace_based_edit_tool"`

    - `type: "text_editor_20250728"`

      - `"text_editor_20250728"`

    - `allowed_callers: optional array of "direct" or "code_execution_20250825" or "code_execution_20260120"`

      - `"direct"`

      - `"code_execution_20250825"`

      - `"code_execution_20260120"`

    - `cache_control: optional CacheControlEphemeral`

      在此内容块创建缓存控制断点。

    - `defer_loading: optional boolean`

      如果为 true，工具不会包含在初始系统提示中。仅在通过工具搜索的 tool_reference 返回时加载。

    - `input_examples: optional array of map[unknown]`

    - `max_characters: optional number`

      查看文件时显示的最大字符数。如果未指定，默认显示完整文件。

    - `strict: optional boolean`

      当为 true 时，保证对工具名称和输入进行模式验证

  - `WebSearchTool20250305 object { name, type, allowed_callers, 7 more }`

    - `name: "web_search"`

      工具名称。

      这是模型和 `tool_use` 块中调用工具的方式。

      - `"web_search"`

    - `type: "web_search_20250305"`

      - `"web_search_20250305"`

    - `allowed_callers: optional array of "direct" or "code_execution_20250825" or "code_execution_20260120"`

      - `"direct"`

      - `"code_execution_20250825"`

      - `"code_execution_20260120"`

    - `allowed_domains: optional array of string`

      如果提供，只有这些域名会包含在结果中。不能与 `blocked_domains` 一起使用。

    - `blocked_domains: optional array of string`

      如果提供，这些域名永远不会出现在结果中。不能与 `allowed_domains` 一起使用。

    - `cache_control: optional CacheControlEphemeral`

      在此内容块创建缓存控制断点。

    - `defer_loading: optional boolean`

      如果为 true，工具不会包含在初始系统提示中。仅在通过工具搜索的 tool_reference 返回时加载。

    - `max_uses: optional number`

      工具在 API 请求中可使用的最大次数。

    - `strict: optional boolean`

      当为 true 时，保证对工具名称和输入进行模式验证

    - `user_location: optional UserLocation`

      用户位置参数。用于提供更相关的搜索结果。

      - `type: "approximate"`

        - `"approximate"`

      - `city: optional string`

        用户的城市。

      - `country: optional string`

        用户的两字母 [ISO 国家代码](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)。

      - `region: optional string`

        用户的区域。

      - `timezone: optional string`

        用户的 [IANA 时区](https://nodatime.org/TimeZones)。

  - `WebFetchTool20250910 object { name, type, allowed_callers, 8 more }`

    - `name: "web_fetch"`

      工具名称。

      这是模型和 `tool_use` 块中调用工具的方式。

      - `"web_fetch"`

    - `type: "web_fetch_20250910"`

      - `"web_fetch_20250910"`

    - `allowed_callers: optional array of "direct" or "code_execution_20250825" or "code_execution_20260120"`

      - `"direct"`

      - `"code_execution_20250825"`

      - `"code_execution_20260120"`

    - `allowed_domains: optional array of string`

      允许获取的域名列表

    - `blocked_domains: optional array of string`

      阻止获取的域名列表

    - `cache_control: optional CacheControlEphemeral`

      在此内容块创建缓存控制断点。

    - `citations: optional CitationsConfigParam`

      获取文档的引用配置。默认禁用引用。

    - `defer_loading: optional boolean`

      如果为 true，工具不会包含在初始系统提示中。仅在通过工具搜索的 tool_reference 返回时加载。

    - `max_content_tokens: optional number`

      在上下文中包含网页文本内容所使用的最大 token 数量。该限制是近似的，不适用于 PDF 等二进制内容。

    - `max_uses: optional number`

      工具在 API 请求中可使用的最大次数。

    - `strict: optional boolean`

      当为 true 时，保证对工具名称和输入进行模式验证

  - `WebSearchTool20260209 object { name, type, allowed_callers, 7 more }`

    - `name: "web_search"`

      工具名称。

      这是模型和 `tool_use` 块中调用工具的方式。

      - `"web_search"`

    - `type: "web_search_20260209"`

      - `"web_search_20260209"`

    - `allowed_callers: optional array of "direct" or "code_execution_20250825" or "code_execution_20260120"`

      - `"direct"`

      - `"code_execution_20250825"`

      - `"code_execution_20260120"`

    - `allowed_domains: optional array of string`

      如果提供，只有这些域名会包含在结果中。不能与 `blocked_domains` 一起使用。

    - `blocked_domains: optional array of string`

      如果提供，这些域名永远不会出现在结果中。不能与 `allowed_domains` 一起使用。

    - `cache_control: optional CacheControlEphemeral`

      在此内容块创建缓存控制断点。

    - `defer_loading: optional boolean`

      如果为 true，工具不会包含在初始系统提示中。仅在通过工具搜索的 tool_reference 返回时加载。

    - `max_uses: optional number`

      工具在 API 请求中可使用的最大次数。

    - `strict: optional boolean`

      当为 true 时，保证对工具名称和输入进行模式验证

    - `user_location: optional UserLocation`

      用户位置参数。用于提供更相关的搜索结果。

  - `WebFetchTool20260209 object { name, type, allowed_callers, 8 more }`

    - `name: "web_fetch"`

      工具名称。

      这是模型和 `tool_use` 块中调用工具的方式。

      - `"web_fetch"`

    - `type: "web_fetch_20260209"`

      - `"web_fetch_20260209"`

    - `allowed_callers: optional array of "direct" or "code_execution_20250825" or "code_execution_20260120"`

      - `"direct"`

      - `"code_execution_20250825"`

      - `"code_execution_20260120"`

    - `allowed_domains: optional array of string`

      允许获取的域名列表

    - `blocked_domains: optional array of string`

      阻止获取的域名列表

    - `cache_control: optional CacheControlEphemeral`

      在此内容块创建缓存控制断点。

    - `citations: optional CitationsConfigParam`

      获取文档的引用配置。默认禁用引用。

    - `defer_loading: optional boolean`

      如果为 true，工具不会包含在初始系统提示中。仅在通过工具搜索的 tool_reference 返回时加载。

    - `max_content_tokens: optional number`

      在上下文中包含网页文本内容所使用的最大 token 数量。该限制是近似的，不适用于 PDF 等二进制内容。

    - `max_uses: optional number`

      工具在 API 请求中可使用的最大次数。

    - `strict: optional boolean`

      当为 true 时，保证对工具名称和输入进行模式验证

  - `WebFetchTool20260309 object { name, type, allowed_callers, 9 more }`

    具有 use_cache 参数的 Web 获取工具，用于绕过缓存内容。

    - `name: "web_fetch"`

      工具名称。

      这是模型和 `tool_use` 块中调用工具的方式。

      - `"web_fetch"`

    - `type: "web_fetch_20260309"`

      - `"web_fetch_20260309"`

    - `allowed_callers: optional array of "direct" or "code_execution_20250825" or "code_execution_20260120"`

      - `"direct"`

      - `"code_execution_20250825"`

      - `"code_execution_20260120"`

    - `allowed_domains: optional array of string`

      允许获取的域名列表

    - `blocked_domains: optional array of string`

      阻止获取的域名列表

    - `cache_control: optional CacheControlEphemeral`

      在此内容块创建缓存控制断点。

    - `citations: optional CitationsConfigParam`

      获取文档的引用配置。默认禁用引用。

    - `defer_loading: optional boolean`

      如果为 true，工具不会包含在初始系统提示中。仅在通过工具搜索的 tool_reference 返回时加载。

    - `max_content_tokens: optional number`

      在上下文中包含网页文本内容所使用的最大 token 数量。该限制是近似的，不适用于 PDF 等二进制内容。

    - `max_uses: optional number`

      工具在 API 请求中可使用的最大次数。

    - `strict: optional boolean`

      当为 true 时，保证对工具名称和输入进行模式验证

    - `use_cache: optional boolean`

      是否使用缓存内容。设置为 false 可绕过缓存并获取新内容。仅在用户明确请求新内容或获取快速变化的源时设置为 false。

  - `ToolSearchToolBm25_20251119 object { name, type, allowed_callers, 3 more }`

    - `name: "tool_search_tool_bm25"`

      工具名称。

      这是模型和 `tool_use` 块中调用工具的方式。

      - `"tool_search_tool_bm25"`

    - `type: "tool_search_tool_bm25_20251119" or "tool_search_tool_bm25"`

      - `"tool_search_tool_bm25_20251119"`

      - `"tool_search_tool_bm25"`

    - `allowed_callers: optional array of "direct" or "code_execution_20250825" or "code_execution_20260120"`

      - `"direct"`

      - `"code_execution_20250825"`

      - `"code_execution_20260120"`

    - `cache_control: optional CacheControlEphemeral`

      在此内容块创建缓存控制断点。

    - `defer_loading: optional boolean`

      如果为 true，工具不会包含在初始系统提示中。仅在通过工具搜索的 tool_reference 返回时加载。

    - `strict: optional boolean`

      当为 true 时，保证对工具名称和输入进行模式验证

  - `ToolSearchToolRegex20251119 object { name, type, allowed_callers, 3 more }`

    - `name: "tool_search_tool_regex"`

      工具名称。

      这是模型和 `tool_use` 块中调用工具的方式。

      - `"tool_search_tool_regex"`

    - `type: "tool_search_tool_regex_20251119" or "tool_search_tool_regex"`

      - `"tool_search_tool_regex_20251119"`

      - `"tool_search_tool_regex"`

    - `allowed_callers: optional array of "direct" or "code_execution_20250825" or "code_execution_20260120"`

      - `"direct"`

      - `"code_execution_20250825"`

      - `"code_execution_20260120"`

    - `cache_control: optional CacheControlEphemeral`

      在此内容块创建缓存控制断点。

    - `defer_loading: optional boolean`

      如果为 true，工具不会包含在初始系统提示中。仅在通过工具搜索的 tool_reference 返回时加载。

    - `strict: optional boolean`

      当为 true 时，保证对工具名称和输入进行模式验证

### 返回值

- `MessageTokensCount object { input_tokens }`

  - `input_tokens: number`

    提供的消息列表、系统提示和工具中的 token 总数。

### Example

```http
curl https://api.anthropic.com/v1/messages/count_tokens \
    -H 'Content-Type: application/json' \
    -H 'anthropic-version: 2023-06-01' \
    -H "X-Api-Key: $ANTHROPIC_API_KEY" \
    -d "{
          \"messages\": [
            {
              \"content\": \"Hello, world\",
              \"role\": \"user\"
            }
          ],
          \"model\": \"claude-opus-4-6\",
          \"system\": [
            {
              \"text\": \"Today's date is 2024-06-01.\",
              \"type\": \"text\"
            }
          ],
          \"thinking\": {
            \"type\": \"adaptive\"
          },
          \"tools\": [
            {
              \"input_schema\": {
                \"type\": \"object\",
                \"properties\": {
                  \"location\": \"bar\",
                  \"unit\": \"bar\"
                },
                \"required\": [
                  \"location\"
                ]
              },
              \"name\": \"name\"
            }
          ]
        }"
```

#### 响应

```json
{
  "input_tokens": 2095
}
```
