# 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