Skip to content
,

Claude Token Counting API in Python: count_tokens Guide with Cost Calculator

12โ€“19 minutes
Woman in a server room holding a tablet with a TOKEN COUNT card, hook 5,000 RPM token counter

Claude’s token counting API tells you exactly how many input tokens a request will use before you send it. It is free, it accepts the same body as the Messages API, and it is the only reliable way to estimate cost for Claude models.

In this guide you will count tokens in Python for text, system prompts, tools, images, PDFs and thinking. Then you will turn those counts into dollar estimates with current December 2026 prices.

TLDR

  • Method: client.messages.count_tokens(model=..., messages=[...]) returns input_tokens.
  • Price: free to call. Limits are 5,000 / 10,000 / 20,000 requests per minute on the Start / Build / Scale tiers.
  • Coverage: text, system prompts, client tools, base64 images, base64 PDFs and thinking blocks.
  • Not supported: server tools (web search, code execution and so on), the MCP connector, url or file image and PDF sources, and the thread field.
  • Accuracy: the count is an estimate. Real billing can differ by a small amount, and output tokens are never counted.
  • Tokenizer: Claude 4.7 and later models produce about 30% more tokens for the same text than older models, so always count with the model you will actually use.

What the Token Counting API Is and When to Use It

The endpoint is POST /v1/messages/count_tokens. In the Python SDK it is client.messages.count_tokens(). You send the same model, system, messages, tools and thinking fields you would send to messages.create(), and you get back one number.

{ "input_tokens": 14 }

Claude does not run the model, so nothing is generated and nothing is billed. Use it when you need to:

  • Budget: estimate the dollar cost of a prompt or a whole job before you run it.
  • Fit the context window: check that a long document plus history still fits before Claude rejects it.
  • Route models: send short prompts to Haiku 5.5 and long ones to Sonnet 5.5 or Opus 5.5.
  • Trim prompts: measure how much a system prompt or tool list grows after each edit.
  • Plan migrations: compare counts on your old model and your new model before you switch.
Claude docs token counting endpoint card showing POST /v1/messages/count_tokens, body fields and input_tokens return value
Official Claude Platform Docs token counting page: one endpoint, one input_tokens field (checked 3 Dec 2026).

Note: do not use tiktoken or any OpenAI tokenizer for Claude. It is a different tokenizer, so its numbers will be wrong for Claude, especially on code and non-English text.

Prerequisites and Setup

You need Python 3.10 or newer, the official anthropic SDK and a Claude API key. This guide was checked against anthropic 2.16.0 (released 1 December 2026) and API version 2026-10-21.

  1. Get an API key. Create one in the Claude Console. If you have never done it, follow how to get a Claude API key.
  2. Install the SDK. Run pip install -U anthropic in a virtual environment.
  3. Set the key as an environment variable. On macOS or Linux run export ANTHROPIC_API_KEY="sk-ant-...". On Windows PowerShell use $env:ANTHROPIC_API_KEY="sk-ant-...". Never paste the key into your code.
  4. Check the version. Run python -c "import anthropic; print(anthropic.__version__)". It should print 2.16.0 or newer.
  5. Run a first count. Copy the first example below into count.py and run python count.py.

New to the SDK in general? The Claude API Python tutorial covers messages, streaming and errors from scratch.

Example 1: Count Text and System Prompts

This is the smallest useful call. It counts a system prompt plus one user message on Claude Opus 5.5.

import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY

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

print(response.input_tokens)  # the docs example returns 14

The response object has a single field, input_tokens. It is the total across the system prompt, all messages and any tools.

Count a whole file or a long conversation

You can pass a full chat history too. Every earlier user and assistant turn counts, because Claude re-reads the whole conversation on each request.

from pathlib import Path
import anthropic

client = anthropic.Anthropic()
doc = Path("report.md").read_text(encoding="utf-8")

history = [
    {"role": "user", "content": "Here is my report:\n\n" + doc},
    {"role": "assistant", "content": "Thanks, I have read it."},
    {"role": "user", "content": "List the three biggest risks."},
]

count = client.messages.count_tokens(
    model="claude-sonnet-5-5",
    system="You are a careful analyst. Answer in short bullet points.",
    messages=history,
)
print(f"This turn will send {count.input_tokens:,} input tokens")

Tip: the endpoint is stateless. To see how much an edit changed a prompt, count the old version and the new version and subtract.

Example 2: Count Tools

Tool definitions are sent as input on every request, so a long tool list quietly adds cost. Pass tools exactly as you would to messages.create().

import anthropic

client = anthropic.Anthropic()

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"],
        },
    }
]

response = client.messages.count_tokens(
    model="claude-opus-5-5",
    tools=tools,
    messages=[{"role": "user", "content": "What's the weather like in San Francisco?"}],
)
print(response.input_tokens)  # the docs example returns 403

Why 403 tokens for one tiny tool? When you use tools, Anthropic adds a tool use system prompt. The pricing page lists it as 286 tokens on Opus 5.5, Sonnet 5.5 and Haiku 5.5 with tool_choice set to auto or none.

Warning: on Opus 5.5, Sonnet 5.5, Fable 5.2 and Fable 5.1, a forced tool_choice of any or tool returns a 400 error, and that also applies to count_tokens. Use auto instead.

Server tools such as web search, web fetch, code execution and tool search are rejected by this endpoint. The advisor tool is the one exception, and for it the count covers only the executor’s first call. For more on tool definitions, see the Claude tool use tutorial.

Example 3: Count Images and PDFs

Images and PDFs must be sent as base64 to be counted. A block with a url source or a Files API file source returns an invalid_request_error.

Count an image

import base64
from pathlib import Path
import anthropic

client = anthropic.Anthropic()
image_b64 = base64.standard_b64encode(Path("chart.jpg").read_bytes()).decode("utf-8")

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

Claude cuts images into 28 x 28 pixel patches. An image costs about ceil(width / 28) x ceil(height / 28) visual tokens, after any downscaling.

Image size Standard tier tokens (older models) High-res tier tokens (Claude 4.7 and later)
200 x 200 px 64 64
1000 x 1000 px 1,296 1,296
1920 x 1080 px 1,560 (resized) 2,691
3840 x 2160 px (4K) 1,560 (resized) 4,784 (resized)

High-res models accept a long edge up to 2,576 px and 4,784 visual tokens. The vision docs say the 1000 x 1000 image costs about $5.18 per thousand images on Opus 5.5. See our Claude vision API tutorial for resizing tips.

Count a PDF

import base64
from pathlib import Path
import anthropic

client = anthropic.Anthropic()
pdf_b64 = base64.standard_b64encode(Path("contract.pdf").read_bytes()).decode("utf-8")

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

Each PDF page is sent as text plus a page image. The PDF docs say a page typically uses 1,500 to 3,000 text tokens, plus at most 1,568 visual tokens for its image. That is why counting the real file beats guessing.

Example 4: Count Thinking Blocks

Pass the thinking setting and any earlier assistant turns with their thinking blocks. On Opus 5.5 use {"type": "adaptive"}, because disabled thinking and budget_tokens are rejected on that model.

import anthropic

client = anthropic.Anthropic()

response = client.messages.count_tokens(
    model="claude-opus-5-5",
    thinking={"type": "adaptive"},
    messages=[
        {"role": "user", "content": "Are there infinitely many primes with n mod 4 == 3?"},
        {
            "role": "assistant",
            "content": [
                {
                    "type": "thinking",
                    "thinking": "This is a nice number theory question...",
                    "signature": "EuYBCkQYAiJAgCs1le6...",  # copy from the real response
                },
                {"type": "text", "text": "Yes, there are infinitely many..."},
            ],
        },
        {"role": "user", "content": "Can you write a formal proof?"},
    ],
)
print(response.input_tokens)

How thinking is counted depends on the model:

  • Keep-all models (Opus 4.5 and later Opus, Sonnet 4.6 and later Sonnet, Haiku 5.5, Fable and Mythos 5 to 5.2): thinking from earlier turns stays in context and counts as input.
  • Last-turn-only models (older Opus and Sonnet, Haiku 4.5 and earlier): the API strips earlier thinking, so it does not count.
  • The current assistant turn: its thinking always counts.

Remember that new thinking Claude generates is billed as output, which this endpoint cannot predict. Read more in our Claude extended thinking API guide.

The Same Call with curl

The raw HTTP request is handy for quick tests in a terminal. Note the API version header.

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"}]
  }'

Anthropic’s ant command line tool can do the same with ant messages count-tokens, if you already use it.

Estimate Cost Before Sending (Worked Examples)

The formula is simple. Input cost is counted tokens times the input price. Output cost is your expected output tokens times the output price, and you can use max_tokens as a worst case.

Current Claude API prices (checked 3 Dec 2026)

Model Model ID Input / MTok Output / MTok Cache read / MTok Batch (in / out)
Claude Fable 5.2 claude-fable-5-2 $8 $40 $0.20 $4 / $20
Claude Opus 5.5 claude-opus-5-5 $4 $20 $0.20 $2 / $10
Claude Sonnet 5.5 claude-sonnet-5-5 $2 $10 $0.10 $1 / $5
Claude Haiku 5.5 (prompt up to 100K) claude-haiku-5-5 $0.10 $0.50 $0.01 $0.05 / $0.25
Claude Haiku 5.5 (prompt over 100K) claude-haiku-5-5 $0.50 $2.50 $0.05 $0.25 / $1.25

MTok means one million tokens. Full details, including cache writes and fast mode, are in our Claude API pricing guide.

Worked example: a support bot with a 12,000-token prompt

Say count_tokens returns 12,000 input tokens (system prompt, tools and history). You expect about 1,000 output tokens, and you will send 10,000 requests a day.

Model Input cost per request Output cost per request Per request Per day (10,000)
Haiku 5.5 $0.0012 $0.0005 $0.0017 $17
Sonnet 5.5 $0.024 $0.010 $0.034 $340
Opus 5.5 $0.048 $0.020 $0.068 $680
Fable 5.2 $0.096 $0.040 $0.136 $1,360

The Sonnet 5.5 row is 12,000 x $2 / 1,000,000 = $0.024 for input, plus 1,000 x $10 / 1,000,000 = $0.01 for output. Running the same job through the Batch API halves every number.

Worked example: one image on Opus 5.5

A 1000 x 1000 px image is 1,296 visual tokens. At $4 per MTok that is 1,296 x 4 / 1,000,000 = $0.0052, matching the docs figure of about $5.18 per thousand images.

Quick answer: cost = (input_tokens x input price + expected output tokens x output price) / 1,000,000. Get input_tokens from count_tokens, and take prices from the official pricing page.

A Reusable Cost Calculator in Python

This snippet counts a request, then prints the input cost and a worst-case total using max_tokens. It also handles the Haiku 5.5 price step above 100,000 prompt tokens.

import anthropic

# USD per million tokens, from platform.claude.com pricing (checked 3 Dec 2026).
PRICES = {
    "claude-fable-5-2": {"in": 8.00, "out": 40.00},
    "claude-opus-5-5": {"in": 4.00, "out": 20.00},
    "claude-sonnet-5-5": {"in": 2.00, "out": 10.00},
    "claude-haiku-5-5": {"in": 0.10, "out": 0.50, "long_in": 0.50, "long_out": 2.50},
}
HAIKU_LONG_THRESHOLD = 100_000

client = anthropic.Anthropic()


def estimate_cost(request: dict, expected_output: int | None = None, batch: bool = False) -> dict:
    """Count input tokens for a Messages request and estimate its cost in USD."""
    model = request["model"]
    count_fields = {k: v for k, v in request.items() if k != "max_tokens"}
    input_tokens = client.messages.count_tokens(**count_fields).input_tokens

    p = PRICES[model]
    in_price, out_price = p["in"], p["out"]
    if "long_in" in p and input_tokens > HAIKU_LONG_THRESHOLD:
        in_price, out_price = p["long_in"], p["long_out"]
    if batch:
        in_price, out_price = in_price / 2, out_price / 2

    output_tokens = expected_output if expected_output is not None else request["max_tokens"]
    input_cost = input_tokens * in_price / 1_000_000
    output_cost = output_tokens * out_price / 1_000_000
    return {
        "model": model,
        "input_tokens": input_tokens,
        "input_cost": round(input_cost, 6),
        "output_cost_estimate": round(output_cost, 6),
        "total_estimate": round(input_cost + output_cost, 6),
    }


if __name__ == "__main__":
    req = {
        "model": "claude-sonnet-5-5",
        "max_tokens": 2000,
        "system": "You summarize meeting notes.",
        "messages": [{"role": "user", "content": open("notes.txt").read()}],
    }
    print(estimate_cost(req, expected_output=800))
    print(estimate_cost(req, expected_output=800, batch=True))

The function strips max_tokens because count_tokens does not take it. Prices change, so keep the PRICES table in one place and update it from the official page.

Tip: to track what you actually spent after the fact, read response.usage on each reply, or see our guide to Claude API cost tracking in the Console.

Tokenizer Notes per Model

Token counts are model-specific. The same text can produce a different number on a different model, so always pass the model you will really call.

Model group Tokenizer What it means for counts
Fable 5, 5.1, 5.2 and Mythos 5, 5.1, 5.2 Tokenizer introduced with Opus 4.7 A prompt counts the same on all six models
Opus 5.5, Opus 5, Opus 4.8, Opus 4.7, Sonnet 5.5, Sonnet 5, Haiku 5.5 Newer tokenizer (Claude 4.7 and later) About 30% more tokens than older models for the same text
Opus 4.6, Sonnet 4.6, Haiku 4.5 Older tokenizer Lower counts, but do not reuse them for newer models

The 30% figure is approximate, and the exact increase depends on your content. When you migrate, count the same request once on each model and compare the two input_tokens values.

The tokenizer also affects rate limits. A prompt that fit under your input tokens per minute limit on Sonnet 4.6 can use noticeably more of it on Sonnet 5.5.

Rate Limits of the Count Tokens Endpoint

Token counting is free but has its own requests per minute (RPM) limit, based on your usage tier.

Usage tier count_tokens RPM Monthly API spend cap (for context)
Start 5,000 $500
Build 10,000 $1,000
Scale 20,000 $200,000
Custom Arranged with sales None
Claude docs pricing and rate limits table for token counting: free, 5,000 RPM Start, 10,000 Build, 20,000 Scale
Official Claude Platform Docs: token counting is free with its own RPM limits (checked 3 Dec 2026).
  • Separate buckets: token counting and message creation have independent limits. Counting does not eat into your Messages RPM or token limits.
  • New accounts: new organizations may start in an Evaluation tier with lower limits that rise automatically.
  • Where to check: your tier and limits are on the Rate limits page in the Claude Console.
  • Request size: a count request can be up to 128 MB on the first-party API, the same as Messages. Partner clouds are lower (for example, 20 MB on Bedrock).

For more on tiers across providers, read LLM API rate limits and tiers explained.

Why the Count Differs from Actual Usage

Anthropic calls the count an estimate. Here is what can make the real usage numbers different from your count.

  • Small system differences: the actual input can differ by a small amount. Counts may include tokens Anthropic adds for system optimizations, and you are not billed for those.
  • No caching: count_tokens accepts cache_control but never uses caching. The real response splits input into input_tokens, cache_creation_input_tokens and cache_read_input_tokens, each with its own price.
  • Output is unknown: the endpoint counts input only. Output text and any new thinking are billed as output and only show up in usage.output_tokens.
  • Server tools: you cannot count web search, code execution or MCP requests. Their result tokens appear only in the real response.
  • Images: large images are downscaled before Claude sees them, which caps their cost. Counting the base64 image gives you the after-resize figure.

Note: caching can change your bill a lot. Cache reads on Opus 5.5 cost $0.20 per MTok instead of $4. If you reuse a long prefix, see how prompt caching cuts API costs.

Troubleshooting: Common Errors and Fixes

The Python SDK raises typed exceptions, so catch the narrow ones first. Here are the errors you are most likely to hit on this endpoint.

Error Likely cause Fix
400 invalid_request_error with a server tool Request includes web search, web fetch, code execution, tool search or the MCP connector Remove those tools from the count, or read usage from the real response
400 on an image or document block Source type is url or file Send the file as base64 for counting
400 tool_choice: type "tool" and "any" are not supported for this model. Forced tool choice on Opus 5.5, Sonnet 5.5 or Fable 5.1 / 5.2 Use {"type": "auto"}
400 on a request with thread Message threads cannot be counted Count the full conversation with system and tools
400 Invalid signature in thinking block ... bound to a different conversation History or tools changed after the thinking block was made Strip that thinking block and later ones, then stop editing history
401 authentication_error Missing, revoked or expired key Check ANTHROPIC_API_KEY in the same shell
404 not_found_error Typo in the model ID or a retired model (Sonnet 4.5 was retired on 30 Nov 2026) Use a current ID such as claude-sonnet-5-5
413 request_too_large Request over 128 MB Split large PDFs or downscale images
429 rate_limit_error Over your count_tokens RPM Slow down, cache counts for repeated prompts, or ask for a higher tier
529 overloaded_error Temporary API load The SDK retries twice by default; retry later

A safe error-handling pattern looks like this:

import anthropic

client = anthropic.Anthropic()

try:
    n = client.messages.count_tokens(
        model="claude-opus-5-5",
        messages=[{"role": "user", "content": "Hello"}],
    ).input_tokens
    print(n)
except anthropic.NotFoundError:
    print("Check the model ID")
except anthropic.RateLimitError:
    print("Too many count requests, slow down")
except anthropic.BadRequestError as e:
    print("Request not countable:", e.message)
except anthropic.APIStatusError as e:
    print("API error", e.status_code)
except anthropic.APIConnectionError:
    print("Network problem")

For 429 and 529 errors on the main Messages API, see our Claude API 429 and 529 fix guide.

Frequently Asked Questions

Is the Claude token counting API free?

Yes. Anthropic does not charge for count_tokens calls. You are limited only by requests per minute: 5,000 on Start, 10,000 on Build and 20,000 on Scale.

Does count_tokens use my Messages API rate limits?

No. Token counting and message creation have separate, independent rate limits. Heavy counting does not reduce what you can send to messages.create().

How accurate is the token count?

It is an estimate that can differ from real usage by a small amount. It also ignores caching and cannot know your output tokens, so compare it with response.usage on a few real calls.

Can I count tokens for images and PDFs from a URL?

No. Blocks with a url or Files API file source are rejected. Download the file and send it as base64 to count it.

Can I use tiktoken to count Claude tokens?

No. tiktoken is OpenAI’s tokenizer and gives wrong numbers for Claude. Use client.messages.count_tokens() with the exact Claude model ID.

Why did my token count go up after switching models?

Claude 4.7 and later models use a newer tokenizer that produces about 30% more tokens for the same text. Recount your prompts on the new model before estimating cost.

Does count_tokens work with prompt caching?

You can include cache_control, but the endpoint does not apply caching. It always returns the full input count, so apply cache read prices yourself in your estimate.

Is token counting available on Bedrock, Vertex and Foundry?

Yes, the docs list it on the Claude API, Amazon Bedrock, Claude Platform on AWS, both Google Cloud options and Microsoft Foundry. It is not available in Managed Agents.

Sources

Free weekly email

Get new AI guides every week

One short weekly email with our newest local AI, ComfyUI and AI tool guides. No spam, no pop-ups, just the good stuff.

Free. Unsubscribe anytime in one click. We only use your email to send this newsletter. See our privacy policy.

Woman in a server room holding a tablet with a TOKEN COUNT card, hook 5,000 RPM token counter