feat: Token 估算(approximate 内置 / tiktoken 可选回落)
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Callable
|
||||
|
||||
|
||||
def approximate_token_count(text: str) -> int:
|
||||
"""内置近似估算:每 4 字符 ≈ 1 token(无外部依赖,可离线)。"""
|
||||
return max(1, (len(text) + 3) // 4)
|
||||
|
||||
|
||||
def _tiktoken_estimator(text: str) -> int | None:
|
||||
"""tiktoken 编码估算;tiktoken 未安装时返回 None。"""
|
||||
try:
|
||||
import tiktoken
|
||||
except ImportError:
|
||||
return None
|
||||
try:
|
||||
enc = tiktoken.get_encoding("cl100k_base")
|
||||
return len(enc.encode(text))
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def make_estimator(backend: str = "tiktoken") -> Callable[[str], int]:
|
||||
"""按配置选择估算器:backend="tiktoken"(默认)优先 tiktoken,
|
||||
缺失或异常回落内置 approximate;backend="approximate" 直接用近似。"""
|
||||
if backend == "approximate":
|
||||
return approximate_token_count
|
||||
return lambda text: _tiktoken_estimator(text) or approximate_token_count(text)
|
||||
Reference in New Issue
Block a user