Claude Tokenizer: How to Count and Inspect Text Tokens

Learn what the Claude tokenizer does to your text, how to count tokens with Anthropic's token-counting API, and how to check results without altering content.

Claude does not read your text as characters or words. It reads tokens. You need a token count produced by Anthropic's own tokenizer, not a general word counter, if you want to know how much of a context window a document uses, estimate request size, or understand why two nearly identical strings measure differently. This guide explains what tokenization does, how to get a count for Claude, and how to keep the text you measure identical to the text you send.

What the Claude tokenizer does to your text

A tokenizer splits input text into units called tokens and maps each one to a numeric ID that the model processes. A token can be a whole word, part of a word, punctuation, whitespace or a byte sequence. When you count tokens, the operation is read-only. It does not edit, normalize or save a changed copy of your text. The result is a number, not a transformed string.

Three points of scope matter. First, token counts are tied to the model's tokenizer, so counts from other vendors' tokenizers are not a reliable stand-in for Claude. Second, words and characters do not convert to tokens at a fixed ratio. The ratio shifts with language, script, source code and whitespace. Third, a request count covers everything sent: the system prompt, every message, any tool definitions or attachments, and the structure the API wraps around messages. The count for a full request is therefore not the same as the count for the bare string.

What you can and cannot inspect

Anthropic does not publish a downloadable tokenizer for current Claude models. There is no official way to see individual token boundaries or token IDs. Two things are documented. The Messages API has a token-counting endpoint (path /v1/messages/count_tokens), and every normal response includes usage fields such as input_tokens and output_tokens. An older local counting helper in the Python SDK targeted earlier models and should not be relied on for current ones. The evidence for this guide did not include a dated confirmation of endpoint details, so check Anthropic's current API documentation before you depend on the exact parameter names shown below.

Before you start

  • An Anthropic API key, stored in the environment variable ANTHROPIC_API_KEY
  • Python 3 with the official SDK installed (pip install anthropic)
  • The exact model ID you plan to use, because counts depend on the model
  • The text saved as a UTF-8 file, exactly as you intend to send it

Count tokens step by step

  • 1. Read the text without changing whitespace or line endings.
  • 2. Build the same request you will actually send: model, system prompt, messages and any tools.
  • 3. Call the token-counting method instead of creating a message.
  • 4. Read the input_tokens value from the result.
  • 5. Optionally, send the real request once and compare its usage.input_tokens with the count.
import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY

# newline="" keeps \r\n and \n exactly as stored in the file
with open("sample.txt", encoding="utf-8", newline="") as f:
    text = f.read()

result = client.messages.count_tokens(
    model="YOUR_MODEL_ID",
    system="You are a helpful assistant.",
    messages=[{"role": "user", "content": text}],
)
print(result.input_tokens)

Match the options to your real request. Include system only if the real request has a system prompt. Pass the same tools list if the real request uses tools. A count taken without these will come out lower than what the real request consumes.

Before-and-after example

The example below is illustrative and has not been run. The output line shows the shape of the result, not a measured value. Line endings are written out as \r\n so they are visible.

Before (contents of sample.txt):
Invoice #1042\r\n
Total: $19.99\r\n

After (printed by the script):
<an integer: result.input_tokens>

sample.txt itself: unchanged

Check the result

  • Run the count twice on the same input. If the numbers differ, something in your input is changing between runs, such as timestamps or generated IDs.
  • Send the real request once and compare usage.input_tokens with your count. Treat the count as an estimate. A small mismatch is not alarming, but a large one usually means the two requests are not built the same way.
  • Confirm the source file was not modified. Run sha256sum sample.txt before and after the script; the hashes should match.

Keep the measured text identical to the sent text

Tokenizers work on exact characters. Common clean-up steps change what gets measured, even when the text looks the same on screen.

Change | Example | Why the count may shift
Line endings converted | \r\n becomes \n | One character removed per line
Trailing whitespace stripped | "end " becomes "end" | Spaces removed
Unicode normalization | é as U+00E9 vs e + U+0301 | Same look, different code points
Invisible characters | U+200B zero-width space, U+00A0 no-break space, U+FEFF byte order mark | Not visible, but still sent
Typographic quotes | " vs “ | Different characters

To make invisible or non-ASCII characters explicit before counting, list their code points:

import unicodedata

for ch in text:
    if not ch.isascii() or not ch.isprintable():
        print(f"U+{ord(ch):04X} {unicodedata.name(ch, '<control>')}")

If you decide to clean the text, for example by removing a byte order mark, work on a copy and keep the original. Count both versions, then send the version you counted.

Estimating where tokens fall

Token boundaries are not exposed, but you can approximate how many tokens a segment adds. Count a minimal request with the segment and without it, then subtract. Text joined together can tokenize differently from its parts, so the per-line figures will not always add up to the whole-document count. This technique has not been verified here against real output. Each call is a separate API request and is subject to your account's rate limits.

def count(content):
    return client.messages.count_tokens(
        model="YOUR_MODEL_ID",
        messages=[{"role": "user", "content": content}],
    ).input_tokens

baseline = count("x")
for line in text.splitlines(keepends=True):
    print(count("x" + line) - baseline, repr(line))

Gaps in this guide

  • No measured token counts are given; the sample results are placeholders.
  • Rate limits, pricing and model coverage for the counting endpoint were not confirmed.
  • Token costs for images, PDFs and tool definitions are not quantified.
  • Whether all current Claude models share one tokenizer was not confirmed.