Practical technical guides / AI engineering: inference cost and context budgets

Count Tokens With the Target Tokenizer: Character Ratios and Other Encodings Drift by Language and Format

Measured with three tiktoken encodings: characters divided by four undercounts JSON by 26% and identifiers by 66%, and an older encoding counts Kannada at over four times.

By Sandeep Belgavi · Published 2026-11-06

Measured with three tiktoken encodings: characters divided by four undercounts JSON by 26% and identifiers by 66%, and an older encoding counts Kannada at over four times.

A budget that was off by a third

The help-desk agent at Belgavi's Book Store packs each model request from parts: instructions, the case history, tool results and a few retrieved notes. A packing function decides how much history fits, and it estimates tokens the way many codebases do, as characters divided by four. For English replies the estimate was close enough that nobody questioned it. Then the store started answering customers in Kannada and Hindi, and tool results moved from prose summaries to raw JSON. Requests began to fail with context-length errors, and when they did not fail, the reserved room for the answer was smaller than planned.

This guide measures how far the estimate drifts, and how far a different model family's tokenizer drifts, on eight kinds of text an agent actually sends. Then it shows a budget guard that does not depend on luck.

The measurement

The companion example counts tokens for eight synthetic help-desk texts with three real byte-pair encodings shipped in OpenAI's tiktoken library (version 0.13.0): o200k_base, cl100k_base and the older r50k_base. The library's own model table maps the GPT-4o, GPT-4.1 and o-series model prefixes to o200k_base, and GPT-4 and GPT-3.5 Turbo to cl100k_base. Treat o200k_base as the target encoding here: the model you will actually call. Percentages are relative to its count.

TextCharactersTarget tokensCharacters per tokenchars/4 errorcl100k_base vs targetr50k_base vs target
English reply424974.37+9.3%+1.0%+2.1%
JSON tool result3151072.94-26.2%-1.9%+13.1%
Identifiers and hashes2311731.34-66.5%0.0%-0.6%
Python source269693.90-1.4%-1.4%+71.0%
Hindi reply267912.93-26.4%+185.7%+328.6%
Kannada reply2801062.64-34.0%+334.9%+572.6%
Markdown table197782.53-35.9%+1.3%+5.1%
Base64 attachment3362171.55-61.3%+8.3%+16.1%

These are counts on one small synthetic sample per kind, not averages over a corpus, but the direction of each row is the point.

What the table says

Characters divided by four only works for English prose and ordinary code. On the English reply it overestimates by 9 percent, which is the safe direction. On everything a tool tends to return, JSON, identifiers, tables and base64, it underestimates by a quarter to two thirds. Identifiers are the extreme: order numbers, ISBNs, UUIDs and hashes come out at 1.34 characters per token, because long digit and hex runs do not merge into large tokens.

Script matters more than language. The Kannada reply has fewer characters than the English one and more tokens. Counted per character, Indic scripts also cost more because each character is three bytes in UTF-8 and byte-pair merges for them are sparser.

Another model family's tokenizer is not an approximation of yours. For English, JSON and identifiers, cl100k_base lands within 2 percent of o200k_base. For Hindi it counts 186 percent more and for Kannada 335 percent more, because the newer vocabulary has many more merges for those scripts. If your target model uses cl100k_base and you count with o200k_base, the error runs the other way: the Kannada reply would be counted at 106 tokens when the model sees 461, an undercount of 77 percent. The oldest encoding, r50k_base, also splits indented Python badly, 71 percent more tokens than the target, because it splits runs of indentation spaces into many tokens.

A budget guard that holds

The guard itself is one line: the prompt plus the output you reserve plus a safety margin must fit the window.

def fits(prompt_tokens: int, max_output: int, window: int, margin: float) -> bool:
    if not 0 <= margin < 1:
        raise ValueError('margin must be in [0, 1)')
    return prompt_tokens + max_output <= math.floor(window * (1 - margin))

What matters is where prompt_tokens comes from. The companion example packs 64 copies of the Kannada reply into an 8,192-token window with 1,024 tokens reserved for output:

PackingEstimated by chars/4Counted with targetMarginEstimate saysActually
64 Kannada replies4,4806,7840%fitsfits
64 Kannada replies4,4806,78410%fitsdoes not fit
60 JSON tool results4,7406,42010%fitsdoes not fit

With no margin the Kannada request fits by luck, 384 tokens to spare. With a sensible 10 percent margin the estimate still says yes and the real count says no. The JSON case fails the same way. A margin cannot rescue an estimate that is wrong by more than the margin.

Counting with the target tokenizer

Use the tokenizer of the model you call, at the place where you pack the request:

import tiktoken

enc = tiktoken.encoding_for_model('gpt-4o')     # resolves to o200k_base
def count(text: str) -> int:
    return len(enc.encode(text))

For models whose tokenizers are not published as a library, use the provider's counting endpoint rather than a stand-in. Anthropic's Messages API has a token counting endpoint whose documentation describes the result as an estimate that may differ from the actual input by a small amount. The Gemini API's count_tokens returns the tokens in the input only. Both count the request as the provider will see it, including any system text and tool definitions, which a local count of your strings misses.

Then keep the margin for what local counts cannot see: message framing tokens, tool schemas the SDK adds, and small differences between counting endpoints and billing. The example uses 10 percent; measure your own gap by comparing your count with the usage the API returns on real responses, and set the margin above the worst gap you see.

Where to count, and how often

Counting every string on every request costs CPU, and the expensive case is the agent loop that re-packs a growing history each turn. Two habits keep it cheap:

  • Count each piece once when it enters the history, store the count next to it, and sum stored counts when packing. Re-count only what changed.
  • Cache counts by content hash and encoding name, so a tool result that appears in many runs is counted once.

If you must estimate before you can count, for example to decide how many search results to fetch, estimate per content type, not per character: identifiers and base64 at about 1.5 characters per token, JSON and tables at about 2.5 to 3, English prose at about 4 on these encodings. Then count the real thing before sending.

Failure modes to test

  • A margin smaller than the estimate error. Test packing with your worst content type, not your most common one.
  • Counting with the wrong encoding after a model change. Make the encoding a function of the model id, and fail loudly when the id is unknown.
  • Counting strings, not requests. Tool definitions and system instructions take tokens too; reconcile local counts with reported usage.
  • Reserving output tokens the model cannot use. The reservation must not exceed the model's output limit, or a fitting prompt still fails.
  • Truncating by characters. Cut at token boundaries with the target tokenizer, or the cut lands mid-word in one script and mid-token in another.

Verification

The companion example records counts with tiktoken 0.13.0 in recorded_counts.json and has six offline tests that check the recording covers every fixture and encoding, the direction and size of each drift above, the three budget cases and the guard's edges. The texts are invented and short, so treat the percentages as a demonstration of mechanism. Anthropic and Gemini counts were not measured here; their tokenizers are not part of this experiment.

Primary references and authorship

Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/python/token_budget_drift. Views are my own and do not represent any employer, past or present.