Token Counting Before API Call: Accuracy, Tools, and Budgeting
The cost of a request and the likelihood of a context_length_exceeded error are determined by the number of tokens in the input and output. Estimating them by eye based on characters or words is inaccurate, with discrepancies reaching double. Precise counting before sending is a mandatory step in any production pipeline.
Why Symbol Estimation is Inaccurate
The rule 'one token ≈ four English characters' works only for Latin text and approximately. For Russian text, code, JSON, and emojis, the ratio is different.
| Text | Characters | Tokens (approx.) | Characters per token |
|---|---|---|---|
| English prose | 400 | 100 | 4.0 |
| Russian prose | 400 | 200–260 | 1.5–2.0 |
| JSON with keys | 400 | 130–180 | 2.2–3.0 |
| Python code | 400 | 120–160 | 2.5–3.3 |
| Base64 string | 400 | 300+ | 1.3 |
For Russian text, a typical estimate is 2–2.5 characters per token. An underestimation error leads to context truncation, an overestimation error leads to unnecessary costs for compression.
Tokenizer and Its Version
A tokenizer is a tokenizer tied to a specific model. Different model families have different dictionaries, so the same text yields different token counts.
flowchart LR
A[Request text] --> B[Model A tokenizer]
A --> C[Model B tokenizer]
B --> D[Token count A]
C --> E[Token count B]
D --> F[Budget and cost]
E --> F
Practical implications:
- Count tokens with the tokenizer corresponding to the target model;
- When changing model versions, the tokenizer may change — token counting needs to be rechecked;
- For unknown models, use an approximation and add a 10–15% buffer.
Counting Through a Library
Most providers publish tokenizers in open libraries. Example for models with open weights:
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("model-name")
def count_tokens(text: str) -> int:
return len(tokenizer.encode(text, add_special_tokens=False))
def count_messages(messages: list[dict]) -> int:
total = 0
for msg in messages:
total += count_tokens(msg["content"])
total += 4 # role and separator tokens
total += 2 # start and end dialog tokens
return total
Role and separator tokens are easy to forget. In a 20-message dialog, this adds 80–100 tokens — a small amount, but it accumulates in mass calls.
Counting Through API
Some providers offer an endpoint for token counting without generation. This is more accurate than a local library because it accounts for server-side wrappers.
import httpx
def count_via_api(text: str, model: str, api_key: str) -> int:
resp = httpx.post(
"https://api.example.com/v1/tokenize",
headers={"Authorization": f"Bearer {api_key}"},
json={"model": model, "input": text},
timeout=10.0,
)
resp.raise_for_status()
return resp.json()["token_count"]
The downside is an additional network call per request. For hot paths, a local tokenizer is better; for cold paths, the API is better.
Context Budgeting
Counting is needed not for its own sake, but to distribute the token budget among parts of the request.
| Request part | Budget share | Note |
|---|---|---|
| System prompt | 5–10 % | Fixed, cached |
| Dialogue history | 20–30 % | Compressed on overflow |
| RAG context | 40–60 % | Main consumer |
| User question | 2–5 % | Usually short |
| Reserve for response | 10–20 % | max_tokens |
Algorithm: count fixed parts, subtract from the window, allocate the remainder to RAG context with a reserve for the response.
def fit_context(
system: str,
history: list[dict],
question: str,
chunks: list[str],
window: int,
reserve: int,
) -> list[str]:
fixed = count_tokens(system) + count_messages(history) + count_tokens(question)
budget = window - fixed - reserve
if budget <= 0:
raise ValueError("Fixed parts do not fit in the window")
selected, used = [], 0
for chunk in chunks:
n = count_tokens(chunk)
if used + n > budget:
break
selected.append(chunk)
used += n
return selected
This approach ensures that the request will not be rejected due to length and that the response will fit within max_tokens.
Caching Counting
Tokenization is not free. For repeating fragments (system prompt, static documents), the result should be cached by text hash.
import hashlib
from functools import lru_cache
@lru_cache(maxsize=10_000)
def count_cached(text_hash: str, text: str) -> int:
return count_tokens(text)
def count_with_cache(text: str) -> int:
h = hashlib.sha256(text.encode("utf-8")).hexdigest()
return count_cached(h, text)
This is especially useful when the same system prompt is sent thousands of times.
Discrepancies and Buffer
Even precise local tokenizer counting can differ from server-side counting by 1–3%. Reasons: server-side wrappers, role tokens, dictionary version differences. Practice is to add a 5% buffer to the calculated number before checking for window overflow.
If the request is still rejected, see LLM API error handling and context window management.
Connection to Cost Optimization
Token counting is the input for cost forecasting and request compression. Without an accurate token count, both tasks are solved blindly. For a systemic approach to budgeting, see LLM API rate limit and budget management.