Files
2026-11-27 14:43:37 +08:00

64 lines
2.9 KiB
Python

"""Count shared-model capacity without retaining prompts or changing generation."""
import hashlib
import json
import threading
from collections import OrderedDict
from app.core.config import get_settings
_counts = OrderedDict()
_lock = threading.Lock()
_tokenizers = threading.BoundedSemaphore(4)
FULL_CONTEXT = 32768
class TokenCountUnavailable(RuntimeError):
"""A tokenization timeout is not proof that a prompt exceeds context."""
def request_tokens(messages, output_tokens, client, *, require_exact=False):
content = json.dumps(messages, ensure_ascii=False, separators=(',', ':'))
# UTF-8 byte length is a conservative token bound for text. Short calls need
# no remote counting; this also avoids an extra connection burst on first use.
conservative = min(FULL_CONTEXT, len(content.encode('utf-8')) + max(0, output_tokens) + 512)
exact_needed = require_exact and conservative > FULL_CONTEXT - 640
if conservative <= 2048:
return conservative
settings = get_settings()
if (not settings.work_assistant_model_enabled or settings.work_assistant_model_control_url
or not settings.direct_llm_api_key):
return conservative
base = settings.direct_llm_base_url.rstrip('/')
# Tokenization is available on the existing self-hosted compatible server.
# Unsupported tokenizers fall back to the conservative byte bound above.
endpoint = (base[:-3] if base.endswith('/v1') else base) + '/tokenize'
key = hashlib.sha256((base + settings.direct_llm_model + content).encode()).digest()
with _lock:
count = _counts.get(key)
if count is not None:
_counts.move_to_end(key)
if count is None:
try:
if not _tokenizers.acquire(timeout=10 if require_exact else 2):
if exact_needed:raise TokenCountUnavailable()
return conservative
try:
response = client.post(endpoint, headers={'Authorization': 'Bearer ' + settings.direct_llm_api_key},
json={'model': settings.direct_llm_model, 'messages': messages, 'add_generation_prompt': True}, timeout=15 if require_exact else 3)
response.raise_for_status()
count = response.json()['count']
finally:
_tokenizers.release()
if isinstance(count, bool) or not isinstance(count, int) or count <= 0:
if exact_needed:raise TokenCountUnavailable()
return conservative
except Exception as exc:
if exact_needed:raise TokenCountUnavailable() from exc
return conservative
with _lock:
_counts[key] = count
while len(_counts) > 256:
_counts.popitem(last=False)
# Padding covers small instructions appended by the progress-aware gateway.
return min(FULL_CONTEXT, count + max(0, output_tokens) + 128)