File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -277,17 +277,18 @@ function estimateTokens(text: string): number {
277277 else ascii ++
278278 }
279279
280- // Tighten the ASCII ratio for structured content where punctuation is
281- // token-dense. JSON key-value patterns and code keywords are strong
282- // signals that the default 4:1 ratio will materially under-estimate.
280+ // Real BPE tokenizers (cl100k_base, o200k_base) average ~3.5-4.0
281+ // ASCII chars/token for both JSON and source code — close to prose.
282+ // The old 2.0 / 2.5 ratios matched minified-JS extremes, not typical
283+ // payloads, and systematically over-estimated token counts.
283284 const trimmed = text . trimStart ( )
284285 const jsonLike = ( trimmed . startsWith ( "{" ) || trimmed . startsWith ( "[" ) )
285286 && / " [ ^ " ] + " \s * : / . test ( text )
286287 const codeLike = ! jsonLike
287288 && / ` ` ` | ^ i m p o r t | ^ e x p o r t | ^ f u n c t i o n | ^ c o n s t | ^ l e t | ^ v a r | ^ c l a s s | ^ i n t e r f a c e | ^ t y p e | ^ d e f | ^ f n | ^ p u b | ^ u s e | ^ m o d | ^ p a c k a g e / m. test ( text )
288289
289- const asciiPerToken = jsonLike ? 2 : codeLike ? 2 .5 : 4
290- return Math . max ( 1 , Math . ceil ( ascii / asciiPerToken + cjk / 1.5 ) )
290+ const asciiPerToken = jsonLike ? 3.5 : codeLike ? 3 .5 : 4
291+ return Math . max ( 1 , Math . ceil ( ascii / asciiPerToken + cjk / 1.0 ) )
291292}
292293
293294interface TokenDist {
You can’t perform that action at this time.
0 commit comments