Skip to content

Commit 4e1d0a7

Browse files
committed
fix(estimateTokens): 校准 token 估算参数以对齐真实 BPE tokenizer 压缩比
JSON: 2.0 → 3.5, 代码: 2.5 → 3.5, CJK: 1.5 → 1.0 基于 cl100k_base / o200k_base 实证基准数据校准
1 parent 3b3d957 commit 4e1d0a7

1 file changed

Lines changed: 6 additions & 5 deletions

File tree

src/index.tsx

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff 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
&& /```|^import |^export |^function |^const |^let |^var |^class |^interface |^type |^def |^fn |^pub |^use |^mod |^package /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

293294
interface TokenDist {

0 commit comments

Comments
 (0)