Repository Public
1# =============================================================================2# SP BOUCHER | INFRASTRUCTURE & AUTOMATION3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : MacLustr LLM API7# File : src/maclustr_llm/tokens.py8# Description : Comptage des tokens côté passerelle (tokenizer du modèle)9# pour borner les requêtes avant le moteur.10# Module : maclustr_llm11# Repository : https://git.spboucher.ai/maclustr-llm12# Created : 2026-11-1913# Last Modified : 2026-11-1914#15# Author : Simon-Pierre Boucher16# Position : Professor of Finance17# Institution : Université du Québec en Outaouais (UQO)18# Organization : SP Boucher19# Website : https://spboucher.ai20# Git : https://git.spboucher.ai21#22# Preferred Contact: admin@spboucher.ai23# Technical Contact: dev@spboucher.ai24# Security/Admin : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License : None specified (no license file in this repository)33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""Comptage des tokens côté passerelle (tokenizer du modèle) pour borner les requêtes avant le moteur.4243Le compte exact (gabarit de chat inclus) reste celui du moteur, rapporté dans `usage`. Ici on calcule44une estimation fidèle : tokens du texte + une marge fixe par message pour les balises du gabarit.45"""4647from __future__ import annotations4849import json50from pathlib import Path51from typing import Any5253PER_MESSAGE_OVERHEAD = 554BASE_OVERHEAD = 8555657class TokenCounter:58 def __init__(self, model_dir: str | None) -> None:59 self._tok: Any = None60 if model_dir:61 path = Path(model_dir) / "tokenizer.json"62 if path.exists():63 try:64 from tokenizers import Tokenizer6566 self._tok = Tokenizer.from_file(str(path))67 except Exception:68 self._tok = None6970 @property71 def exact(self) -> bool:72 return self._tok is not None7374 def count_text(self, text: str) -> int:75 if not text:76 return 077 if self._tok is not None:78 return len(self._tok.encode(text, add_special_tokens=False).ids)79 return len(text.encode()) // 3 + 1 # repli prudent sans tokenizer8081 def count_chat(self, messages: list[dict[str, Any]], tools: list[dict[str, Any]] | None) -> int:82 n = BASE_OVERHEAD83 for m in messages:84 n += PER_MESSAGE_OVERHEAD85 content = m.get("content")86 if isinstance(content, str):87 n += self.count_text(content)88 if m.get("tool_calls"):89 n += self.count_text(json.dumps(m["tool_calls"], ensure_ascii=False))90 if tools:91 n += self.count_text(json.dumps(tools, ensure_ascii=False)) + 4092 return n93