Claude Tokens and Context Windows: Counting Tokens in Python
👋 In plain words: Claude does not read words, it reads tokens. Every request has a fixed token budget called the context window, and you pay for every token in and out. This lesson shows you how to count tokens, read the token usage on every reply, and plan a request that fits the budget.
Tokens decide three things in every Claude application: whether a request fits, how long the reply can be, and what it costs. In this lesson you will learn what a token is, count tokens with the official endpoint, read the usage fields, check a model’s context window with the Models API, and turn token counts into a cost estimate you can put in a test report.
🔑 Key terms
- Token: the unit Claude reads and writes. A token is often a short word or part of a longer word; code and non-English text use more tokens per character.
- Tokenizer: the rule that splits text into tokens. Different Claude model generations use different tokenizers.
- Context window: the maximum number of tokens a model can take as input in one request (system prompt, tools, messages and documents together).
- max_tokens: the most tokens Claude may write in its reply. It is a ceiling you set on each request.
- Usage: the token counts the API reports on every response.
💡 Think of it like this
The context window is a suitcase with a fixed size. Your system prompt, tool definitions, the conversation history and any documents all go in it. max_tokens is the space you keep free for what Claude will pack on the way back. If the suitcase is full, nothing more fits, however important it is.
🪜 Step 1: Understand what a token is
A model does not see letters or words. It sees a sequence of token IDs. Three facts matter for developers:
- Tokens are not words. Common English words are often one token. Long or rare words, numbers, code symbols and many non-English scripts split into several tokens.
- Tokenizers change between model generations. Anthropic’s model documentation notes that the tokenizer introduced with Claude Opus 4.7 can produce roughly 1× to 1.35× as many tokens for the same text as older models. Re-measure when you change models.
- Never estimate Claude tokens with another vendor’s tokenizer. Libraries such as
tiktokenbelong to OpenAI and give the wrong count for Claude. Use Claude’s own token counting endpoint.
🪜 Step 2: Count tokens before you send
The token counting endpoint (POST /v1/messages/count_tokens) takes the same model, system, messages and tools as a real request and returns the input token count. It does not generate a reply.
📄 count_tokens.py
import anthropic
client = anthropic.Anthropic()
bug_report = (
"Steps: open /checkout, apply coupon SAVE10, pay with Visa.\n"
"Expected: total reduced by 10%. Actual: total unchanged and coupon shows 'applied'.\n"
"Browser: Chrome 142, Windows 11. Happens every time."
)
count = client.messages.count_tokens(
model="claude-opus-5-5",
system="You are a QA triage assistant. Classify bug reports by severity.",
messages=[{"role": "user", "content": bug_report}],
)
print("input tokens:", count.input_tokens)⌨️ Terminal
python count_tokens.py🖥️ Output (sample run)
input tokens: 85
- Pass the same model you will use for the real call. Counts are model-specific.
- Use it in a pre-flight check: if the count plus your planned
max_tokensexceeds the context window, trim or split the input before you send.
🪜 Step 3: Read usage on every reply
Every response reports what you were billed for in response.usage:
📄 usage.py
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=300,
messages=[{"role": "user", "content": "List 3 risks of testing only on Chrome."}],
)
u = response.usage
print("input_tokens :", u.input_tokens)
print("output_tokens :", u.output_tokens)
print("cache_creation_input_tokens:", u.cache_creation_input_tokens)
print("cache_read_input_tokens :", u.cache_read_input_tokens)
print("stop_reason :", response.stop_reason)⌨️ Terminal
python usage.py🖥️ Output (sample run)
input_tokens : 27
output_tokens : 62
cache_creation_input_tokens: 0
cache_read_input_tokens : 0
stop_reason : end_turn
| Field | Meaning |
|---|---|
input_tokens |
Input tokens billed at the normal rate (after any cache hits) |
output_tokens |
Tokens Claude wrote, including thinking tokens |
cache_creation_input_tokens |
Input tokens written to the prompt cache on this call |
cache_read_input_tokens |
Input tokens read from the cache, billed at a much lower rate |
🪜 Step 4: Check the context window and output limit
Hard-coding limits goes stale. The Models API returns the current limits for each model: max_input_tokens is the context window and max_tokens is the largest output you may request.
📄 model_limits.py
import anthropic
client = anthropic.Anthropic()
for model_id in ["claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5"]:
m = client.models.retrieve(model_id)
print(f"{m.display_name:<18} context={m.max_input_tokens:>9,} max output={m.max_tokens:>7,}")⌨️ Terminal
python model_limits.py🖥️ Output (sample run)
Claude Opus 5.5 context=1,000,000 max output=128,000
Claude Sonnet 5.5 context=1,000,000 max output=128,000
Claude Haiku 5.5 context=1,000,000 max output=128,000
According to Anthropic’s model catalog, the current Opus 5.5, Sonnet 5.5 and Haiku 5.5 models each have a 1M-token context window and up to 128K output tokens. Older models can differ: Claude Haiku 4.5 has a 200K context window and 64K maximum output.
max_tokens values need streaming. The SDK refuses very large non-streaming requests because they could exceed HTTP timeouts. Use client.messages.stream(...) for long outputs (Lesson 9).🪜 Step 5: Plan a request that fits
Think of each request as a budget:
input (system + tools + history + documents) + max_tokens ≤ what the model allows
Use this checklist for every feature:
- Count the fixed parts once: system prompt and tool definitions.
- Estimate the variable parts: user input, retrieved documents, conversation history.
- Set
max_tokensfor the longest answer you really need. Classification needs a few hundred tokens; a code review may need many thousands. - Decide what happens when it does not fit: summarise old turns, drop tool output, retrieve fewer documents, or split the job. Lesson 19 covers these techniques.
🌍 Real-world example: Ravi’s log analyser
Ravi sends whole CI logs to Claude. Most are 20K tokens, but one nightly run produced a 2-million-token log, and the request failed. He adds a pre-flight count_tokens check. Logs over 150K tokens are cut to the lines around each FAILED marker before sending, and the report says which parts were cut.
🪜 Step 6: Turn tokens into cost
Prices are per million tokens (MTok) and differ by model. These are Anthropic’s first-party API list prices for the current models, as of November 2026:
| Model | Input $/MTok | Output $/MTok |
|---|---|---|
Claude Opus 5.5 (claude-opus-5-5) |
$4.00 | $20.00 |
Claude Sonnet 5.5 (claude-sonnet-5-5) |
$2.00 | $10.00 |
Claude Haiku 5.5 (claude-haiku-5-5) |
$0.10 | $0.50 (for prompts up to 100K tokens) |
This calculator runs locally. It turns the usage numbers you log into dollars:
📄 cost.py
PRICES = { # USD per million tokens: (input, output)
"claude-opus-5-5": (4.00, 20.00),
"claude-sonnet-5-5": (2.00, 10.00),
"claude-haiku-5-5": (0.10, 0.50),
}
def request_cost(model: str, input_tokens: int, output_tokens: int) -> float:
price_in, price_out = PRICES[model]
return input_tokens / 1_000_000 * price_in + output_tokens / 1_000_000 * price_out
# A nightly job: 2,000 failure reports, about 1,200 input and 300 output tokens each
runs, tokens_in, tokens_out = 2_000, 1_200, 300
for model in PRICES:
total = runs * request_cost(model, tokens_in, tokens_out)
print(f"{model:<18} ${total:8.2f} per night")⌨️ Terminal
python cost.py🖥️ Output
claude-opus-5-5 $ 21.60 per night
claude-sonnet-5-5 $ 10.80 per night
claude-haiku-5-5 $ 0.54 per night
- Output tokens cost five times more than input tokens on all three models, so long answers and heavy thinking dominate cost.
- Cache reads and batch processing lower these numbers further. Module 10 covers both.
🧪 Practice Questions
Question 1. A developer estimates Claude input size with an OpenAI tokenizer library and sets a hard limit from that number. Requests near the limit fail with context errors. What is the best fix?
- A. Increase max_tokens
- B. Count tokens with Claude’s count_tokens endpoint using the same model as the real request
- C. Switch to a model with a smaller context window
- D. Divide character count by 4 instead
Show answer
Answer: B. Claude tokenizers differ from other vendors’ and between model generations. The count_tokens endpoint returns the real count for the model you will call.
Question 2. A reply shows a short three-sentence answer, but usage.output_tokens is very high. What is the most likely reason?
- A. The input was cached
- B. Thinking tokens are counted as output tokens
- C. usage counts characters, not tokens
- D. The stop_reason was end_turn
Show answer
Answer: B. Thinking happens on current models even when its text is not displayed, and it is billed as output. Lower the effort level if the task does not need deep reasoning.
Question 3. Which two values together must fit what the model allows for a request? (Choose 2.)
- A. All input tokens: system prompt, tools, history and documents
- B. The max_tokens you request for the reply
- C. The number of requests per minute
- D. The size of the Python SDK
Show answer
Answer: A and B. The context window bounds input, and max_tokens bounds the output you ask for. Rate limits are a separate constraint.
Question 4. Your team switches a feature to a newer model generation. What should you re-check first?
- A. Nothing; token counts are the same for every Claude model
- B. Token counts and cost, because the tokenizer may produce more tokens for the same text
- C. Only the output prices
- D. Only the system prompt wording
Show answer
Answer: B. Anthropic notes that newer tokenizers can produce more tokens for the same text, which changes budgets and cost. Re-baseline with count_tokens.
📝 Assignment
- Task 1: Count the tokens of your own team’s longest bug report or test case with
count_tokens.
✅ Done when: you have the token count and the character count side by side. - Task 2: Add a
budget_check(text, limit)function that counts tokens and raisesValueErrorwhen a prompt is over the limit, and write a pytest test for it with a short and a long input.
✅ Done when: both tests pass. - Stretch: Extend
cost.pyto read a CSV of logged usage (model,input_tokens,output_tokens) and print the total cost per model.
✅ Done when: the script prints one total per model from your CSV.
❓ Frequently Asked Questions
🤔 How many words is one Claude token?
It varies with the text and the model’s tokenizer. Plain English is roughly three-quarters of a word per token, but code and other languages use more tokens. Always count with the API for real decisions.
🤔 What is the context window of Claude Opus 5.5?
Anthropic’s model catalog lists 1M tokens of context and up to 128K output tokens for Claude Opus 5.5. Query the Models API for live values.
🤔 Does count_tokens cost money?
It does not generate output. Check Anthropic’s current documentation for its pricing and rate limits, and avoid calling it in tight loops.
🤔 Why did my reply stop in the middle of a sentence?
It hit max_tokens, and stop_reason is max_tokens. Raise the limit, ask for a shorter answer, or continue the response in a follow-up request.
🏁 Summary
- Tokens are what Claude reads, writes and bills; tokenizers differ by model generation.
- Use
messages.count_tokenswith the real model, never another vendor’s tokenizer. response.usagereports input, output and cache tokens; output includes thinking.- Get limits from the Models API: current Opus, Sonnet and Haiku 5.5 have 1M context and 128K output.
- Cost = tokens × price per MTok; output tokens cost five times more than input.
Next, continue with Claude Messages API Roles: user, assistant and System Prompts.
Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.