File size: 1,821 Bytes
f80362a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# token_counter.py

import tiktoken
from logging_config import logger

encoding_model = "o200k_base"
def count_tokens(messages, encoding_name=encoding_model):
    """
    Count the total number of tokens in a list of messages, including system prompts.

    Args:
        messages (list): List of message dictionaries with 'role' and 'content' keys.
        encoding_name (str): Encoding name for tokenization (default: "o200k_base").

    Returns:
        dict: Dictionary containing the total token count and a breakdown by role.
    """
    try:
        enc = tiktoken.get_encoding(encoding_name)
        logger.info(f"Using encoding: {encoding_name}")
    except Exception as e:
        logger.error(f"Failed to get encoding '{encoding_name}': {e}")
        raise ValueError(f"Invalid encoding: {encoding_name}")

    total_tokens = 0
    token_breakdown = {}

    try:
        for m in messages:
            if not isinstance(m, dict) or "role" not in m or "content" not in m:
                logger.error(f"Invalid message format: {m}")
                raise ValueError("Each message must be a dictionary with 'role' and 'content' keys.")

            # Encode role and content
            role_tokens = len(enc.encode(m["role"]))
            content_tokens = len(enc.encode(m["content"]))
            message_tokens = role_tokens + content_tokens

            # Add to totals
            total_tokens += message_tokens
            token_breakdown[m["role"]] = token_breakdown.get(m["role"], 0) + message_tokens

        logger.info(f"Token count completed. Total tokens: {total_tokens}")
        logger.info(f"Token breakdown by role: {token_breakdown}")
        return {"total": total_tokens, "by_role": token_breakdown}
    except Exception as e:
        logger.error(f"Error counting tokens: {e}")
        raise