forked from Alishahryar1/free-claude-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoken_estimation.py
More file actions
37 lines (26 loc) · 962 Bytes
/
Copy pathtoken_estimation.py
File metadata and controls
37 lines (26 loc) · 962 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
"""Process-wide best-effort plain-text token estimation."""
from typing import Protocol
import tiktoken
from loguru import logger
_DISALLOWED_SPECIAL: tuple[str, ...] = ()
class _TokenEncoder(Protocol):
def encode(
self, text: str, *, disallowed_special: tuple[str, ...]
) -> list[int]: ...
def _load_encoder() -> _TokenEncoder | None:
try:
return tiktoken.get_encoding("cl100k_base")
except Exception as exc:
logger.warning(
"cl100k_base token encoder unavailable ({}); using approximate token estimates",
type(exc).__name__,
)
return None
_ENCODER = _load_encoder()
def estimate_text_tokens(text: str) -> int:
"""Estimate tokens for plain text using the shared process-wide encoder."""
if not text:
return 0
if _ENCODER is not None:
return len(_ENCODER.encode(text, disallowed_special=_DISALLOWED_SPECIAL))
return max(1, len(text) // 4)