---
title: Token 計數
url: https://platform.claude.com/docs/zh-TW/build-with-claude/token-counting
description: 在將訊息傳送給 Claude 之前計算其中的 token 數量。使用 token 計數來管理速率限制和成本、做出模型路由決策，並將提示調整至目標長度。
featureMetadata:
  status: stable
  zdr:
    eligibility: eligible
    note: Excludes [Covered Models](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#model-specific-data-retention-requirements). 在傳送請求前計算 token 數。
  supportedModels:
    - claude-fable-5-1
    - claude-mythos-5-1
    - claude-fable-5
    - claude-mythos-5
    - claude-mythos-preview
    - claude-opus-5-5
    - claude-opus-5
    - claude-sonnet-5-5
    - claude-sonnet-5
    - claude-haiku-5-5
    - claude-haiku-4-5-20251001
    - claude-opus-4-8
    - claude-opus-4-7
    - claude-opus-4-6
    - claude-sonnet-4-6
    - claude-opus-4-5-20251101
    - claude-sonnet-4-5-20250929
  supportedPlatforms:
    Claude API: stable
    Claude Platform on AWS: stable
    Claude Models on Google Cloud (Anthropic managed): stable
    Amazon Bedrock: stable
    Amazon Bedrock (InvokeModel): stable
    Claude Models on Google Cloud (Google managed): stable
    Microsoft Foundry: stable
---

「Token counting」（token 計數）可讓您在將訊息傳送給 Claude 之前，確定訊息中的 token 數量。這有助於您對提示和使用量做出明智的決策。透過 token 計數，您可以：

* 主動管理「rate limit」（速率限制）和成本
* 做出明智的「model routing」（模型路由）決策
* 將提示最佳化至特定長度

***

## 如何計算訊息 token

[token 計數](https://platform.claude.com/docs/zh-TW/api/messages/count_tokens)端點接受與建立訊息相同的結構化輸入清單，包括支援系統提示、[工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/overview)、[圖片](https://platform.claude.com/docs/zh-TW/build-with-claude/vision)和 [PDF](https://platform.claude.com/docs/zh-TW/build-with-claude/pdf-support)。回應中包含[輸入 token](https://platform.claude.com/docs/zh-TW/api/messages/count_tokens#message_tokens_count.input_tokens) 的總數。

(See the `messages/count_tokens` method in [the API reference](https://platform.claude.com/docs/zh-TW/api/messages/count_tokens).)

對於 Messages API 接受的少數輸入，此端點會傳回 `invalid_request_error`：

* [伺服器工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/server-tools)，例如網頁搜尋、網頁擷取、程式碼執行和工具搜尋（[顧問工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/advisor-tool)以外的所有伺服器工具）
* [MCP 連接器](https://platform.claude.com/docs/zh-TW/agents-and-tools/mcp-connector)
* 具有 `url` 或 `file` 來源的 `image` 或 `document` 區塊

請以 base64 格式傳送圖片和 PDF 以進行計數。對於使用伺服器工具或 MCP 伺服器的請求，Messages API 回應會在其 [`usage`](https://platform.claude.com/docs/zh-TW/api/messages/create#message.usage) 物件中回報所使用的 token 數量。

<Note>
  Token 計數是一個**估計值**。在某些情況下，建立訊息時實際使用的輸入 token 數量可能會有少量差異。

  Token 計數可能包含 Anthropic 為系統最佳化而自動新增的 token。**系統新增的 token 不會向您收費**。計費僅反映您的內容。
</Note>

### 支援的模型

所有[現行模型](https://platform.claude.com/docs/zh-TW/models/overview)都支援 token 計數。

<Note>
  Claude 4.7 及更新的模型以及 Claude Mythos Preview 使用較新的「tokenizer」（分詞器）。相同的輸入文字所產生的 token 比早期模型多約 30%。確切的增幅取決於內容和工作負載的型態。請針對您計劃使用的模型重新計算提示，而不要重複使用針對早期模型所測得的計數。
</Note>

### 計算基本訊息中的 token

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages/count_tokens \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "content-type: application/json" \
    -H "anthropic-version: 2026-10-21" \
    -d '{
      "model": "claude-opus-5-5",
      "system": "You are a scientist",
      "messages": [{
        "role": "user",
        "content": "Hello, Claude"
      }]
    }'
  ```

  ```bash CLI
  ant messages count-tokens \
    --model claude-opus-5-5 \
    --system "You are a scientist" \
    --message '{role: user, content: "Hello, Claude"}'
  ```

  ```python Python
  client = anthropic.Anthropic()

  response = client.messages.count_tokens(
      model="claude-opus-5-5",
      system="You are a scientist",
      messages=[{"role": "user", "content": "Hello, Claude"}],
  )

  print(response.json())
  ```

  ```typescript TypeScript
  const client = new Anthropic();

  const response = await client.messages.countTokens({
    model: "claude-opus-5-5",
    system: "You are a scientist",
    messages: [
      {
        role: "user",
        content: "Hello, Claude"
      }
    ]
  });

  console.log(response);
  ```

  ```csharp C#
  using System;
  using System.Threading.Tasks;
  using Anthropic;
  using Anthropic.Models.Messages;

  AnthropicClient client = new();

  var parameters = new MessageCountTokensParams
  {
      Model = Model.ClaudeOpus5_5,
      System = "You are a scientist",
      Messages = [new UserMessageParam { Content = "Hello, Claude" }]
  };

  var response = await client.Messages.CountTokens(parameters);
  Console.WriteLine(response);
  ```

  ```go Go
  client := anthropic.NewClient()

  response, err := client.Messages.CountTokens(context.TODO(), anthropic.MessageCountTokensParams{
  	Model: anthropic.ModelClaudeOpus5_5,
  	System: anthropic.MessageCountTokensParamsSystemUnion{
  		OfString: anthropic.String("You are a scientist"),
  	},
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Hello, Claude")),
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }

  fmt.Println(response)
  ```

  ```java Java
  import com.anthropic.models.messages.MessageCountTokensParams;
  import com.anthropic.models.messages.MessageTokensCount;
  // ...

  public class CountTokensExample {

      public static void main(String[] args) {
          AnthropicClient client = AnthropicOkHttpClient.fromEnv();

          MessageCountTokensParams params = MessageCountTokensParams.builder()
              .model(Model.CLAUDE_OPUS_5_5)
              .system("You are a scientist")
              .addUserMessage("Hello, Claude")
              .build();

          MessageTokensCount count = client.messages().countTokens(params);
          System.out.println(count);
      }
  }
  ```

  ```php PHP
  $client = new Client();

  $response = $client->messages->countTokens(
      messages: [
          ['role' => 'user', 'content' => 'Hello, Claude']
      ],
      model: Model::CLAUDE_OPUS_5_5,
      system: 'You are a scientist',
  );

  echo json_encode($response);
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  response = client.messages.count_tokens(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    system: "You are a scientist",
    messages: [
      { role: "user", content: "Hello, Claude" }
    ]
  )

  puts response
  ```
</CodeGroup>

```json Output
{ "input_tokens": 14 }
```

### 計算包含工具的訊息中的 token

<Note>
  Token 計數支援用戶端工具和[顧問工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/advisor-tool)。包含其他[伺服器工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/server-tools)的請求會傳回錯誤。對於顧問工具，計數僅涵蓋執行者的第一次取樣呼叫。
</Note>

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages/count_tokens \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "content-type: application/json" \
    -H "anthropic-version: 2026-10-21" \
    -d '{
      "model": "claude-opus-5-5",
      "tools": [
        {
          "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"
              }
            },
            "required": ["location"]
          }
        }
      ],
      "messages": [
        {
          "role": "user",
          "content": "What'\''s the weather like in San Francisco?"
        }
      ]
    }'
  ```

  ```bash CLI
  ant messages count-tokens <<'YAML'
  model: claude-opus-5-5
  tools:
    - 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
        required:
          - location
  messages:
    - role: user
      content: What's the weather like in San Francisco?
  YAML
  ```

  ```python Python
  client = anthropic.Anthropic()

  response = client.messages.count_tokens(
      model="claude-opus-5-5",
      tools=[
          {
              "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",
                      }
                  },
                  "required": ["location"],
              },
          }
      ],
      messages=[{"role": "user", "content": "What's the weather like in San Francisco?"}],
  )

  print(response.json())
  ```

  ```typescript TypeScript
  const client = new Anthropic();

  const response = await client.messages.countTokens({
    model: "claude-opus-5-5",
    tools: [
      {
        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"
            }
          },
          required: ["location"]
        }
      }
    ],
    messages: [{ role: "user", content: "What's the weather like in San Francisco?" }]
  });

  console.log(response);
  ```

  ```csharp C#
  using System;
  using System.Collections.Generic;
  using System.Text.Json;
  using System.Threading.Tasks;
  using Anthropic;
  using Anthropic.Models.Messages;

  AnthropicClient client = new();

  var parameters = new MessageCountTokensParams
  {
      Model = Model.ClaudeOpus5_5,
      Tools =
      [
          new MessageCountTokensTool(new Tool()
          {
              Name = "get_weather",
              Description = "Get the current weather in a given location",
              InputSchema = new InputSchema()
              {
                  Properties = new Dictionary<string, JsonElement>
                  {
                      ["location"] = JsonSerializer.SerializeToElement(new { type = "string", description = "The city and state, e.g. San Francisco, CA" }),
                  },
                  Required = ["location"],
              },
          }),
      ],
      Messages = [new UserMessageParam { Content = "What's the weather like in San Francisco?" }]
  };

  var count = await client.Messages.CountTokens(parameters);
  Console.WriteLine(count);
  ```

  ```go Go
  client := anthropic.NewClient()

  response, err := client.Messages.CountTokens(context.TODO(), anthropic.MessageCountTokensParams{
  	Model: anthropic.ModelClaudeOpus5_5,
  	Tools: []anthropic.MessageCountTokensToolUnionParam{
  		{OfTool: &anthropic.ToolParam{
  			Name:        "get_weather",
  			Description: anthropic.String("Get the current weather in a given location"),
  			InputSchema: anthropic.ToolInputSchemaParam{
  				Properties: map[string]any{
  					"location": map[string]any{
  						"type":        "string",
  						"description": "The city and state, e.g. San Francisco, CA",
  					},
  				},
  				Required: []string{"location"},
  			},
  		}},
  	},
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("What's the weather like in San Francisco?")),
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }

  jsonData, _ := json.MarshalIndent(response, "", "  ")
  fmt.Println(string(jsonData))
  ```

  ```java Java
  import com.anthropic.models.messages.MessageCountTokensParams;
  import com.anthropic.models.messages.MessageTokensCount;
  // ...
          AnthropicClient client = AnthropicOkHttpClient.fromEnv();

          InputSchema schema = InputSchema.builder()
              .properties(
                  JsonValue.from(
                      Map.of(
                          "location",
                          Map.of(
                              "type",
                              "string",
                              "description",
                              "The city and state, e.g. San Francisco, CA"
                          )
                      )
                  )
              )
              .putAdditionalProperty("required", JsonValue.from(List.of("location")))
              .build();

          MessageCountTokensParams params = MessageCountTokensParams.builder()
              .model(Model.CLAUDE_OPUS_5_5)
              .addTool(
                  Tool.builder()
                      .name("get_weather")
                      .description("Get the current weather in a given location")
                      .inputSchema(schema)
                      .build()
              )
              .addUserMessage("What's the weather like in San Francisco?")
              .build();

          MessageTokensCount count = client.messages().countTokens(params);
          System.out.println(count);
  ```

  ```php PHP
  $client = new Client();

  $response = $client->messages->countTokens(
      messages: [
          ['role' => 'user', 'content' => "What's the weather like in San Francisco?"]
      ],
      model: Model::CLAUDE_OPUS_5_5,
      tools: [
          [
              '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'
                      ]
                  ],
                  'required' => ['location']
              ]
          ]
      ],
  );

  echo json_encode($response, JSON_PRETTY_PRINT);
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  response = client.messages.count_tokens(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    tools: [
      {
        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"
            }
          },
          required: ["location"]
        }
      }
    ],
    messages: [
      { role: "user", content: "What's the weather like in San Francisco?" }
    ]
  )

  puts response
  ```
</CodeGroup>

```json Output
{ "input_tokens": 403 }
```

### 計算包含圖片的訊息中的 token

<CodeGroup>
  ```bash cURL
  #!/bin/sh

  IMAGE_BASE64=$(curl -s "https://platform.claude.com/docs/images/vision-example.jpg" | base64 | tr -d '\n')

  curl https://api.anthropic.com/v1/messages/count_tokens \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -H "content-type: application/json" \
    -d @- <<EOF
  {
    "model": "claude-opus-5-5",
    "messages": [
      {"role": "user", "content": [
        {"type": "image", "source": {
          "type": "base64",
          "media_type": "image/jpeg",
          "data": "$IMAGE_BASE64"
        }},
        {"type": "text", "text": "Describe this image"}
      ]}
    ]
  }
  EOF
  ```

  ```bash CLI
  curl -s "https://platform.claude.com/docs/images/vision-example.jpg" \
    -o ./vision-example.jpg

  ant messages count-tokens <<'YAML'
  model: claude-opus-5-5
  messages:
    - role: user
      content:
        - type: image
          source:
            type: base64
            media_type: image/jpeg
            data: "@./vision-example.jpg"
        - type: text
          text: Describe this image
  YAML
  ```

  ```python Python
  import base64
  import httpx2

  image_url = "https://platform.claude.com/docs/images/vision-example.jpg"
  image_media_type = "image/jpeg"
  image_data = base64.standard_b64encode(httpx2.get(image_url).content).decode("utf-8")

  client = anthropic.Anthropic()

  response = client.messages.count_tokens(
      model="claude-opus-5-5",
      messages=[
          {
              "role": "user",
              "content": [
                  {
                      "type": "image",
                      "source": {
                          "type": "base64",
                          "media_type": image_media_type,
                          "data": image_data,
                      },
                  },
                  {"type": "text", "text": "Describe this image"},
              ],
          }
      ],
  )
  print(response.json())
  ```

  ```typescript TypeScript
  const anthropic = new Anthropic();

  const imageUrl = "https://platform.claude.com/docs/images/vision-example.jpg";
  const imageMediaType = "image/jpeg";
  const imageArrayBuffer = await (await fetch(imageUrl)).arrayBuffer();
  const imageData = Buffer.from(imageArrayBuffer).toString("base64");

  const response = await anthropic.messages.countTokens({
    model: "claude-opus-5-5",
    messages: [
      {
        role: "user",
        content: [
          {
            type: "image",
            source: {
              type: "base64",
              media_type: imageMediaType,
              data: imageData
            }
          },
          {
            type: "text",
            text: "Describe this image"
          }
        ]
      }
    ]
  });
  console.log(response);
  ```

  ```csharp C#
  using System;
  using System.Collections.Generic;
  using System.Net.Http;
  using System.Threading.Tasks;
  using Anthropic;
  using Anthropic.Models.Messages;

  AnthropicClient client = new();

  string imageUrl = "https://platform.claude.com/docs/images/vision-example.jpg";

  using HttpClient httpClient = new();
  byte[] imageBytes = await httpClient.GetByteArrayAsync(imageUrl);
  string imageData = Convert.ToBase64String(imageBytes);

  var parameters = new MessageCountTokensParams
  {
      Model = Model.ClaudeOpus5_5,
      Messages =
      [
          new UserMessageParam
          {
              Content = new List<ContentBlockParam>
              {
                  new ContentBlockParam(new ImageBlockParam(
                      new ImageBlockParamSource(new Base64ImageSource()
                      {
                          Data = imageData,
                          MediaType = MediaType.ImageJpeg,
                      })
                  )),
                  new ContentBlockParam(new TextBlockParam("Describe this image")),
              },
          }
      ]
  };

  var count = await client.Messages.CountTokens(parameters);
  Console.WriteLine(count);
  ```

  ```go Go
  imageURL := "https://platform.claude.com/docs/images/vision-example.jpg"

  req, err := http.NewRequest("GET", imageURL, nil)
  if err != nil {
  	log.Fatal(err)
  }
  req.Header.Set("User-Agent", "AnthropicDocsBot/1.0")

  resp, err := http.DefaultClient.Do(req)
  if err != nil {
  	log.Fatal(err)
  }
  defer resp.Body.Close()

  imageBytes, err := io.ReadAll(resp.Body)
  if err != nil {
  	log.Fatal(err)
  }
  imageData := base64.StdEncoding.EncodeToString(imageBytes)

  client := anthropic.NewClient()

  response, err := client.Messages.CountTokens(context.TODO(), anthropic.MessageCountTokensParams{
  	Model: anthropic.ModelClaudeOpus5_5,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(
  			anthropic.NewImageBlockBase64("image/jpeg", imageData),
  			anthropic.NewTextBlock("Describe this image"),
  		),
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }

  fmt.Println(response)
  ```

  ```java Java
  import com.anthropic.models.messages.Base64ImageSource;
  // ...
  import com.anthropic.models.messages.MessageCountTokensParams;
  import com.anthropic.models.messages.MessageTokensCount;
  // ...
          AnthropicClient client = AnthropicOkHttpClient.fromEnv();

          String imageUrl =
              "https://platform.claude.com/docs/images/vision-example.jpg";
          String imageMediaType = "image/jpeg";

          HttpClient httpClient = HttpClient.newHttpClient();
          HttpRequest request = HttpRequest.newBuilder()
              .uri(URI.create(imageUrl))
              .build();
          byte[] imageBytes = httpClient
              .send(request, HttpResponse.BodyHandlers.ofByteArray())
              .body();
          String imageBase64 = Base64.getEncoder().encodeToString(imageBytes);

          ContentBlockParam imageBlock = ContentBlockParam.ofImage(
              ImageBlockParam.builder()
                  .source(
                      Base64ImageSource.builder()
                          .mediaType(Base64ImageSource.MediaType.IMAGE_JPEG)
                          .data(imageBase64)
                          .build()
                  )
                  .build()
          );

          ContentBlockParam textBlock = ContentBlockParam.ofText(
              TextBlockParam.builder()
                  .text("Describe this image")
                  .build()
          );

          MessageCountTokensParams params = MessageCountTokensParams.builder()
              .model(Model.CLAUDE_OPUS_5_5)
              .addUserMessageOfContentBlockParams(List.of(imageBlock, textBlock))
              .build();

          MessageTokensCount count = client.messages().countTokens(params);
          System.out.println(count);
  ```

  ```php PHP
  $imageUrl = 'https://platform.claude.com/docs/images/vision-example.jpg';
  $imageMediaType = 'image/jpeg';
  $imageData = base64_encode(file_get_contents($imageUrl));

  $client = new Client();

  $response = $client->messages->countTokens(
      messages: [
          [
              'role' => 'user',
              'content' => [
                  [
                      'type' => 'image',
                      'source' => [
                          'type' => 'base64',
                          'media_type' => $imageMediaType,
                          'data' => $imageData
                      ]
                  ],
                  ['type' => 'text', 'text' => 'Describe this image']
              ]
          ]
      ],
      model: 'claude-opus-5-5',
  );
  print_r($response);
  ```

  ```ruby Ruby
  require "base64"
  require "net/http"

  image_url = "https://platform.claude.com/docs/images/vision-example.jpg"
  image_media_type = "image/jpeg"

  uri = URI(image_url)
  image_data = Base64.strict_encode64(Net::HTTP.get(uri))

  client = Anthropic::Client.new

  response = client.messages.count_tokens(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    messages: [
      {
        role: "user",
        content: [
          {
            type: "image",
            source: {
              type: "base64",
              media_type: image_media_type,
              data: image_data
            }
          },
          { type: "text", text: "Describe this image" }
        ]
      }
    ]
  )
  puts response
  ```
</CodeGroup>

```json Output
{ "input_tokens": 1028 }
```

設定了 [`"oversized_image": "error"`](https://platform.claude.com/docs/zh-TW/build-with-claude/vision-coordinates#oversized-image-error) 的內嵌圖片區塊，在計數時會被拒絕，方式與 Messages API 拒絕它的方式完全相同。

### 計算包含思考的訊息中的 token

<Note>
  如需更多詳細資訊，請參閱[思考與上下文視窗](https://platform.claude.com/docs/zh-TW/build-with-claude/thinking#thinking-and-the-context-window)。

  * 在[保留所有先前回合](https://platform.claude.com/docs/zh-TW/build-with-claude/thinking#thinking-block-preservation-by-model)的模型上，來自**先前** assistant 回合的思考區塊會計入您的輸入 token；在僅保留最後一個回合的模型上，API 會移除這些區塊，因此它們**不會**計入。
  * **目前** assistant 回合的思考**會**計入您的輸入 token。
</Note>

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages/count_tokens \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "content-type: application/json" \
    -H "anthropic-version: 2026-10-21" \
    -d '{
      "model": "claude-opus-5-5",
      "thinking": {
        "type": "adaptive"
      },
      "messages": [
        {
          "role": "user",
          "content": "Are there an infinite number of prime numbers such that n mod 4 == 3?"
        },
        {
          "role": "assistant",
          "content": [
            {
              "type": "thinking",
              "thinking": "This is a nice number theory question. Lets think about it step by step...",
              "signature": "EuYBCkQYAiJAgCs1le6/Pol5Z4/JMomVOouGrWdhYNsH3ukzUECbB6iWrSQtsQuRHJID6lWV..."
            },
            {
              "type": "text",
              "text": "Yes, there are infinitely many prime numbers p such that p mod 4 = 3..."
            }
          ]
        },
        {
          "role": "user",
          "content": "Can you write a formal proof?"
        }
      ]
    }'
  ```

  ```bash CLI
  ant messages count-tokens <<'YAML'
  model: claude-opus-5-5
  thinking:
    type: adaptive
  messages:
    - role: user
      content: Are there an infinite number of prime numbers such that n mod 4 == 3?
    - role: assistant
      content:
        - type: thinking
          thinking: >-
            This is a nice number theory question. Lets think about it step by step...
          signature: >-
            EuYBCkQYAiJAgCs1le6/Pol5Z4/JMomVOouGrWdhYNsH3ukzUECbB6iWrSQtsQuRHJID6lWV...
        - type: text
          text: Yes, there are infinitely many prime numbers p such that p mod 4 = 3...
    - role: user
      content: Can you write a formal proof?
  YAML
  ```

  ```python Python
  client = anthropic.Anthropic()

  response = client.messages.count_tokens(
      model="claude-opus-5-5",
      thinking={"type": "adaptive"},
      messages=[
          {
              "role": "user",
              "content": "Are there an infinite number of prime numbers such that n mod 4 == 3?",
          },
          {
              "role": "assistant",
              "content": [
                  {
                      "type": "thinking",
                      "thinking": "This is a nice number theory question. Let's think about it step by step...",
                      "signature": "EuYBCkQYAiJAgCs1le6/Pol5Z4/JMomVOouGrWdhYNsH3ukzUECbB6iWrSQtsQuRHJID6lWV...",
                  },
                  {
                      "type": "text",
                      "text": "Yes, there are infinitely many prime numbers p such that p mod 4 = 3...",
                  },
              ],
          },
          {"role": "user", "content": "Can you write a formal proof?"},
      ],
  )

  print(response.json())
  ```

  ```typescript TypeScript
  const client = new Anthropic();

  const response = await client.messages.countTokens({
    model: "claude-opus-5-5",
    thinking: { type: "adaptive" },
    messages: [
      {
        role: "user",
        content: "Are there an infinite number of prime numbers such that n mod 4 == 3?"
      },
      {
        role: "assistant",
        content: [
          {
            type: "thinking",
            thinking:
              "This is a nice number theory question. Let's think about it step by step...",
            signature:
              "EuYBCkQYAiJAgCs1le6/Pol5Z4/JMomVOouGrWdhYNsH3ukzUECbB6iWrSQtsQuRHJID6lWV..."
          },
          {
            type: "text",
            text: "Yes, there are infinitely many prime numbers p such that p mod 4 = 3..."
          }
        ]
      },
      {
        role: "user",
        content: "Can you write a formal proof?"
      }
    ]
  });

  console.log(response);
  ```

  ```csharp C#
  using System;
  using System.Threading.Tasks;
  using System.Collections.Generic;
  using Anthropic;
  using Anthropic.Models.Messages;

  AnthropicClient client = new();

  var parameters = new MessageCountTokensParams
  {
      Model = Model.ClaudeOpus5_5,
      Thinking = new ThinkingConfigAdaptive(),
      Messages =
      [
          new UserMessageParam
          {
              Content = "Are there an infinite number of prime numbers such that n mod 4 == 3?"
          },
          new AssistantMessageParam
          {
              Content = new List<ContentBlockParam>
              {
                  new ContentBlockParam(new ThinkingBlockParam()
                  {
                      Thinking = "This is a nice number theory question. Let's think about it step by step...",
                      Signature = "EuYBCkQYAiJAgCs1le6/Pol5Z4/JMomVOouGrWdhYNsH3ukzUECbB6iWrSQtsQuRHJID6lWV...",
                  }),
                  new ContentBlockParam(new TextBlockParam("Yes, there are infinitely many prime numbers p such that p mod 4 = 3...")),
              },
          },
          new UserMessageParam { Content = "Can you write a formal proof?" }
      ]
  };

  var response = await client.Messages.CountTokens(parameters);
  Console.WriteLine(response);
  ```

  ```go Go
  client := anthropic.NewClient()

  thinkingBlock := anthropic.NewThinkingBlock(
  	"EuYBCkQYAiJAgCs1le6/Pol5Z4/JMomVOouGrWdhYNsH3ukzUECbB6iWrSQtsQuRHJID6lWV...",
  	"This is a nice number theory question. Let's think about it step by step...",
  )

  textBlock := anthropic.NewTextBlock(
  	"Yes, there are infinitely many prime numbers p such that p mod 4 = 3...",
  )

  response, err := client.Messages.CountTokens(context.TODO(), anthropic.MessageCountTokensParams{
  	Model: anthropic.ModelClaudeOpus5_5,
  	Thinking: anthropic.ThinkingConfigParamUnion{
  		OfAdaptive: &anthropic.ThinkingConfigAdaptiveParam{},
  	},
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Are there an infinite number of prime numbers such that n mod 4 == 3?")),
  		anthropic.NewAssistantMessage(thinkingBlock, textBlock),
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Can you write a formal proof?")),
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }

  fmt.Printf("%+v\n", response)
  ```

  ```java Java
  import com.anthropic.models.messages.MessageCountTokensParams;
  import com.anthropic.models.messages.MessageTokensCount;
  // ...
  import com.anthropic.models.messages.ThinkingBlockParam;
  import com.anthropic.models.messages.ThinkingConfigAdaptive;
  // ...
          AnthropicClient client = AnthropicOkHttpClient.fromEnv();

          List<ContentBlockParam> assistantBlocks = List.of(
              ContentBlockParam.ofThinking(
                  ThinkingBlockParam.builder()
                      .thinking(
                          "This is a nice number theory question. Let's think about it step by step..."
                      )
                      .signature(
                          "EuYBCkQYAiJAgCs1le6/Pol5Z4/JMomVOouGrWdhYNsH3ukzUECbB6iWrSQtsQuRHJID6lWV..."
                      )
                      .build()
              ),
              ContentBlockParam.ofText(
                  TextBlockParam.builder()
                      .text("Yes, there are infinitely many prime numbers p such that p mod 4 = 3...")
                      .build()
              )
          );

          MessageCountTokensParams params = MessageCountTokensParams.builder()
              .model(Model.CLAUDE_OPUS_5_5)
              .thinking(ThinkingConfigAdaptive.builder().build())
              .addUserMessage("Are there an infinite number of prime numbers such that n mod 4 == 3?")
              .addAssistantMessageOfContentBlockParams(assistantBlocks)
              .addUserMessage("Can you write a formal proof?")
              .build();

          MessageTokensCount count = client.messages().countTokens(params);
          System.out.println(count);
  ```

  ```php PHP
  $client = new Client();

  $response = $client->messages->countTokens(
      messages: [
          [
              'role' => 'user',
              'content' => 'Are there an infinite number of prime numbers such that n mod 4 == 3?'
          ],
          [
              'role' => 'assistant',
              'content' => [
                  [
                      'type' => 'thinking',
                      'thinking' => 'This is a nice number theory question. Let\'s think about it step by step...',
                      'signature' => 'EuYBCkQYAiJAgCs1le6/Pol5Z4/JMomVOouGrWdhYNsH3ukzUECbB6iWrSQtsQuRHJID6lWV...'
                  ],
                  [
                      'type' => 'text',
                      'text' => 'Yes, there are infinitely many prime numbers p such that p mod 4 = 3...'
                  ]
              ]
          ],
          [
              'role' => 'user',
              'content' => 'Can you write a formal proof?'
          ]
      ],
      model: 'claude-opus-5-5',
      thinking: ['type' => 'adaptive'],
  );

  echo json_encode($response);
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  response = client.messages.count_tokens(
    model: "claude-opus-5-5",
    thinking: {
      type: "adaptive"
    },
    messages: [
      {
        role: "user",
        content: "Are there an infinite number of prime numbers such that n mod 4 == 3?"
      },
      {
        role: "assistant",
        content: [
          {
            type: "thinking",
            thinking: "This is a nice number theory question. Let's think about it step by step...",
            signature: "EuYBCkQYAiJAgCs1le6/Pol5Z4/JMomVOouGrWdhYNsH3ukzUECbB6iWrSQtsQuRHJID6lWV..."
          },
          {
            type: "text",
            text: "Yes, there are infinitely many prime numbers p such that p mod 4 = 3..."
          }
        ]
      },
      {
        role: "user",
        content: "Can you write a formal proof?"
      }
    ]
  )

  puts response
  ```
</CodeGroup>

```json Output
{ "input_tokens": 88 }
```

### 計算包含 PDF 的訊息中的 token

<Note>
  Token 計數支援 base64 編碼的 PDF，並適用與 Messages API 相同的 [PDF 要求](https://platform.claude.com/docs/zh-TW/build-with-claude/pdf-support#check-pdf-requirements)。此端點不支援 `url` 或 `file` 文件來源。
</Note>

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages/count_tokens \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "content-type: application/json" \
    -H "anthropic-version: 2026-10-21" \
    -d @- <<EOF
  {
    "model": "claude-opus-5-5",
    "messages": [{
      "role": "user",
      "content": [
        {
          "type": "document",
          "source": {
            "type": "base64",
            "media_type": "application/pdf",
            "data": "$PDF_BASE64"
          }
        },
        {
          "type": "text",
          "text": "Please summarize this document."
        }
      ]
    }]
  }
  EOF
  ```

  ```bash CLI
  ant messages count-tokens <<'YAML'
  model: claude-opus-5-5
  messages:
    - role: user
      content:
        - type: document
          source:
            type: base64
            media_type: application/pdf
            data: "@./document.pdf"
        - type: text
          text: Please summarize this document.
  YAML
  ```

  ```python Python
  import base64
  import anthropic

  client = anthropic.Anthropic()

  with open("/path/to/document.pdf", "rb") as pdf_file:
      pdf_base64 = base64.standard_b64encode(pdf_file.read()).decode("utf-8")

  response = client.messages.count_tokens(
      model="claude-opus-5-5",
      messages=[
          {
              "role": "user",
              "content": [
                  {
                      "type": "document",
                      "source": {
                          "type": "base64",
                          "media_type": "application/pdf",
                          "data": pdf_base64,
                      },
                  },
                  {"type": "text", "text": "Please summarize this document."},
              ],
          }
      ],
  )

  print(response.json())
  ```

  ```typescript TypeScript
  import { readFile } from "node:fs/promises";

  const client = new Anthropic();

  const pdfBase64 = await readFile("/path/to/document.pdf", { encoding: "base64" });

  const response = await client.messages.countTokens({
    model: "claude-opus-5-5",
    messages: [
      {
        role: "user",
        content: [
          {
            type: "document",
            source: {
              type: "base64",
              media_type: "application/pdf",
              data: pdfBase64
            }
          },
          {
            type: "text",
            text: "Please summarize this document."
          }
        ]
      }
    ]
  });

  console.log(response);
  ```

  ```csharp C#
  using System;
  using System.IO;
  using System.Threading.Tasks;
  using System.Collections.Generic;
  using Anthropic;
  using Anthropic.Models.Messages;

  AnthropicClient client = new();

  byte[] pdfBytes = await File.ReadAllBytesAsync("/path/to/document.pdf");
  string pdfBase64 = Convert.ToBase64String(pdfBytes);

  var parameters = new MessageCountTokensParams
  {
      Model = Model.ClaudeOpus5_5,
      Messages =
      [
          new UserMessageParam
          {
              Content = new List<ContentBlockParam>
              {
                  new ContentBlockParam(new DocumentBlockParam(
                      new DocumentBlockParamSource(new Base64PdfSource()
                      {
                          Data = pdfBase64,
                      })
                  )),
                  new ContentBlockParam(new TextBlockParam("Please summarize this document.")),
              },
          }
      ]
  };

  var count = await client.Messages.CountTokens(parameters);
  Console.WriteLine(count);
  ```

  ```go Go
  client := anthropic.NewClient()

  pdfBytes, err := os.ReadFile("/path/to/document.pdf")
  if err != nil {
  	log.Fatal(err)
  }
  pdfBase64 := base64.StdEncoding.EncodeToString(pdfBytes)

  response, err := client.Messages.CountTokens(context.TODO(), anthropic.MessageCountTokensParams{
  	Model: anthropic.ModelClaudeOpus5_5,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(
  			anthropic.NewDocumentBlock(anthropic.Base64PDFSourceParam{
  				Data: pdfBase64,
  			}),
  			anthropic.NewTextBlock("Please summarize this document."),
  		),
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }

  fmt.Println(response)
  ```

  ```java Java
  import com.anthropic.models.messages.Base64PdfSource;
  // ...
  import com.anthropic.models.messages.DocumentBlockParam;
  import com.anthropic.models.messages.MessageCountTokensParams;
  import com.anthropic.models.messages.MessageTokensCount;
  // ...
          AnthropicClient client = AnthropicOkHttpClient.fromEnv();

          byte[] fileBytes = Files.readAllBytes(Path.of("/path/to/document.pdf"));
          String pdfBase64 = Base64.getEncoder().encodeToString(fileBytes);

          ContentBlockParam documentBlock = ContentBlockParam.ofDocument(
              DocumentBlockParam.builder()
                  .source(Base64PdfSource.builder()
                      .data(pdfBase64)
                      .build())
                  .build()
          );

          ContentBlockParam textBlock = ContentBlockParam.ofText(
              TextBlockParam.builder()
                  .text("Please summarize this document.")
                  .build()
          );

          MessageCountTokensParams params = MessageCountTokensParams.builder()
              .model(Model.CLAUDE_OPUS_5_5)
              .addUserMessageOfContentBlockParams(List.of(documentBlock, textBlock))
              .build();

          MessageTokensCount count = client.messages().countTokens(params);
          System.out.println(count);
  ```

  ```php PHP
  $client = new Client();

  $pdfBase64 = base64_encode(file_get_contents('/path/to/document.pdf'));

  $response = $client->messages->countTokens(
      messages: [
          [
              'role' => 'user',
              'content' => [
                  [
                      'type' => 'document',
                      'source' => [
                          'type' => 'base64',
                          'media_type' => 'application/pdf',
                          'data' => $pdfBase64
                      ]
                  ],
                  [
                      'type' => 'text',
                      'text' => 'Please summarize this document.'
                  ]
              ]
          ]
      ],
      model: 'claude-opus-5-5',
  );

  echo json_encode($response);
  ```

  ```ruby Ruby
  require "base64"

  client = Anthropic::Client.new

  pdf_base64 = Base64.strict_encode64(File.binread("/path/to/document.pdf"))

  response = client.messages.count_tokens(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    messages: [
      {
        role: "user",
        content: [
          {
            type: "document",
            source: {
              type: "base64",
              media_type: "application/pdf",
              data: pdf_base64
            }
          },
          {
            type: "text",
            text: "Please summarize this document."
          }
        ]
      }
    ]
  )

  puts response
  ```
</CodeGroup>

```json Output
{ "input_tokens": 2188 }
```

***

## Claude Fable 和 Claude Mythos 模型上的 token 計數

Claude Fable 5.1、Claude Mythos 5.1、Claude Fable 5 和 Claude Mythos 5 共用隨 Claude Opus 4.7 推出的 tokenizer。同一個提示在這四個模型上的計數相同，且比 Claude Opus 4.7 之前的模型高出約 30%（確切的增幅取決於內容）。Token 計數端點會依據您傳入的 `model` 所使用的 tokenizer 進行計數。若要衡量您工作負載的差異，請將同一個請求計數兩次，一次使用您目前的模型，另一次使用您計劃遷移到的模型，然後比較兩個 `input_tokens` 值。

<Note>
  **帳單與遷移：** 這些模型上的使用量和帳單反映的是此 tokenizer 的計數。從 Claude Opus 4.7 之前的模型遷移時，請勿重複使用在舊模型上測得的 token 計數來估算成本或是否符合「context window」（上下文視窗）。請使用您計劃使用的 `model` ID（例如 `"claude-fable-5-1"`）來計算您的提示。
</Note>

***

## 定價與速率限制

Token 計數**可免費使用**，但會受到基於您[使用層級](https://platform.claude.com/docs/zh-TW/api/rate-limits#rate-limits)的每分鐘請求數速率限制。如果您需要更高的限制，請在 Claude Console 的[速率限制](https://platform.claude.com/usage/limits)頁面上使用**申請提高層級**。

| 使用層級  | 每分鐘請求數（RPM） |
| ----- | ----------- |
| Start | 5,000       |
| Build | 10,000      |
| Scale | 20,000      |

<Note>
  Token 計數和訊息建立具有各自獨立的速率限制。其中一項的使用量不會計入另一項的限制。
</Note>

***

## 常見問題

<AccordionGroup>
  <Accordion title="Token 計數是否使用提示快取？">
    不會，token 計數提供的是估計值，不使用快取邏輯。雖然您可以在 token 計數請求中提供 `cache_control` 區塊，但「prompt caching」（提示快取）僅在實際建立訊息時才會發生。
  </Accordion>
</AccordionGroup>

***

## 後續步驟

<CardGroup cols={2}>
  <Card title="計算訊息 token" icon="code" href="https://platform.claude.com/docs/zh-TW/api/messages/count_tokens">
    閱讀 token 計數端點的完整 API 參考文件。
  </Card>

  <Card title="上下文視窗" icon="arrows-maximize" href="https://platform.claude.com/docs/zh-TW/build-with-claude/context-windows">
    使用 token 計數讓提示保持在模型的上下文視窗範圍內。
  </Card>

  <Card title="速率限制" icon="gauge" href="https://platform.claude.com/docs/zh-TW/api/rate-limits">
    在傳送請求之前檢查 token 計數，以維持在您的使用層級範圍內。
  </Card>

  <Card title="提示快取" icon="database" href="https://platform.claude.com/docs/zh-TW/build-with-claude/prompt-caching">
    透過快取提示前綴，降低重複提示的成本和延遲。
  </Card>
</CardGroup>

## 可用性

Token 計數在所有模型上可供使用，且具備零資料保留和HIPAA 就緒資格。

### API 支援

#### [Messages API](https://platform.claude.com/docs/zh-TW/build-with-claude/working-with-messages)

* 可用性：可用

| 狀態 | 模型                                                             |
| -- | -------------------------------------------------------------- |
| 可用 | [所有模型](https://platform.claude.com/docs/zh-TW/models/overview) |

#### [Managed Agents](https://platform.claude.com/docs/zh-TW/managed-agents/overview)

* 可用性：不可用

### 資料處理

[資料處理概覽](https://platform.claude.com/docs/zh-TW/manage-claude/api-and-data-retention#feature-eligibility)

| 項目   | 零資料保留                                                                                                                                    | HIPAA |
| ---- | ---------------------------------------------------------------------------------------------------------------------------------------- | ----- |
| 狀態   | 符合資格（不含 [涵蓋的模型](https://platform.claude.com/docs/zh-TW/manage-claude/api-and-data-retention#model-specific-data-retention-requirements)） | 符合資格  |
| 詳細資訊 | 在傳送請求前計算 token 數。                                                                                                                        | —     |

適用端點：

* `/v1/messages/count_tokens`
