* 轻量字符估算(fallback) * CJK 字符约 1.6 字符/token,ASCII 约 4 字符/token
(text: string)
| 40 | * CJK 字符约 1.6 字符/token,ASCII 约 4 字符/token |
| 41 | */ |
| 42 | function estimateTokens(text: string): number { |
| 43 | if (!text) return 0 |
| 44 | let cjk = 0 |
| 45 | let other = 0 |
| 46 | for (const ch of text) { |
| 47 | const cp = ch.codePointAt(0) ?? 0 |
| 48 | // CJK 统一表意文字 + 扩展区 + 假名 + 谚文 |
| 49 | if ( |
| 50 | (cp >= 0x4e00 && cp <= 0x9fff) || |
| 51 | (cp >= 0x3040 && cp <= 0x30ff) || |
| 52 | (cp >= 0xac00 && cp <= 0xd7af) || |
| 53 | (cp >= 0x3400 && cp <= 0x4dbf) |
| 54 | ) { |
| 55 | cjk++ |
| 56 | } else { |
| 57 | other++ |
| 58 | } |
| 59 | } |
| 60 | return Math.ceil(cjk / 1.6 + other / 4) |
| 61 | } |
| 62 | |
| 63 | /** |
| 64 | * 计算单段文本的 token 数。 |