How to Count Tokens: tiktoken, Anthropic's API and usage (2026)
The most reliable way to count tokens is to use the method from the model's own provider: for OpenAI models, use the open-source library tiktoken locally; for Claude, use Anthropic's count tokens endpoint; for everyone else, check their docs. Any generic "token counter" web page can only give you an estimate, because the same text can produce a different token count on a different model.
This article follows the order "estimate first, verify second, and treat the billing numbers as final."
Why does the same text have different token counts in different models?
A token is a piece produced by the model's tokenizer. It is not a character and not a word. Each model family has its own vocabulary and splitting rules, so:
- The same sentence might be 20 tokens for one provider and 24 for another.
- Differences tend to be larger for Chinese, code, emoji and rare symbols than for English.
- Besides the text you write, role markers, system prompts and tool definitions in the request also use tokens.
For the basics of what a token is and why billing is based on it, see What is a token in an LLM. The one takeaway here: don't use one model's count to predict another model's bill.
How do you count tokens locally with tiktoken?
tiktoken is OpenAI's open-source tokenizer library and applies to OpenAI models. Installation and a minimal example:
pip install tiktoken
import tiktoken
# Get a tokenizer by encoding name; which encoding a model uses is defined in OpenAI's official docs
enc = tiktoken.get_encoding("o200k_base")
text = "你好,这是一段用来测试的文本。Hello, tokens!"
ids = enc.encode(text)
print(len(ids)) # number of tokens
print(enc.decode(ids)) # decode back, to check
You can also let the library pick the encoding by model name: tiktoken.encoding_for_model("<model name>"). If the library doesn't recognize the model name yet, it raises a KeyError. In that case, fall back to get_encoding and specify the encoding manually.
Two things to note:
len(ids)is only the token count of the plain text. When you call an interface like Chat Completions that takes a messages array, each message also carries extra formatting overhead. See the official OpenAI docs and cookbook for the exact calculation, and treat them as authoritative. For how to structure the messages array, see What is Chat Completions.- tiktoken does not apply to Claude, Gemini, or Chinese-developed models. Using it on those only gives you a rough order of magnitude.
How do you count tokens for Claude?
Anthropic provides a dedicated count tokens endpoint, so you don't have to actually generate a reply. The path is POST /v1/messages/count_tokens. The request body is essentially the same as the Messages API, and the response contains input_tokens.
Calling it with curl:
curl https://api.anthropic.com/v1/messages/count_tokens \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"model": "<model name>",
"messages": [{"role": "user", "content": "你好,Claude"}]
}'
The response looks like {"input_tokens": <number>}. In the official Python SDK, the equivalent is client.messages.count_tokens(model=..., messages=[...]).
A few notes:
- Both the
x-api-keyandanthropic-versionheaders are required. This differs from OpenAI'sAuthorization: Bearerstyle; see Authorization: Bearer vs. x-api-key for the difference. - You need an Anthropic API key. For how to get one, see How to get a Claude API key.
- Rate limits, whether the endpoint is billed, and whether it can include images and tool definitions are all defined by Anthropic's official docs. The docs also state that the returned number is an estimate and may differ slightly from an actual call.
How do you count tokens for other models?
| Model source | Local / API method | Notes |
|---|---|---|
| OpenAI | tiktoken (local) | Watch for extra message-format overhead |
| Anthropic | count tokens endpoint | Requires an API key |
| Gemini | count tokens method in the official SDK | Follow Google's official docs |
| DeepSeek, Qwen and other Chinese models | Check whether the provider offers a tokenizer or counting endpoint | If not, work backwards from the usage field in the response |
When in doubt, use the last approach, which works for every provider.
How do you use the usage field in the response for a final check?
Almost every API response includes usage fields, such as input tokens and output tokens. The provider counts these itself, and they are what you are billed on. The method is simple:
- Estimate a value using the methods above.
- Send one real request and note the input token count in the response.
- Calculate the ratio between the two, then apply that ratio as a correction to similar requests from then on.
Output tokens can't be calculated exactly in advance, because they depend on how much the model actually writes. You can cap them with max_tokens; for how to set it, see How to set max_tokens.
If your bill differs a lot from your own counts, work through it line by line using the method in How to check wrong API billing.
Once you have the count, how do you convert it to monthly usage and cost?
A single request's number is only a starting point. To budget properly, record the number of requests over a period, the average input and output, and multiply by the unit price. Continue with:
- How to estimate your monthly token usage: a three-step logging method
- How token billing works: breaking one call's bill into line items
Prices and model availability change from provider to provider. When you need to compare, see cdnping's model monitor, which is based on the public OpenRouter API and shows each model's availability, latency and price-change history across inference providers.
What if you don't want to juggle keys from several providers?
For beginners, the hard part is often not counting tokens but registering, paying and managing keys separately for each provider. AGI Plan is a multi-provider LLM aggregation gateway. It is billed monthly by subscription, settled in RMB (Chinese yuan), and needs no overseas credit card. Tools like Claude Code and Codex only need a changed endpoint address. Its metering unit is the CU: 1 CU equals 1,000 output tokens of the baseline model, so the token estimation methods you learn here can be used directly to estimate CU consumption. Some models are available only outside mainland China; check the AGI Plan models page for specifics. To learn how to connect, see the getting started page. AGI Plan is a commercial partner of cdnping, and it states clearly that it is not an officially authorized channel. Read the details carefully before deciding whether it suits you.
Next steps
- Use tiktoken or the count tokens endpoint to count the tokens in the prompt you use most.
- Send one real request, compare against the usage in the response, and work out your estimation error.
- Log your calls for a week, then work out a budget using the monthly usage estimate method.