feat(inference): CJK 保守 token 估算(T9 架构审查整改)

- Issue11: approximate_token_count 重写
  - 新增 _is_cjk_char(CJK 统一表意/扩展A/假名/韩文/兼容/全角六大 Unicode 范围)
  - CJK 字符按 1.5 token/字符(旧 4 字符 1 token 严重低估,裁剪失效致 API 超限)
  - 其余字符仍 4 字符 1 token;最少 1 token
- 同步 config-design.md token_estimation 注释
- 新增 4 用例,全量 186 passed / 100.00%(995 stmts/252 br)
This commit is contained in:
lhl
2026-08-12 09:54:20 +08:00
parent 8239a37a99
commit 8febc50eb8
4 changed files with 53 additions and 3 deletions
+27
View File
@@ -19,6 +19,33 @@ def test_approximate_count_linear():
assert approximate_token_count("abcdefghi") == 3
# ---------- T9: CJK 保守估算 ----------
def test_approximate_cjk_conservative():
"""CJK(中文/日文/韩文)字符按保守 ×1.5/字符 估算,远高于 4 字符 1 token。"""
cjk = "日本語の設計書" # 7 个 CJK 字符
assert approximate_token_count(cjk) >= len(cjk) # 至少 1 token/字符
# 旧逻辑 len//4=1(严重低估);新逻辑 ≥7
assert approximate_token_count(cjk) > len(cjk) // 4
def test_approximate_ascii_unchanged():
"""纯 ASCII 仍按 4 字符 1 token(不回归)。"""
assert approximate_token_count("abcdefgh") == 2
def test_approximate_mixed_cjk_and_ascii():
"""混合文本:CJK 部分保守估算 + ASCII 部分按 4 字符 1 token。"""
# "abc" 3 ASCII → 1 token"日本語" 3 CJK → ceil(3*1.5)=5;合计 ≥ 6
total = approximate_token_count("abc日本語")
assert total >= 1 + 3
def test_approximate_cjk_fullwidth_forms():
"""全角符号(CJK 兼容/全角区块)同样保守估算(日文文档常见)。"""
assert approximate_token_count("(設計)") >= 4 # 4 个全角字符,至少 4 token
def test_tiktoken_estimator_missing_falls_back():
# 未安装 tiktoken 或不可用时返回 None(由 make_estimator 回落 approximate
r = _tiktoken_estimator("hello")