Estimate OpenAI Tokens Without an API Call

Published · 27 views
Estimate OpenAI Tokens Without an API Call

If you're truncating prompts or estimating OpenAI API cost before a call goes out, the text.length / 4 rule is wrong by a lot more than people assume, and which direction it's wrong in depends entirely on what kind of text you're counting. I ran the actual OpenAI tokenizer against four different content shapes to see by how much, and the naive estimate held up for exactly one of them.

Why chars/4 Isn't One Number

The chars/4 heuristic comes from English prose averaging close to 4 characters per token, and for plain sentences it's a reasonable rough guide. The problem is that token density isn't constant across content types — punctuation-heavy JSON, code with lots of short symbols, and URLs all tokenize differently than a paragraph of English, and in opposite directions from each other. A single fixed ratio can't represent all of them, which means "chars/4 is accurate enough" is really "chars/4 is accurate enough for prose," and a lot of real API payloads aren't prose.

Testing It With the Real Tokenizer

I used js-tiktoken, the JS port of OpenAI's own tiktoken library, to get the real gpt-4o token count for four sample texts and compared each against the naive chars/4 estimate:

const { encodingForModel } = require("js-tiktoken");
const enc = encodingForModel("gpt-4o");

const samples = {
  "Plain English sentence": "The quarterly report needs to be finished by Friday afternoon at the latest.",
  "JSON payload": JSON.stringify({ id: 482, name: "Aliyan Faisal", role: "developer", active: true, tags: ["node", "laravel", "ai"] }),
  "JavaScript code": `function debounce(fn, delay) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}`,
  "URL-heavy text": "See https://aliyanfaisal.com/blog/... and https://nodejs.org/api/worker_threads.html for details.",
};

for (const [label, text] of Object.entries(samples)) {
  const chars = text.length;
  const naive = Math.round(chars / 4);
  const actual = enc.encode(text).length;
  const diffPct = (((naive - actual) / actual) * 100).toFixed(1);
  console.log(`${label}: chars=${chars} naive=${naive} actual=${actual} diff=${diffPct}%`);
}

Here's what that run actually printed:

Plain English sentence: chars=76 naive=19 actual=14 diff=35.7%
JSON payload: chars=97 naive=24 actual=30 diff=-20.0%
JavaScript code: chars=149 naive=37 actual=39 diff=-5.1%
URL-heavy text: chars=128 naive=32 actual=33 diff=-3.0%

What the Numbers Actually Mean

Content type Naive estimate Real token count Error
Plain English sentence 19 14 Overestimates by 36%
JSON payload 24 30 Underestimates by 20%
JavaScript code 37 39 Underestimates by 5%
URL-heavy text 32 33 Underestimates by 3%

Prose is the one case where chars/4 overshoots, because common English words and spaces compress into fewer, longer tokens than the ratio assumes. JSON goes the other way and by the widest margin in this run — repeated punctuation ({, ", :, ,) each tends to cost its own token, so a payload that looks short in characters is longer in tokens than the formula expects. Code and URLs land close to the naive number here, but that's close by coincidence of this specific sample, not because code and URLs tokenize like prose — different variable-naming styles and path structures shift the ratio in the same two directions.

A 20% underestimate on JSON is the one that actually costs money: if you're sizing a request against a context window or a per-request token budget using chars/4, a JSON-heavy payload is the exact case where you'll go over without warning.

When the Naive Estimate Is Fine, and When It Isn't

I wouldn't rip out chars/4 everywhere — it's genuinely fine for a rough "how much room is left" indicator in a chat UI where being off by a few tokens changes nothing. Where I'd stop trusting it:

  • Any place you're truncating content to fit a hard context limit — an underestimate means the request gets rejected or silently truncated by the API instead of by your own code
  • Billing estimates you show a client or put in an invoice, where "roughly 20% low on JSON-heavy calls" is a real discrepancy, not rounding error
  • Batch jobs processing structured data (API responses, database rows serialized to JSON) rather than freeform prose, since that's exactly the JSON case above

If your payloads are mostly conversational text, chars/4 will run a little high and that's a safe direction to be wrong in. If they're mostly structured data, it runs low, which is the direction that actually breaks things.

Frequently Asked Questions

Does this apply to Claude models the same way? The token counts themselves are model-specific — Claude uses a different tokenizer than GPT-4o — but the underlying pattern holds: structured/punctuation-heavy text tokenizes less predictably than prose on basically every BPE-style tokenizer, Claude's included. If you're also working against Claude's context limits, see the Claude context window breakdown by model for the actual per-model numbers.

Is js-tiktoken slower than just counting characters? Yes, noticeably — encoding is real tokenization work, not a string length check. For a single request before sending it to the API, the difference is irrelevant. For counting tokens across a large batch of stored documents, cache the result per document rather than re-encoding on every read.

Does this matter if I'm already handling rate limit and retry errors? Not directly, but they're related problems in the same code path. An inaccurate token estimate is how you end up oversending into a context limit; see fixing OpenAI API rate limit errors in Node.js for the retry side of this, and exponential backoff for OpenAI API calls for what to do once you do get a 429.

The Actual Recommendation

Use chars/4 for a soft, non-critical estimate and nothing that enforces a hard limit. The moment a token count decides whether a request gets sent, truncated, or billed, switch to js-tiktoken (or your provider's own counting endpoint, if it has one) and accept the small performance cost — it's a few milliseconds against a mistake that costs a rejected API call or an undercounted invoice. If you're building anything that serializes structured data into a prompt, assume the naive estimate is running low, not high, and size your limits with that margin built in.

Last checked December 3, 2026. Sources: OpenAI Tokenizer, js-tiktoken on npm, openai/tiktoken on GitHub.

#nodejs #openai #tokenization #js-tiktoken #ai-backend #cost-estimation
Aliyan Faisal

Written by

Aliyan Faisal

Software engineer and AI developer. I build LLM-powered products, RAG pipelines and automations, and the web apps behind them.

Get new posts in your inbox

The best new articles, daily, twice a week or weekly. Choose your topics. No spam, unsubscribe anytime.

Prefer an app? Get posts as they go live.

0 Comments

No comments yet — be the first to share your thoughts.

Leave a comment

Never published.