fix(tokens): warm fallback tokenizer in background (#5861)
* fix(tokens): keep fallback token estimation offline * fix(tokens): warm fallback tokenizer in background * test(tokens): isolate agent fixtures from tokenizer readiness * test(tokens): keep Codex pressure fixtures within byte budget * docs: remove manual wrapping from troubleshooting prose
This commit is contained in:
1 parent
e0b8efa0be
commit
4a7ad00e4f
16 files changed
+378
-101
No files matched your search
@@ -43,6 +43,7 @@ from nanobot.session.keys import (
|
||||
)
|
||||
from nanobot.utils.evaluator import evaluate_response, resolve_evaluator_prompt
|
||||
from nanobot.utils.helpers import sync_workspace_templates
|
||||
from nanobot.utils.token_encoding import warmup_token_encoding
|
||||
from nanobot.webui.build import BuildMode
|
||||
from nanobot.webui.dev import WebUIDevError, WebUIDevServer
|
||||
from nanobot.webui.sidebar_state import read_webui_sidebar_state
|
||||
@@ -406,6 +407,7 @@ def _run_gateway(
|
||||
raise typer.Exit(1)
|
||||
|
||||
console.print(f"{__logo__} Starting nanobot gateway version {__version__} on port {port}...")
|
||||
warmup_token_encoding()
|
||||
_prepare_webui_bundle_for_gateway(
|
||||
config,
|
||||
mode=webui_bundle_mode,
|
||||
|
||||
+47
-45
@@ -14,14 +14,16 @@ import uuid
|
||||
from collections.abc import Iterable
|
||||
from contextlib import suppress
|
||||
from datetime import datetime
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, TypeVar, cast, overload
|
||||
|
||||
import tiktoken
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.utils.token_encoding import get_token_encoding as _get_token_encoding
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from tiktoken import Encoding
|
||||
|
||||
from nanobot.providers.base import LLMUsage
|
||||
|
||||
_TOOLS_TOKEN_CACHE_MAX_ENTRIES = 64
|
||||
@@ -104,11 +106,6 @@ def sanitize_surrogates_deep(value: Any) -> Any:
|
||||
return value
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _get_token_encoding() -> Any:
|
||||
return tiktoken.get_encoding("cl100k_base")
|
||||
|
||||
|
||||
def _cache_tools_token_count(
|
||||
tools_id: int,
|
||||
fingerprint: tuple[int, ...],
|
||||
@@ -123,7 +120,7 @@ def _cache_tools_token_count(
|
||||
|
||||
|
||||
def _estimate_tools_tokens(
|
||||
enc: Any,
|
||||
enc: Encoding,
|
||||
tools: list[dict[str, Any]],
|
||||
*,
|
||||
leading_separator: bool,
|
||||
@@ -144,7 +141,7 @@ def _estimate_tools_tokens(
|
||||
rendered = json.dumps(tools, ensure_ascii=False)
|
||||
if leading_separator:
|
||||
rendered = "\n" + rendered
|
||||
token_count = len(enc.encode(rendered))
|
||||
token_count = len(enc.encode_ordinary(rendered))
|
||||
counts[leading_separator] = token_count
|
||||
_cache_tools_token_count(tools_id, fingerprint, counts)
|
||||
return token_count
|
||||
@@ -410,34 +407,35 @@ def truncate_text(text: str, max_chars: int) -> str:
|
||||
def truncate_text_to_tokens(text: str, max_tokens: int) -> str:
|
||||
"""Truncate text to a token budget with a stable suffix.
|
||||
|
||||
Unlike :func:`truncate_text`, this measures actual tokens, so the cap holds
|
||||
regardless of language or content (CJK and code cost more tokens per char).
|
||||
Falls back to a conservative UTF-8 byte budget if tiktoken is unavailable.
|
||||
Uses cl100k_base when ready, which may differ from the model's tokenizer.
|
||||
Falls back to a UTF-8 byte budget while loading or if initialization failed.
|
||||
"""
|
||||
if max_tokens <= 0:
|
||||
return text
|
||||
try:
|
||||
enc = _get_token_encoding()
|
||||
tokens = enc.encode(text)
|
||||
if len(tokens) <= max_tokens:
|
||||
return text
|
||||
suffix_tokens = enc.encode(_TRUNCATED_SUFFIX)
|
||||
body_budget = max_tokens - len(suffix_tokens)
|
||||
if body_budget <= 0:
|
||||
if enc is not None:
|
||||
tokens = enc.encode_ordinary(text)
|
||||
if len(tokens) <= max_tokens:
|
||||
return text
|
||||
suffix_tokens = enc.encode_ordinary(_TRUNCATED_SUFFIX)
|
||||
body_budget = max_tokens - len(suffix_tokens)
|
||||
if body_budget <= 0:
|
||||
return enc.decode(tokens[:max_tokens])
|
||||
for candidate_budget in range(body_budget, -1, -1):
|
||||
result = enc.decode(tokens[:candidate_budget]) + _TRUNCATED_SUFFIX
|
||||
if len(enc.encode_ordinary(result)) <= max_tokens:
|
||||
return result
|
||||
return enc.decode(tokens[:max_tokens])
|
||||
for candidate_budget in range(body_budget, -1, -1):
|
||||
result = enc.decode(tokens[:candidate_budget]) + _TRUNCATED_SUFFIX
|
||||
if len(enc.encode(result)) <= max_tokens:
|
||||
return result
|
||||
return enc.decode(tokens[:max_tokens])
|
||||
except Exception:
|
||||
if len(text.encode("utf-8")) <= max_tokens:
|
||||
return text
|
||||
suffix_bytes = len(_TRUNCATED_SUFFIX.encode("utf-8"))
|
||||
if max_tokens <= suffix_bytes:
|
||||
return _truncate_text_to_utf8_bytes(text, max_tokens)
|
||||
body = _truncate_text_to_utf8_bytes(text, max_tokens - suffix_bytes)
|
||||
return body + _TRUNCATED_SUFFIX
|
||||
pass
|
||||
if len(text.encode("utf-8")) <= max_tokens:
|
||||
return text
|
||||
suffix_bytes = len(_TRUNCATED_SUFFIX.encode("utf-8"))
|
||||
if max_tokens <= suffix_bytes:
|
||||
return _truncate_text_to_utf8_bytes(text, max_tokens)
|
||||
body = _truncate_text_to_utf8_bytes(text, max_tokens - suffix_bytes)
|
||||
return body + _TRUNCATED_SUFFIX
|
||||
|
||||
|
||||
def _truncate_text_to_utf8_bytes(text: str, max_bytes: int) -> str:
|
||||
@@ -812,20 +810,22 @@ def _estimate_prompt_tokens_with_source(
|
||||
per_message_overhead = len(messages) * 4
|
||||
try:
|
||||
enc = _get_token_encoding()
|
||||
tool_tokens = (
|
||||
_estimate_tools_tokens(enc, tools, leading_separator=bool(parts)) if tools else 0
|
||||
)
|
||||
message_tokens = len(enc.encode(message_payload)) if message_payload else 0
|
||||
return message_tokens + tool_tokens + per_message_overhead, "tiktoken"
|
||||
if enc is not None:
|
||||
tool_tokens = (
|
||||
_estimate_tools_tokens(enc, tools, leading_separator=bool(parts)) if tools else 0
|
||||
)
|
||||
message_tokens = len(enc.encode_ordinary(message_payload)) if message_payload else 0
|
||||
return message_tokens + tool_tokens + per_message_overhead, "tiktoken"
|
||||
except Exception:
|
||||
tool_payload = (
|
||||
("\n" if message_payload else "") + json.dumps(tools, ensure_ascii=False)
|
||||
if tools
|
||||
else ""
|
||||
)
|
||||
payload = message_payload + tool_payload
|
||||
estimated = len(payload.encode("utf-8"))
|
||||
return estimated + per_message_overhead, "heuristic"
|
||||
pass
|
||||
tool_payload = (
|
||||
("\n" if message_payload else "") + json.dumps(tools, ensure_ascii=False)
|
||||
if tools
|
||||
else ""
|
||||
)
|
||||
payload = message_payload + tool_payload
|
||||
estimated = len(payload.encode("utf-8"))
|
||||
return estimated + per_message_overhead, "heuristic"
|
||||
|
||||
|
||||
def estimate_prompt_tokens(
|
||||
@@ -871,9 +871,11 @@ def estimate_message_tokens(message: dict[str, Any]) -> int:
|
||||
return 4
|
||||
try:
|
||||
enc = _get_token_encoding()
|
||||
return max(4, len(enc.encode(payload)) + 4)
|
||||
if enc is not None:
|
||||
return max(4, len(enc.encode_ordinary(payload)) + 4)
|
||||
except Exception:
|
||||
return max(4, len(payload.encode("utf-8")) + 4)
|
||||
pass
|
||||
return max(4, len(payload.encode("utf-8")) + 4)
|
||||
|
||||
|
||||
def estimate_prompt_tokens_chain(
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Background initialization of the fallback token counter."""
|
||||
|
||||
import os
|
||||
from threading import Lock, Thread
|
||||
|
||||
import tiktoken
|
||||
from loguru import logger
|
||||
|
||||
_encoding: tiktoken.Encoding | None = None
|
||||
_warmup_thread: Thread | None = None
|
||||
_warmup_lock = Lock()
|
||||
|
||||
|
||||
def _load_encoding() -> None:
|
||||
global _encoding
|
||||
try:
|
||||
if "TIKTOKEN_CACHE_DIR" not in os.environ and "DATA_GYM_CACHE_DIR" not in os.environ:
|
||||
from nanobot.config.paths import get_data_dir
|
||||
|
||||
os.environ.setdefault("TIKTOKEN_CACHE_DIR", str(get_data_dir() / "cache" / "tiktoken"))
|
||||
_encoding = tiktoken.get_encoding("cl100k_base")
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"Token encoding unavailable ({}); using UTF-8 byte estimates until restart.", exc,
|
||||
)
|
||||
|
||||
|
||||
def warmup_token_encoding() -> None:
|
||||
"""Start one process-wide load; tiktoken reuses its persistent vocabulary cache."""
|
||||
global _warmup_thread
|
||||
with _warmup_lock:
|
||||
if _warmup_thread is not None:
|
||||
return
|
||||
# A stalled upstream download must not hold up asyncio's executor shutdown.
|
||||
_warmup_thread = Thread(target=_load_encoding, name="nanobot-tokenizer", daemon=True)
|
||||
try:
|
||||
_warmup_thread.start()
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"Token encoding unavailable ({}); using UTF-8 byte estimates until restart.", exc,
|
||||
)
|
||||
|
||||
|
||||
def get_token_encoding() -> tiktoken.Encoding | None:
|
||||
"""Return immediately, using byte estimates while loading or after failure."""
|
||||
if _warmup_thread is None:
|
||||
warmup_token_encoding()
|
||||
return _encoding
|
||||
Reference in new issue
Block a user