Counting Tokens and Cost
Part of the Calling Models From Code section of Coddy's AI Engineering journey. Lesson 11 of 22.
You pay for tokens: every token you send and every token the model writes. Output tokens cost more than input tokens. Prices are quoted in dollars per million tokens, so a call costs input_tokens / 1,000,000 x input price plus the same for output.
To know the input size before you send, call client.messages.count_tokens with the same model, messages and, if you use them, system and tools. It returns an object whose input_tokens matches what the call will report in usage.
messages = [{"role": "user", "content": "What is the capital of France?"}]
count = client.messages.count_tokens(model="claude-opus-5-5", messages=messages)
print(count.input_tokens)
response = client.messages.create(model="claude-opus-5-5", max_tokens=100, messages=messages)
print(response.usage.input_tokens, response.usage.output_tokens)
cost = response.usage.input_tokens / 1_000_000 * 4.00 + response.usage.output_tokens / 1_000_000 * 20.00
print(f"${cost:.6f}")This prints 15, 15 8 and $0.000220. The stand-in counts tokens with a simple rule; a real tokenizer splits text differently, so read the counts instead of guessing them. Counting tokens costs nothing, which makes it a good check before a long request.
Challenge
EasyShow what a question costs before and after it is sent. The starter holds the Claude Opus 5.5 prices from November 2026: $4 per million input tokens and $20 per million output tokens. Prices change, so a real program reads them from Anthropic's pricing page.
- Count the tokens of
messageswithmodel="claude-opus-5-5"and printEstimate: <n> tokens. - Send the messages with
max_tokens=200. PrintInput: <n>andOutput: <n>fromusage. - Work out the cost with
PRICE_INPUTandPRICE_OUTPUTand printCost: $followed by it with 6 decimal places.
For example, for the input What is the boiling point of water? the program prints:
Estimate: 16 tokens
Input: 16
Output: 12
Cost: $0.000304Try it yourself
import coddy_ai as anthropic # in production: import anthropic
client = anthropic.Anthropic()
# Claude Opus 5.5 prices in dollars per million tokens (November 2026)
PRICE_INPUT = 4.00
PRICE_OUTPUT = 20.00
question = input()
messages = [{"role": "user", "content": question}]
# 1. Count the input tokens before sending and print "Estimate: <n> tokens"
# 2. Send the question (max_tokens=200) and print "Input: <n>" and "Output: <n>"
# 3. Print "Cost: $<cost>" with 6 decimal places
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Calling Models From Code
3Tokens and Structure
Counting Tokens and CostHandling API ErrorsJSON Schema OutputClassifying With EnumsRecap: Review SorterPractice on your own: Online Python compiler