Mental model
A browser token counter runs a tokenizer selected for a target model over the text it can see, producing a quick planning estimate before a request is sent. It helps size drafts and warn about context pressure, but the provider’s count for the fully serialized request remains authoritative for routing, truncation, and billing.
Learning outcomes
- Explain why a local token count can differ from a provider’s count for the same visible messages.
- Calculate relative estimation error and remaining context after reserving output capacity.
- Design a browser counter that pins tokenizer versions, stays responsive, and exposes uncertainty.
Theory
A tokenizer does not count words or characters. It applies model-specific normalization and pre-tokenization, then maps byte or character sequences into subword token IDs. A change to casing, Unicode normalization, whitespace, vocabulary merges, or model family can change the count. The Hugging Face tokenization pipeline documents normalization and pre-tokenization as explicit stages; a local counter must load the same tokenizer assets and revision as its selected model.
The visible message bodies are only part of a request. A chat API may serialize roles, separators, a generation prefix, tool declarations, a response schema, image or audio payloads, and provider-specific metadata. Some of those fields are not plain strings that a browser can tokenize locally. A counter that encodes only the text should label the result as a visible-text estimate, not as the request’s exact input-token count. When the provider offers a count endpoint, send the same request shape to that endpoint before making a hard context or cost decision.
Let be the local estimate in tokens and the provider-reported count for the final request, also in tokens. The relative absolute error is dimensionless:
Suppose a local browser counter estimates 934 visible-text tokens, while the provider reports 972 input tokens after adding message framing and tool metadata. The absolute gap is 38 tokens and . With an 8,192-token context and a 512-token output reserve, the confirmed request leaves this much room for future input:
Before reconciliation, that allowance is provisional; a conservative margin can reduce avoidable rejections but cannot turn an estimate into ground truth.
Versioning matters as much as the counting algorithm. Store the model identifier, tokenizer name and revision, chat-template revision, and whether the count includes tool schemas or multimodal fields with each diagnostic result. If the model provider changes any serialization behavior, a local tokenizer can remain byte-for-byte identical while the request count shifts. Reconcile using representative requests and track the signed error by model and request shape; a mean close to zero can still hide large positive and negative errors.
The count also has a latency budget. Tokenizing a long conversation synchronously on the main thread can block typing and rendering. Load tokenizer assets lazily, run encoding in a dedicated Web Worker, debounce rapid edits, and invalidate cached message counts only when their content or role changes. Byte-pair merges can cross adjacent text boundaries, so cached counts are exact only for the same serialized boundary assumptions; recalculate the affected request rather than summing arbitrary fragments.
Implementation
This worker-side example counts visible message bodies with a model-matched encoding. It deliberately reports the result as an estimate and never claims to include role framing, tools, response schemas, or non-text inputs. A production adapter should keep the tokenizer and model mapping in one versioned registry and call the provider’s count endpoint before a hard limit decision.
typescriptimport { encodingForModel } from "js-tiktoken";type ModelId = "gpt-4o" | "gpt-4o-mini";type Message = {role: "system" | "developer" | "user" | "assistant";content: string;};type TextEstimate = {model: ModelId;visibleTextTokens: number;includesRequestFraming: false;providerReconciliationRequired: true;};export function estimateVisibleTextTokens(model: ModelId,messages: readonly Message[],): TextEstimate {const encoding = encodingForModel(model);try {const visibleTextTokens = messages.reduce((total, message) => total + encoding.encode(message.content).length,0,);return {model,visibleTextTokens,includesRequestFraming: false,providerReconciliationRequired: true,};} finally {encoding.free();}}const estimate = estimateVisibleTextTokens("gpt-4o", [{ role: "user", content: "Compare paged attention with a dense KV cache." },]);console.assert(estimate.visibleTextTokens > 0);console.assert(estimate.providerReconciliationRequired);
Trade-offs
Shipping tokenizer assets to the browser reduces round trips and gives users immediate feedback, but increases download size, memory use, and upgrade coordination. A worker protects interaction responsiveness at the cost of another message channel and duplicated state. For short prompts, a debounced worker estimate may be enough; for long histories or expensive schemas, use the provider count endpoint and retain the local result only as an early warning.
A safety margin lowers the chance that a request crosses the context limit after provider framing is added. A large margin wastes usable context and may truncate useful history, while a small margin increases rejection and retry rates. Tune the margin from measured error distributions for each model and request shape. Do not carry an error rate measured on text-only requests into a workflow that includes tools, images, or audio.
Local counting can expose user text to tokenizer code delivered from a third-party asset host. Pin the asset digest, serve it from a trusted origin where possible, and keep the counter fully local; never send the draft to an analytics endpoint just to count it. A provider reconciliation request should use the same authenticated route and privacy controls as the final inference request.
Failure modes and misconceptions
- A tokenizer is selected by name alone. Model aliases can move to a different tokenizer or template. Pin and record the model and tokenizer revisions.
- Visible message text is treated as a full request. Tool definitions, role framing, response schemas, and multimodal payloads may add tokens that local text encoding does not see.
- The user assumes the displayed number is a billing total. Label estimates and provider counts separately, including which fields each number covers.
- A main-thread counter freezes the interface. Move encoding to a worker, debounce edits, and cap the size of imported histories.
- Cached fragment counts are summed after an edit. Token boundaries can change around modified text. Recount the changed serialized request or use a boundary-aware tokenizer API.
- Unicode is normalized differently. A visually identical string may tokenize differently after normalization. Keep the original text and use the normalization behavior of the exact tokenizer revision.
Decision scenario
A support chat client counts 6,400 visible text tokens in a draft and plans to send it to a model with an 8,192-token context. The request also includes three tool schemas and a 900-token output reserve. The provider count endpoint returns 7,520 input tokens, leaving only 672 tokens after the reserve. Keep the provider count as the limit check, warn that the draft is close to capacity, and trim history with the product’s documented policy before generation. Do not silently discard older turns just because the browser’s lower text-only estimate appeared to leave room.