This commit is contained in:
zyp
2026-11-27 14:43:37 +08:00
parent 1ae94dfb1f
commit b18c6efe92
64 changed files with 5629 additions and 2414 deletions
+12 -4
View File
@@ -12,11 +12,16 @@ _tokenizers = threading.BoundedSemaphore(4)
FULL_CONTEXT = 32768
def request_tokens(messages, output_tokens, client):
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()
@@ -34,18 +39,21 @@ def request_tokens(messages, output_tokens, client):
_counts.move_to_end(key)
if count is None:
try:
if not _tokenizers.acquire(timeout=2):
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=3)
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:
except Exception as exc:
if exact_needed:raise TokenCountUnavailable() from exc
return conservative
with _lock:
_counts[key] = count