Count tokens before the API call: estimate LLM cost before the bill arrives
This AtmoRouter-authored article shows how to count tokens before a request is sent so you can estimate LLM cost up front, with local tokenizer counts, a pre-flight budget check and a way to reconcile estimates with billed usage.
Why it matters
Most teams learn their token count only after a request has run, when the money is already spent. Counting before the call lets you price a job, cap the context, and stop oversized prompts early. Each model family has its own tokenizer, so the same paragraph can be 80 tokens on one model and 110 on another.
The sample code uses the tiktoken library, strips the model ID prefix and falls back to a default encoding for unknown names. In an illustrative 2,000 requests a day with 60,000 input and 1,500 output tokens, cx/gpt-6.2-sol costs about $0.0165 per request and zai/glm-5.4 about $0.000227 at catalogue from-prices.
If 45,000 of those input tokens are a cached prefix the cost drops by roughly 60%, because cached input bills at 10% of the input rate. On the AtmoRouter AI gateway, billed figures come from the X-Atmorouter-Cost header, and Budgets can cap the maximum input and output prices used for routing. Rates change, so check the model page.