Claude Platform Docs
Messages上下文管理

Token 計數

在將訊息傳送給 Claude 之前計算其中的 token 數量。使用 token 計數來管理速率限制和成本、做出模型路由決策,並將提示調整至目標長度。

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

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

如何計算訊息 token

token 計數可檢視預覽,內含 API 參考文件連結——按 Tab 鍵直到焦點進入卡片,按 Escape 鍵返回。端點接受與建立訊息相同的結構化輸入清單,包括支援系統提示、工具、圖片和 PDF。回應中包含輸入 token可檢視預覽,內含 API 參考文件連結——按 Tab 鍵直到焦點進入卡片,按 Escape 鍵返回。 的總數。

對於 Messages API 接受的少數輸入,此端點會傳回 invalid_request_error:

  • 伺服器工具,例如網頁搜尋、網頁擷取、程式碼執行和工具搜尋(顧問工具以外的所有伺服器工具)
  • MCP 連接器
  • 具有 url 或 file 來源的 image 或 document 區塊

請以 base64 格式傳送圖片和 PDF 以進行計數。對於使用伺服器工具或 MCP 伺服器的請求,Messages API 回應會在其 usage可檢視預覽,內含 API 參考文件連結——按 Tab 鍵直到焦點進入卡片,按 Escape 鍵返回。 物件中回報所使用的 token 數量。

支援的模型

所有現行模型都支援 token 計數。

計算基本訊息中的 token

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())
Output
{ "input_tokens": 14 }

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

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())
Output
{ "input_tokens": 403 }

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

import base64
import httpx2

image_url = "https://code.saschaberens.de/_h/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())
Output
{ "input_tokens": 1028 }

設定了 "oversized_image": "error" 的內嵌圖片區塊,在計數時會被拒絕,方式與 Messages API 拒絕它的方式完全相同。

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

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())
Output
{ "input_tokens": 88 }

計算包含 PDF 的訊息中的 token

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())
Output
{ "input_tokens": 2188 }

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

Claude Fable 5.2、Claude Mythos 5.2、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 值。


定價與速率限制

Token 計數可免費使用,但會受到基於您使用層級的每分鐘請求數速率限制。如果您需要更高的限制,請在 Claude Console 的速率限制頁面上使用申請提高層級。

使用層級每分鐘請求數(RPM)
Start5,000
Build10,000
Scale20,000

常見問題


後續步驟

閱讀 token 計數端點的完整 API 參考文件。

使用 token 計數讓提示保持在模型的上下文視窗範圍內。

在傳送請求之前檢查 token 計數,以維持在您的使用層級範圍內。

透過快取提示前綴,降低重複提示的成本和延遲。

可用性

Token 計數
API
  • Messages API
  • Managed Agents 不支援
模型
  • 所有模型

適用端點

  • /v1/messages/count_tokens
零資料保留符合資格

不含 涵蓋的模型

在傳送請求前計算 token 數。

HIPAA符合資格

這個頁面有幫助嗎?