Tokenization and cost math
Models do not read characters or words, they read tokens: chunks of text from a fixed vocabulary learned during training. Every limit you care about, context window size, rate limits, latency and price, is denominated in tokens. If you can estimate tokens per request and requests per day, you can estimate your bill, and that estimate is the first number a product manager will ask you for.
Why it matters
Token counts surprise people in three ways. First, they vary by tokenizer: the same paragraph can be a noticeably different number of tokens on different model families. Second, they vary by language and content: English prose is efficient, while code, JSON, numbers and many non-Latin scripts take more tokens per character. Third, they hide in places you forget: system prompts, tool definitions, retrieved documents and the full conversation history are re-sent on every turn. A chat feature where each turn re-sends a long history grows its cost per message as the conversation gets longer.
How it works
Most modern tokenizers are byte pair encoding (BPE) variants. Training starts from bytes and repeatedly merges the most frequent adjacent pair into a new token until the vocabulary hits a target size. Common words become single tokens, rare words split into pieces, and any byte sequence can still be encoded, so there is no "unknown word". OpenAI's open-source tiktoken library implements its encodings; o200k_base, for example, is the encoding listed for the GPT-4o family in OpenAI's cookbook. Other providers use their own tokenizers and expose counting endpoints instead of publishing them.
Rendering diagram…
A rough English heuristic is about three quarters of a word per token, but never bill from heuristics. Use the provider's counter. Anthropic exposes POST /v1/messages/count_tokens, which accepts the same body as a Messages request (including tools, images and PDFs) and returns the input token count. Gemini has a countTokens method. For OpenAI models you can count locally with tiktoken.
The cost formula
For a single request:
cost = input_tokens * input_price
+ cached_input_tokens * cached_price
+ output_tokens * output_price
Prices are quoted per million tokens and change often, so pull them from the provider's pricing page at build time rather than hard-coding them. Output tokens cost several times more than input tokens across the major providers, and reasoning tokens are billed as output. Prompt caching changes the input side: on Anthropic, cache reads are billed at a fraction of the base input price while cache writes carry a premium (see context windows and caching). Batch APIs from the major providers offer discounted pricing for asynchronous jobs.
Reference architecture
Cost control is a pipeline, not a one-off spreadsheet. Count before you send, record what you were billed, and aggregate by feature.
Rendering diagram…
The response's usage object is the source of truth for billing. Estimates are for budgeting and guardrails.
Code
Here is a small estimator. It counts tokens locally with tiktoken for a quick estimate, asks Anthropic's counting endpoint for an exact Claude count, and projects monthly cost. The prices are placeholders you should load from config.
import tiktoken
import anthropic
# Placeholder prices in USD per million tokens. Load real ones from config.
PRICES = {"input": 3.00, "output": 15.00}
def local_estimate(text: str) -> int:
enc = tiktoken.get_encoding("o200k_base")
return len(enc.encode(text))
def claude_count(system: str, user: str, model: str = "claude-sonnet-4-6") -> int:
client = anthropic.Anthropic()
result = client.messages.count_tokens(
model=model,
system=system,
messages=[{"role": "user", "content": user}],
)
return result.input_tokens
def monthly_cost(input_tokens: int, output_tokens: int, requests_per_day: int) -> float:
per_request = (input_tokens * PRICES["input"] + output_tokens * PRICES["output"]) / 1_000_000
return per_request * requests_per_day * 30
system = "You are a support assistant for an online bookstore. " * 20
question = "Where is my order #18273? It was due yesterday."
print("tiktoken estimate:", local_estimate(system + question))
inp = claude_count(system, question)
print("Claude input tokens:", inp)
print("Projected monthly cost: $%.2f" % monthly_cost(inp, 300, 5_000))
Notice the two counts will not match exactly. That is expected: different tokenizers, plus the provider adds formatting tokens around messages.
Trade-offs and pitfalls
- Tokenizer mismatch. Using
tiktokento estimate a non-OpenAI model is fine for rough sizing and wrong for billing. - Hidden context. Tool definitions and long system prompts are paid on every call. A large tool catalog can cost more than the user's actual message.
- Conversation growth. Re-sending the full history makes per-turn cost grow with conversation length. Summarize or window older turns.
- Output caps. A generous
max_tokensdoes not cost anything unless used, but verbose prompts invite verbose answers. Ask for concise output when you want it. - Images, audio and PDFs are tokens too. Providers convert them at documented rates (Gemini documents fixed tokens-per-second rates for audio and video), and a scanned PDF can cost far more than its text suggests.
- Non-English users. If your users write in languages that tokenize less efficiently, your per-user cost is higher. Budget per locale.
- Price drift. Providers cut and restructure prices regularly. Keep prices in config and recompute dashboards from raw token counts.
Checklist
- Prices live in config, sourced from the provider pricing page.
- Every call logs input, cached input and output tokens from the
usagefield. - Costs are aggregated by feature and tenant, with spend alerts.
- Long conversations are trimmed or summarized past a token budget.
- Tool definitions and system prompts are measured and kept lean.
- You estimate cost for a feature before launch using real sample inputs.