openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
115 lines (114 loc) • 3.07 kB
JavaScript
//#region packages/normalization-core/src/cjk-chars.ts
/**
* Shared CJK-aware character counting for approximate token estimates.
*
* This is a provider-independent budget heuristic, not an exact tokenizer.
* Weighting common CJK, rare BMP characters, width-compatibility forms, and
* supplementary ideographs separately keeps current tokenizers within a
* conservative budget range while preserving the existing Latin behavior.
*/
const CHARS_PER_TOKEN_ESTIMATE = 4;
const DEFAULT_BUDGET_OPTIONS = {};
const ASCII_RUN_OR_NON_ASCII_CODE_POINT_RE = /[\p{ASCII}]+|[^\p{ASCII}]/gu;
const WEIGHTED_CJK_RANGES = [
[
[],
[],
[],
[],
[]
],
[
[],
[],
[],
[],
[],
[],
[],
[],
[]
],
[
[],
[],
[],
[],
[],
[],
[],
[],
[]
],
[[119648, 119665]],
[
[],
[],
[],
[],
[],
[]
]
];
const WEIGHTED_CJK_RE = new RegExp(`[${WEIGHTED_CJK_RANGES.flatMap((e) => e.map(([e, t]) => `\\u{${e.toString(16)}}-\\u{${t.toString(16)}}`)).join("")}]`, "u");
const CJK_CATEGORY = (() => {
const e = Math.max(...WEIGHTED_CJK_RANGES.flatMap((e) => e.map(([, e]) => e)));
const t = new Uint8Array(e + 1);
for (const [e, n] of WEIGHTED_CJK_RANGES.entries()) for (const [r, i] of n) t.fill(e + 1, r, i + 1);
return t;
})();
function estimateStringChars(e) {
return estimateStringCharsWithMinimumRawWeight(e);
}
/** Apply a raw-text safety floor without multiplying CJK adjustments twice. */
function estimateStringCharsWithMinimumRawWeight(e, t = DEFAULT_BUDGET_OPTIONS) {
const n = Math.max(1, t.minimumRawWeight ?? 1);
if (n !== 1 && n !== 2) {
let t = 0;
for (const r of e.matchAll(ASCII_RUN_OR_NON_ASCII_CODE_POINT_RE)) {
const e = r[0];
const i = Math.ceil(e.length * n);
t += e.charCodeAt(0) <= 127 ? i : Math.max(estimateStringChars(e), i);
}
return t;
}
const r = e.search(WEIGHTED_CJK_RE);
if (r < 0) return e.length * n;
let i = 0;
let a = 0;
let o = 0;
let s = 0;
let c = 0;
for (let t = r; t < e.length; t += 1) {
let n = e.charCodeAt(t);
if (n < 128) continue;
if (n >= 55296 && n <= 56319) {
const r = e.charCodeAt(t + 1);
if (r >= 56320 && r <= 57343) {
n = 65536 + (n - 55296) * 1024 + r - 56320;
t += 1;
}
}
switch (CJK_CATEGORY[n]) {
case 1:
i += 1;
break;
case 2:
a += 1;
break;
case 3:
o += 1;
break;
case 4:
s += 1;
break;
case 5: c += 1;
}
}
return e.length * n + i * (4 - n) + a * (12 - n) + o * (8 - n) + s * (12 - 2 * n) + c * (16 - 2 * n);
}
function estimateTokensFromChars(e) {
return Math.ceil(Math.max(0, e) / 4);
}
//#endregion
export { estimateTokensFromChars as i, estimateStringChars as n, estimateStringCharsWithMinimumRawWeight as r, CHARS_PER_TOKEN_ESTIMATE as t };