Files
company-ai-platform/app/modules/work_assistant/model_capacity.py
T
2026-11-14 22:48:33 +08:00

56 lines
2.4 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
def request_tokens(messages, output_tokens, client):
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)
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=2):
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=3)
response.raise_for_status()
count = response.json()['count']
finally:
_tokenizers.release()
if isinstance(count, bool) or not isinstance(count, int) or count <= 0:
return conservative
except Exception:
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)