Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ export function estimateTokens(text) {
if (!s) return 0;
const chars = s.length;
const words = (s.match(/\S+/g) || []).length;
return Math.max(Math.ceil(chars / 4), Math.ceil(words * 1.3));
const cjkChars = (s.match(/[\u3400-\u4DBF\u4E00-\u9FFF\uF900-\uFAFF\u3040-\u30FF\uAC00-\uD7AF]/g) || []).length;
const charEstimate = Math.ceil((chars - cjkChars) / 4) + cjkChars;
return Math.max(charEstimate, Math.ceil(words * 1.3));
}

// Flatten any supported payload into text units: {role, kind, text}.
Expand Down
11 changes: 11 additions & 0 deletions test/basic.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,17 @@ test("units rejects non-array payload.messages with TypeError", () => {
);
});


test("estimateTokens keeps CJK text within the documented reference tolerance", () => {
const text = "漢".repeat(200);
const referenceTokens = 200;
const tolerance = 0.15;
const estimated = estimateTokens(text);
assert.ok(
Math.abs(estimated - referenceTokens) <= referenceTokens * tolerance,
`estimated ${estimated}, expected within 15% of ${referenceTokens}`,
);
});
test("compact does not leave tool_result without its tool_use when trimming", () => {
const payload = {
messages: [
Expand Down
Loading