Insight

Count Tokens Before the API Call: Estimate LLM Cost Up Front

Estimate LLM API cost before you send a request: token counting with tiktoken, budget thresholds, and how to reconcile estimates against billed usage.

Most teams learn their token count the expensive way: after the request has already run. The response tells you what was billed, but by then you have paid for it. If you count tokens before the API call, you can price a job, enforce a context budget, and stop oversized prompts before they reach the model.

This is an AtmoRouter-authored post. The numbers below are illustrative math built on the public AtmoRouter catalogue at writing time, not an independent benchmark, and rates change. Every estimate here is an approximation; the bill is always based on the usage the model reports.

Why estimates and bills disagree

Every model family ships its own tokenizer. The same paragraph can be 80 tokens on one model and 110 on another, and none of them split on word boundaries the way people expect. Long identifiers, base64 blobs, minified JSON and non-English text all inflate counts in ways a len(text) / 4 heuristic misses badly.

There is also overhead you do not write yourself: the chat template wrapper, tool schemas, and any system prompt your framework injects. A request that looks like 50k tokens of "prompt" in your code can be 53k on the wire.

The practical conclusion: a local count is a budgeting tool, not an invoice. Treat it as a floor with a margin, and reconcile against billed usage, which on AtmoRouter comes from the upstream usage report rather than a character estimate.

Counting tokens locally with tiktoken

The tiktoken library (OpenAI's BPE tokenizer) counts tokens for OpenAI models and raises a KeyError for names it does not recognise. Because gateway model IDs carry a family prefix, strip it before asking for an encoding, and fall back to o200k_base when the name is unknown:

pythonimport tiktoken

RATES = {"cx/gpt-6.2-sol": (0.245, 1.225)}  # USD per million input/output tokens


def count_tokens(text: str, model: str) -> int:
    bare = model.split("/", 1)[-1]
    try:
        enc = tiktoken.encoding_for_model(bare)
    except KeyError:
        enc = tiktoken.get_encoding("o200k_base")
    return len(enc.encode(text))


def estimate_cost_usd(input_tokens: int, output_tokens: int, model: str) -> float:
    price_in, price_out = RATES[model]
    return input_tokens * price_in / 1e6 + output_tokens * price_out / 1e6

The output side is the part you cannot count, because the text does not exist yet. Use max_tokens as the ceiling and a typical figure from your own logs as the expected value.

Note that this tokenizer is only exact for OpenAI models. For other families the count is an approximation; calibrate it by comparing your local count with usage.prompt_tokens on a sample of real requests.

Turning a count into a budget

A count only saves money if something acts on it. The common pattern is a pre-flight check in your own code:

pythonMAX_INPUT_TOKENS = 480_000  # stays under the model's 500,000-token input limit

before_send = count_tokens(system + history + user_msg, "cx/gpt-6.2-sol")
if before_send > MAX_INPUT_TOKENS:
    history = summarise_oldest(history, keep_recent=10)  # your own trimming/summary helper
    before_send = count_tokens(system + history + user_msg, "cx/gpt-6.2-sol")

On the AtmoRouter side, Budgets let you set maximum input and output prices, which limits which price tiers your requests can be routed to. That limits the rate, not the token count, so the two controls complement each other: your code bounds the tokens, the budget bounds the unit price.

A good workflow has three layers: a local count that rejects or trims oversized prompts, a max_tokens ceiling on output, and the gateway budget as the backstop.

What a mis-sized prompt costs

Illustrative math: 2,000 requests per day, each with 60,000 input tokens and 1,500 output tokens. At the catalogue's from-prices:

| Model | From price (input / output per Mtok) | Cost per request | Per day | Per 30 days | |---|---|---|---|---| | cx/gpt-6.2-sol | $0.245 / $1.225 | $0.0165 | $33.08 | $992.25 | | zai/glm-5.4 | $0.0035 / $0.011 | $0.000227 | $0.45 | $13.59 |

Now assume 45,000 of those 60,000 input tokens are a cached prefix. On AtmoRouter cached input bills at 10% of the input rate where supported, so the cx/gpt-6.2-sol request drops to $0.0066, about 60% less, with no change in behaviour. That is the single largest lever a pre-flight token count exposes: how much of your prompt is a stable prefix that could be cached.

Output is cheap in this example and dominates in others. For a 5,000-in / 8,000-out request on cx/gpt-6.2-sol, output is 89% of the bill. Count tokens on both sides, or you will budget for the small half.

Rates refresh continuously, a minimum request charge applies, and the "from" price is the lowest listed tier rather than a guarantee for every request. Check live rates on the model page before relying on any figure here.

Reconciling estimates with the bill

Each response carries the numbers to close the loop. Non-streaming JSON reports an X-Atmorouter-Cost header; streams report the final usage.cost. The usage block also gives you prompt_tokens, completion_tokens, and the cached-token breakdown.

Log your estimate next to the billed count for a few hundred requests and compute the ratio. That single correction factor, per model, will make every future estimate materially more accurate than any character heuristic.

pythonimport os, requests

messages = [{"role": "user", "content": "Summarise this changelog in five bullets."}]

r = requests.post(
    "https://atmorouter.dev/v1/chat/completions",
    headers={"Authorization": f"Bearer {os.environ['ATMOROUTER_API_KEY']}"},
    json={"model": "cx/gpt-6.2-sol", "messages": messages, "max_tokens": 1500},
)
data = r.json()
print(r.headers.get("X-Atmorouter-Cost"), data["usage"]["prompt_tokens"])

FAQ

Is tiktoken exact for non-OpenAI models?

No. It is a close proxy for many BPE tokenizers and a poor one for others. Measure the gap against billed prompt_tokens before you trust it for a given model.

Should I reject requests that exceed my token budget?

Usually trim rather than reject: summarise or drop the oldest history, keep the system prompt and the latest turns intact, then recount.

Do failed requests count against my balance?

On AtmoRouter, failed requests are never billed, so an oversized or malformed call costs you nothing but latency. Still catch it before sending when you can.

Next step

Pull the current catalogue and prices from https://atmorouter.dev/models, read the billing formula and current minimum on https://atmorouter.dev/pricing, then pair your pre-flight count with a budget. For the caching side of the math, see the prompt caching and long context cost posts on this blog.

Older

Kilo Code With an OpenAI-Compatible API: AtmoRouter Setup Guide

Build with AtmoRouter.