Spaces:
Runtime error

humanizer-engine / app /utils /token_utils.py
faseehsandhu's picture
stage 1 completed
f66da21
Raw History Blame Contribute Delete
1.88 kB
"""
Token counting and max_tokens calculation utilities.
We deliberately avoid importing a tokeniser here to keep this module
dependency-free. Token counts are approximated using a conservative
words-to-tokens ratio (1 word ≈ 1.4 tokens for English prose).
"""
from __future__ import annotations
# Empirical words-to-tokens ratio for English prose.
# Claude/GPT tokenisers typically produce ~1.3-1.5 tokens per word.
_WORDS_TO_TOKENS: float = 1.4
def count_tokens(text: str, model: str = "") -> int: # noqa: ARG001
"""Approximate the number of tokens in *text*.
Args:
text: Any string.
model: LLM model name (currently unused — kept for future exact counting
via tiktoken or the Anthropic token-counting API).
Returns:
Estimated integer token count.
"""
word_count = len(text.split())
return int(word_count * _WORDS_TO_TOKENS)
def calculate_max_tokens(
input_word_count: int,
max_expansion: float = 0.40,
token_ratio: float = _WORDS_TO_TOKENS,
safety_buffer: float = 1.5,
) -> int:
"""Calculate the max_tokens parameter to pass to the LLM.
Formula: input_word_count × (1 + max_expansion) × token_ratio × safety_buffer
Args:
input_word_count: Number of words in the original text.
max_expansion: Maximum allowed length increase as a fraction (e.g. 0.40 = 40%).
token_ratio: Tokens-per-word ratio for the target model.
safety_buffer: Multiplier to ensure we never hard-truncate the output.
Returns:
Integer value suitable for the ``max_tokens`` parameter of any LLM API call.
"""
expanded_words = input_word_count * (1.0 + max_expansion)
tokens = expanded_words * token_ratio * safety_buffer
# Clamp to a sensible minimum so short inputs still get a reasonable budget
return max(256, int(tokens))