How to Estimate Tokens Before You Send a Request
Estimate LLM tokens before you send: rules of thumb, tiktoken for rough counts, count_tokens for Claude, model multipliers and keeping prompts small.
You only learn the exact token count of a request after the model has processed it: it is in the usage field of the response. But there are good reasons to know the rough size before you send — to stay inside a context window, to keep a budget, and to avoid a request that is rejected because it is larger than what your plan has left.
This is an explainer with a checklist at the end. Nothing here needs to be exact; a solid estimate with a margin is enough.
Why estimate at all
- Remaining tokens. FreeModel checks a request's estimated size against what your plan has left. If one prompt needs more than that, you get
402 prompt_exceeds_quotabefore the model runs. - Free plan request size. On the free plan a single request may carry up to about 128,000 tokens; larger ones get
413 context_length_exceeded. - Context windows. Each model has a maximum context, listed on its page under models where it is published.
- Cost. Input and output tokens both count toward your plan.
What actually counts
| Part of the request | Counts as | Often forgotten? |
|---|---|---|
| System prompt | Input | Yes — it is resent on every call |
| Conversation history | Input | Yes — it grows every turn |
| Tool definitions and tool results | Input | Yes, in agents |
| The answer | Output | No |
| Reasoning ("thinking") tokens | Output | Yes — part of completion_tokens |
The rule of thumb
For English prose, one token is roughly four characters, or about three quarters of a word. Code, JSON, numbers and many non-English scripts use more tokens per character. FreeModel's own pre-checks use a similar shortcut — text length divided by 3.8 — so a quick len(text) / 3.8 puts you in the same range as the gateway's check.
That is good enough for "will this fit?" decisions. For anything closer, count with a tokenizer.
Rough counting with tiktoken
tiktoken is OpenAI's open-source tokenizer library. Other vendors' models use their own tokenizers, so treat its count as an estimate, not the truth for every model.
import json
import tiktoken
enc = tiktoken.get_encoding("o200k_base")
def estimate_tokens(messages, tools=None):
total = 3 # reply priming
for m in messages:
content = m["content"] if isinstance(m["content"], str) else json.dumps(m["content"])
total += len(enc.encode(content)) + 4 # per-message overhead
if tools:
total += len(enc.encode(json.dumps(tools)))
return total
messages = [
{"role": "system", "content": "You are a code reviewer."},
{"role": "user", "content": open("diff.txt", encoding="utf-8").read()},
]
print(estimate_tokens(messages))
The per-message overhead and tool count are approximations; providers format these internally in different ways. Add a margin of 10–20%.
count_tokens for Claude-format requests
The Anthropic format has an endpoint for this: POST /v1/messages/count_tokens. With the Anthropic SDK pointed at FreeModel:
import os
import anthropic
client = anthropic.Anthropic(api_key=os.environ["FREEMODEL_API_KEY"],
base_url="https://freemodel.in")
count = client.messages.count_tokens(
model="claude-sonnet-5",
system="You are a code reviewer.",
messages=[{"role": "user", "content": open("diff.txt", encoding="utf-8").read()}],
)
print(count.input_tokens)
Be clear about what you get. On FreeModel this endpoint returns an estimate computed from the length of the system prompt and messages; it does not run the model and does not use plan tokens. Tool definitions are not included in the estimate. Sending the real request to claude-sonnet-5 needs a paid plan.
From tokens to plan tokens
Each model uses plan tokens at its own rate: one token on a 3× model is three plan tokens. Multiply your estimate by the model's multiplier to see what a request takes from your plan. For a request with 10,000 input and 2,000 output tokens:
| Model | Multiplier | Plan tokens used |
|---|---|---|
Free models on the free plan (including claude-haiku-5.5) | 1× | 12,000 |
gpt-6.2-astra on the free plan | 1.5× | 18,000 |
claude-haiku-5.5 on a paid plan | 1.5× | 18,000 |
gpt-6-astra | 1.75× | 21,000 |
claude-sonnet-5, claude-opus-5-5 | 3× | 36,000 |
kimi-k3 | 4× | 48,000 |
The same arithmetic explains prompt_exceeds_quota: the gateway multiplies the estimated prompt by the multiplier and compares it with what is left. More on how this adds up in understanding token pricing.
A pre-flight check
Put the estimate in front of every call that might be large. Refuse or trim early instead of finding out from an error:
MULTIPLIER = {"gpt-6-luna": 1, "claude-haiku-5.5": 1.5, "claude-sonnet-5": 3}
def preflight(messages, model, max_output, plan_tokens_left, max_input=100_000):
est_in = estimate_tokens(messages)
if est_in > max_input:
raise ValueError(f"~{est_in:,} input tokens; trim the history first")
need = (est_in + max_output) * MULTIPLIER.get(model, 3)
if need > plan_tokens_left:
raise ValueError(f"needs ~{need:,.0f} plan tokens, {plan_tokens_left:,} left")
return est_in
The multiplier used for gpt-6-luna here is its free-plan rate. Read your remaining tokens from the dashboard or keep your own running total from usage.
The real number: usage
Every successful response includes usage.prompt_tokens and usage.completion_tokens; with streaming, they arrive in the last chunk before [DONE]. Log them next to your estimate for a week and you will know how far off your estimate runs for your own prompts — then set the margin from data, not guesswork.
Checklist: keeping prompts small
- Keep the system prompt short; it is paid on every call.
- Send the last few turns, not the whole conversation (see long-context best practices).
- Truncate tool results and file contents to the part that matters.
- In RAG, send three to five good chunks, not twenty.
- Set
max_tokensdeliberately — generous for reasoning models, tight for short answers. - Pick the multiplier on purpose: a 1.5× model for routine work, 3× and above when the task needs it.
FAQ
How many characters are in a token?
For English prose, roughly four. Code, numbers and many non-English languages use more tokens per character, so treat four as an optimistic average.
Is count_tokens exact on FreeModel?
No. It returns an estimate based on the length of the system prompt and messages. The exact count is the usage field of the real response.
Do output tokens count against my plan?
Yes. Input and output tokens both count, and reasoning tokens are part of the output.
Why does usage show more input tokens than I counted?
Your local tokenizer is not the model's tokenizer, and the request carries more than your text, such as message formatting and tool definitions. Plan for a margin.
Grab a free API key — 1M tokens on 8 free models after a one-time Telegram verification, no card. Every model from $1.20.