Token 計數使您能夠在將訊息發送給 Claude 之前確定訊息中的 token 數量,幫助您對提示和使用情況做出明智的決策。使用 token 計數,您可以:

  • 主動管理速率限制和成本
  • 做出智能模型路由決策
  • 優化提示以達到特定長度

如何計算訊息 token

token 計數端點接受與創建訊息相同的結構化輸入列表,包括支援系統提示、工具圖像PDF。回應包含輸入 token 的總數。

Token 計數應被視為估計值。在某些情況下,創建訊息時實際使用的輸入 token 數量可能會有少量差異。

支援的模型

Token 計數端點支援以下模型:

  • Claude Opus 4
  • Claude Sonnet 4
  • Claude Sonnet 3.7
  • Claude Sonnet 3.5
  • Claude Haiku 3.5
  • Claude Haiku 3
  • Claude Opus 3

計算基本訊息中的 token

import anthropic

client = anthropic.Anthropic()

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

print(response.json())
JSON
{ "input_tokens": 14 }

計算帶有工具的訊息中的 token

伺服器工具 token 計數僅適用於第一次採樣調用。

import anthropic

client = anthropic.Anthropic()

response = client.messages.count_tokens(
    model="claude-opus-4-20250514",
    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())
JSON
{ "input_tokens": 403 }

計算帶有圖像的訊息中的 token

#!/bin/sh

IMAGE_URL="https://upload.wikimedia.org/wikipedia/commons/a/a7/Camponotus_flavomarginatus_ant.jpg"
IMAGE_MEDIA_TYPE="image/jpeg"
IMAGE_BASE64=$(curl "$IMAGE_URL" | base64)

curl https://api.anthropic.com/v1/messages/count_tokens \
     --header "x-api-key: $ANTHROPIC_API_KEY" \
     --header "anthropic-version: 2023-06-01" \
     --header "content-type: application/json" \
     --data \
'{
    "model": "claude-opus-4-20250514",
    "messages": [
        {"role": "user", "content": [
            {"type": "image", "source": {
                "type": "base64",
                "media_type": "'$IMAGE_MEDIA_TYPE'",
                "data": "'$IMAGE_BASE64'"
            }},
            {"type": "text", "text": "Describe this image"}
        ]}
    ]
}'
JSON
{ "input_tokens": 1551 }

計算帶有擴展思考的訊息中的 token

有關如何使用擴展思考計算上下文窗口的更多詳細信息,請參見此處

  • 先前助手回合的思考區塊會被忽略,不會計入您的輸入 token
  • 當前助手回合的思考計入您的輸入 token
curl https://api.anthropic.com/v1/messages/count_tokens \
    --header "x-api-key: $ANTHROPIC_API_KEY" \
    --header "content-type: application/json" \
    --header "anthropic-version: 2023-06-01" \
    --data '{
      "model": "claude-opus-4-20250514",
      "thinking": {
        "type": "enabled",
        "budget_tokens": 16000
      },
      "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?"
        }
      ]
    }'
JSON
{ "input_tokens": 88 }

計算帶有 PDF 的訊息中的 token

Token 計數支援 PDF,與 Messages API 具有相同的限制

curl https://api.anthropic.com/v1/messages/count_tokens \
    --header "x-api-key: $ANTHROPIC_API_KEY" \
    --header "content-type: application/json" \
    --header "anthropic-version: 2023-06-01" \
    --data '{
      "model": "claude-opus-4-20250514",
      "messages": [{
        "role": "user",
        "content": [
          {
            "type": "document",
            "source": {
              "type": "base64",
              "media_type": "application/pdf",
              "data": "'$(base64 -i document.pdf)'"
            }
          },
          {
            "type": "text",
            "text": "Please summarize this document."
          }
        ]
      }]
    }'
JSON
{ "input_tokens": 2188 }

定價和速率限制

Token 計數免費使用,但受到基於您的使用層級的每分鐘請求數限制。如果您需要更高的限制,請通過 Anthropic Console 聯繫銷售團隊。

使用層級每分鐘請求數 (RPM)
1100
22,000
34,000
48,000

Token 計數和訊息創建有各自獨立的速率限制 — 使用其中一個不會計入另一個的限制。


常見問題