估算文本的 token 数(中文约 1.5 字符/token,英文约 4 字符/token)
(text: str)
| 46 | |
| 47 | |
| 48 | def estimate_tokens(text: str) -> int: |
| 49 | """估算文本的 token 数(中文约 1.5 字符/token,英文约 4 字符/token)""" |
| 50 | if not text: |
| 51 | return 0 |
| 52 | # 粗略估算:中文字符和英文字符混合 |
| 53 | chinese_chars = sum(1 for c in text if '\u4e00' <= c <= '\u9fff') |
| 54 | english_chars = len(text) - chinese_chars |
| 55 | # 中文约 1.5 字符/token,英文约 4 字符/token |
| 56 | return int(chinese_chars / 1.5 + english_chars / 4) + 10 |
| 57 | |
| 58 | |
| 59 | # 内存中的每日 token 累计 |
no outgoing calls
no test coverage detected