Same topic, related formats. Practice these next.
Same topic, related formats. Practice these next.
OpenAI uses tiktoken (local BPE library); Anthropic exposes messages.count_tokens on the SDK, which calls a server endpoint for the exact count.
Imagine mailing a heavy package: you weigh it on a scale to make sure the post office will accept it. For LLM calls, tokens are the weight and the API has a maximum. OpenAI gives you a kitchen scale you can keep on your counter, that is tiktoken, a small library that counts tokens locally and fast. Anthropic does not ship a portable kitchen scale; instead they let you call their official scale by phone before you send the package. That phone call is messages.count_tokens. Either way you weigh first, send second, and never get surprised by a rejected package at the counter.
Everything you need to truly understand this topic: intuition, mechanics, step by step explanation, code, formulas, and worked example. Click to expand.
Everything you need to truly understand this topic: intuition, mechanics, step by step explanation, code, formulas, and worked example.
Everything important, quickly.
6 min: tiktoken versus messages.count_tokens, why the asymmetry exists, character heuristics and where they fail, tool schemas and image tokens, cache the prefix pattern, cross-provider abstraction.
Real products, models, and research that use this idea.
What an interviewer would ask next. Try answering before peeking at the approach.
Red flags and common mistakes that signal junior thinking. Click to expand.
Using the wrong encoding name for the model family or assuming string length in characters maps to token count, which under-counts non-ASCII text and code by a wide margin.
The night-before-the-interview bullets. Scan these on the way to the call.
Primary sources. Skim if you want the original framing.