Skip to content

Commit 31e941c

Browse files
authored
fix(context): count fullwidth chars in token estimates (#96442)
1 parent 56d95b1 commit 31e941c

2 files changed

Lines changed: 10 additions & 2 deletions

File tree

src/utils/cjk-chars.test.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,13 @@ describe("estimateStringChars", () => {
4646
expect(estimateStringChars("안녕하세요")).toBe(20);
4747
});
4848

49+
it("handles East Asian fullwidth letters, numbers, and punctuation", () => {
50+
expect(estimateStringChars("ABC123")).toBe(6 * CHARS_PER_TOKEN_ESTIMATE);
51+
expect(estimateStringChars("hello,world")).toBe(
52+
"helloworld".length + CHARS_PER_TOKEN_ESTIMATE,
53+
);
54+
});
55+
4956
it("handles CJK punctuation and symbols in the extended range", () => {
5057
// "⺀" (U+2E80) is in CJK Radicals Supplement range
5158
expect(estimateStringChars("⺀")).toBe(CHARS_PER_TOKEN_ESTIMATE);

src/utils/cjk-chars.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,10 @@ export const CHARS_PER_TOKEN_ESTIMATE = 4;
2020
/**
2121
* Matches CJK Unified Ideographs, CJK Extension A/B, CJK Compatibility
2222
* Ideographs, Hangul Syllables, Hiragana, Katakana, and other non-Latin
23-
* scripts that typically use ~1 token per character.
23+
* scripts and East Asian fullwidth forms that typically use ~1 token per character.
2424
*/
25-
const NON_LATIN_RE = /[\u2E80-\u9FFF\uA000-\uA4FF\uAC00-\uD7AF\uF900-\uFAFF\u{20000}-\u{2FA1F}]/gu;
25+
const NON_LATIN_RE =
26+
/[\u2E80-\u9FFF\uA000-\uA4FF\uAC00-\uD7AF\uF900-\uFAFF\uFF01-\uFF60\uFFE0-\uFFE6\u{20000}-\u{2FA1F}]/gu;
2627

2728
/**
2829
* Return an adjusted character length that accounts for non-Latin (CJK, etc.)

0 commit comments

Comments
 (0)