Lesson 5.2
Tokens, Pricing and Counting
What a token is, how input and output tokens are priced differently, how to count them before you send a request, and how to turn the usage object into a cost figure.
Every Claude bill is a function of tokens: how many went in, how many came out, and how many were served from cache. Developers who understand the token economy design cheaper prompts, set sensible max_tokens, and can explain an invoice. The exam tests the pricing model's structure, the counting endpoint, and the meaning of each usage field.
What a token is
A token is the unit the model reads and writes: roughly three to four characters of English text, less for code, punctuation-heavy content and many non-Latin scripts. Numbers, whitespace and JSON braces all consume tokens. Images are converted to tokens based on their pixel area, and PDFs cost text tokens plus image tokens for each rendered page. Tokenisers differ between model generations, so the same prompt can produce different counts on different models.
The pricing structure
Prices are quoted per million tokens and differ in four ways you must remember:
| Dimension | Principle |
|---|---|
| Input vs output | Output tokens cost several times more than input tokens |
| Model tier | Opus costs more than Sonnet, which costs more than Haiku |
| Cache status | Cache writes cost a premium over base input; cache reads cost a small fraction of it |
| Batch | Message Batches requests are discounted on both input and output |
Extended thinking tokens are billed as output tokens. Tool definitions, system prompts and the whole conversation history count as input on every request, which is why long agent loops get expensive without caching. The current figures live on the pricing page at docs.anthropic.com; code that hard-codes prices should load them from configuration so they can be updated without a deploy.
Reading the usage object
"usage": {
"input_tokens": 1860,
"output_tokens": 412,
"cache_creation_input_tokens": 0,
"cache_read_input_tokens": 12400
}
input_tokensis the uncached portion only.cache_creation_input_tokenswere written to the cache this request at the write premium.cache_read_input_tokenswere served from cache at the discounted rate.- Total prompt size is the sum of all three input fields.
A cost calculation therefore needs four rates:
def cost_usd(usage, p): # p: prices per million tokens for this model
return (usage.input_tokens * p["input"]
+ usage.cache_creation_input_tokens * p["cache_write"]
+ usage.cache_read_input_tokens * p["cache_read"]
+ usage.output_tokens * p["output"]) / 1_000_000
Streamed responses report input usage in message_start and final output usage in message_delta; the SDK's final message object combines them.
Counting before you send
POST /v1/messages/count_tokens returns the input token count for a request without running it and without charge. Pass the same model, system, messages and tools you intend to send; tools and system prompts count.
count = client.messages.count_tokens(
model=MODEL, system=SYSTEM_PROMPT, tools=TOOLS,
messages=history + [{"role": "user", "content": new_text}],
)
if count.input_tokens > BUDGET:
history = trim(history)
const { input_tokens } = await client.messages.countTokens({
model: MODEL, system: SYSTEM_PROMPT, messages,
});
Use it to enforce context budgets, estimate cost before a batch, decide when to summarise history, and compare prompt variants. Do not use third-party tokenisers built for other providers; they under- or over-count Claude tokens significantly. The count endpoint has its own rate limit, separate from Messages.
Levers that reduce token spend
- Shorten the prompt. Remove redundant instructions and examples; measure with
count_tokens. - Cap output. Set
max_tokensto what the task needs and ask for concise answers; output is the expensive side. - Cache the stable prefix. System prompts, tool definitions and documents reused across requests should sit behind a
cache_controlbreakpoint (lesson 5-3). - Batch the bulk work. Anything not latency-sensitive belongs in the Batches API.
- Right-size the model. Route simple tasks to a smaller tier (lesson 5-1).
- Resize images. Downscale to the documented maximum useful dimensions before encoding.
- Trim history. Summarise or drop old turns in chat applications (lesson 6-3).
Monitoring spend
The Console shows usage and cost by model, workspace and API key, and organisations can set spend limits per workspace. For programmatic reporting, the Admin API exposes usage and cost reports to Admin API keys. Attribute spend to features by giving each feature its own key or workspace, and log usage per request with a feature tag so you can reconcile the two views.
Exam focus
- Output tokens cost several times more than input tokens; prices also vary by tier, cache status and batch versus real-time.
usage.input_tokensexcludes cached tokens; total prompt size isinput_tokens + cache_creation_input_tokens + cache_read_input_tokens.- Extended thinking tokens are billed as output.
count_tokensis free, model-specific, and countssystem,toolsandmessagestogether; use it for budgeting, not third-party tokenisers.- Images are priced by pixel area and PDFs by text plus page images; resizing saves money.
- Current prices change and should be read from the pricing page or configuration, never hard-coded in logic.
Check yourself
5 questions
1.How are input tokens and output tokens priced relative to each other on the Claude API?
2.A response contains: "usage": {"input_tokens": 1200, "output_tokens": 300, "cache_read_input_tokens": 8000, "cache_creation_input_tokens": 0} How should the input side be interpreted?
3.What does the token counting endpoint (client.messages.count_tokens / countTokens) return, and what does it cost?
4.A developer sizes prompts with tiktoken and sets context budgets from its counts. The requests sometimes exceed the context window anyway. What is wrong?
5.Which of the following count towards the input tokens billed for a Messages request?
