A token count is not a property of a file. It is a property of a file plus a tokenizer. The same text produces different counts depending on the model, its encoding and the language, as OpenAI's own documentation notes (OpenAI Help Center). The word "idempotency" encodes to four tokens under one common encoding and three under another, which is why the count has to be tied to a specific tokenizer rather than treated as a fixed number (OpenReplay).
That distinction matters at scale. An agentic loop might re-read and re-tokenize a working directory on every step. If you have a few thousand files, a naive preflight pass touches all of them on every run even though only a handful changed since the last one. The count is deterministic for a given input and tokenizer, so most of that work is redundant.
The fix is to treat token counting like any other pure function and memoize it. The classic memoization key is the function arguments. Here the arguments are the file bytes and the tokenizer identity. You do not need to hash the tokenizer, only to record its name and version, because that is what you cannot re-derive from the bytes.
A cheap heuristic like characters divided by four is fine for capacity planning but not for billing or context-window decisions, because it breaks on code, JSON, non-English text and emoji (OpenReplay). So the cached value should be an exact count from the real tokenizer, not an estimate. That makes the cache a correctness tool as well as a speed tool.



