Skip to content

Commit 08c05e3

Browse files
authored
Improve token estimation speed.
1 parent 82802c1 commit 08c05e3

1 file changed

Lines changed: 8 additions & 1 deletion

File tree

python_agent_harness/token_estimator.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from __future__ import annotations
99

1010
import json
11+
import re
1112

1213
from . import config
1314

@@ -23,11 +24,17 @@ def is_cjk_char(c: str) -> bool:
2324
)
2425

2526

27+
# The same ranges as `is_cjk_char`, as a single compiled character class.
28+
# Scanning for CJK runs in C (the regex engine) instead of a per-character
29+
# Python loop, so large payloads count CJK chars much faster.
30+
_CJK_RE = re.compile(r"[\u3000-\u9fff\uf900-\ufaff\uff00-\uffef\U00020000-\U0002fa1f]")
31+
32+
2633
def estimate_tokens(text: str) -> int:
2734
"""Estimate tokens in TEXT: Latin ~4 chars/token, CJK ~2 chars/token."""
2835
if not text:
2936
return 0
30-
cjk = sum(1 for ch in text if is_cjk_char(ch))
37+
cjk = len(_CJK_RE.findall(text))
3138
latin = len(text) - cjk
3239
return round(latin / 4.0 + cjk / 2.0)
3340

0 commit comments

Comments
 (0)