datarobot_genai.core.utils.token_tracking
token_tracking
Token estimation utilities for LLM context management.
Provides fast, dependency-free heuristic token counting that works offline without requiring tiktoken or network access. Optimized for CSV/tabular data with ~8% average error compared to tiktoken on real-world datasets.
Example usage
from datarobot_genai.core.utils.token_tracking import estimate_tokens tokens = estimate_tokens("Hello, world!") print(f"Estimated tokens: {tokens}")
For DataFrames:
from datarobot_genai.core.utils.token_tracking import estimate_csv_rows_for_token_limit csv_text, token_count = estimate_csv_rows_for_token_limit(df, max_tokens=5000)
For LLM usage tracking:
from datarobot_genai.core.utils.token_tracking import TokenUsageTracker tracker = TokenUsageTracker(strategy=HeuristicTokenCountingStrategy()) tracker.track_call(messages, response, model="gpt-4")
TokenCountingStrategy
Bases: Protocol
Protocol for token counting strategies.
Source code in datarobot_genai/core/utils/token_tracking.py
count_tokens
Count prompt and completion tokens.
Parameters
messages : list Input messages sent to LLM response : Any Response from LLM model : str Model name
Returns
tuple[int, int] (prompt_tokens, completion_tokens)
Source code in datarobot_genai/core/utils/token_tracking.py
HeuristicTokenCountingStrategy
Token counting using smart heuristic estimation.
Uses a BPE-aware algorithm that considers word length, punctuation, numbers, and special characters. More accurate than simple char/4. No external dependencies required.
Examples
strategy = HeuristicTokenCountingStrategy() messages = [{"role": "user", "content": "Hello!"}] prompt_tokens, completion_tokens = strategy.count_tokens(messages, response, "gpt-4")
Source code in datarobot_genai/core/utils/token_tracking.py
count_tokens
Count tokens using heuristic estimation.
Source code in datarobot_genai/core/utils/token_tracking.py
ApiResponseCountingStrategy
Token counting from API response (preferred when available).
Falls back to heuristic estimation if API response doesn't include usage data.
Examples
strategy = ApiResponseCountingStrategy() prompt_tokens, completion_tokens = strategy.count_tokens(messages, response, "gpt-4")
Source code in datarobot_genai/core/utils/token_tracking.py
__init__
Initialize with optional fallback strategy.
Parameters
fallback_strategy : TokenCountingStrategy, optional Strategy to use if API response doesn't have usage data. Defaults to HeuristicTokenCountingStrategy.
Source code in datarobot_genai/core/utils/token_tracking.py
count_tokens
Extract token counts from API response.
Source code in datarobot_genai/core/utils/token_tracking.py
TokenUsageTracker
Accumulates token usage across multiple LLM calls.
Useful for tracking total token consumption in a session or workflow.
Examples
tracker = TokenUsageTracker(strategy=HeuristicTokenCountingStrategy()) tracker.track_call(messages, response, "gpt-4") print(tracker.to_dict())
Source code in datarobot_genai/core/utils/token_tracking.py
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 | |
__init__
Initialize tracker with counting strategy.
Parameters
strategy : TokenCountingStrategy Token counting strategy to use for tracking.
Source code in datarobot_genai/core/utils/token_tracking.py
track_call
Track token usage from an LLM call.
Parameters
messages : list Input messages response : Any LLM response model : str Model name
Source code in datarobot_genai/core/utils/token_tracking.py
to_dict
Convert to dictionary.
Returns
dict Dictionary with prompt_tokens, completion_tokens, total_tokens, call_count, and model.
Source code in datarobot_genai/core/utils/token_tracking.py
estimate_tokens
Estimate token count using a heuristic based on BPE tokenization patterns.
This function provides a fast, dependency-free approximation of token counts without requiring tiktoken or network access.
Algorithm based on empirical observations of GPT tokenizers: - Common words (≤6 chars): ~1 token each - Longer words: split into subword tokens (~4 chars per token) - Numbers: ~3 digits per token - Punctuation: usually separate tokens - Whitespace: merged with adjacent tokens (except newlines) - CJK text (Chinese/Japanese/Korean): ~0.85 tokens per character
Unicode Support: - Handles all Unicode alphabets (Latin, Cyrillic, Arabic, Greek, etc.) - Special handling for CJK scripts which don't use word boundaries - Non-ASCII punctuation counted as individual tokens
Performance: - Small texts (<10 MB): Full accurate counting, ~12 MB/sec - Large texts (≥10 MB): Sampling-based estimation, ~600+ MB/sec (processes 10 evenly-distributed 100KB samples and extrapolates)
Accuracy (compared to tiktoken): - Real CSV data: ~8% average error (primary use case) - English prose: ±10-15% - Code/technical content: ±15-20% - Numeric-heavy content: ±5-10% - CJK text: ±15-25% (tends to overestimate, which is safer)
Based on OpenAI's tokenizer guidelines: - ~4 characters per token for English text - ~0.75 tokens per word on average Reference: https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them
For exact counts, use tiktoken or check API response usage data.
Parameters
text : str Text to estimate tokens for
Returns
int Estimated number of tokens
Source code in datarobot_genai/core/utils/token_tracking.py
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 | |
estimate_tokens_from_file
estimate_tokens_from_file(file_path: str, encoding: str = 'utf-8', sample_size: int = _SAMPLE_SIZE, sample_count: int = _SAMPLE_COUNT) -> int
Estimate token count from a file without loading it entirely into memory.
This function is memory-efficient for large files (100MB+, even multi-GB). It reads only small samples from evenly-distributed positions in the file, then extrapolates to estimate total tokens.
Memory usage: ~2-3MB regardless of file size (only samples are loaded).
Parameters
file_path : str Path to the text file encoding : str, optional File encoding (default: utf-8) sample_size : int, optional Size of each sample chunk in bytes (default: 100KB) sample_count : int, optional Number of samples to take (default: 10)
Returns
int Estimated number of tokens
Examples
tokens = estimate_tokens_from_file("large_dataset.csv") print(f"Estimated {tokens:,} tokens")
Source code in datarobot_genai/core/utils/token_tracking.py
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 | |
estimate_tokens_streaming
estimate_tokens_streaming(text_iterator: Any, sample_every_n: int = 100, max_samples: int = 1000) -> tuple[int, int]
Estimate tokens from a streaming text source (e.g., file lines, DataFrame rows).
Memory-efficient for processing large datasets row-by-row without loading everything into memory. Samples every Nth item and extrapolates.
Parameters
text_iterator : Iterable[str] Iterator yielding text strings (e.g., file lines, df rows) sample_every_n : int, optional Sample every Nth item (default: 100) max_samples : int, optional Maximum number of samples to collect (default: 1000)
Returns
tuple[int, int] (estimated_total_tokens, items_processed)
Examples
with open("large_file.csv") as f: ... tokens, lines = estimate_tokens_streaming(f) print(f"Estimated {tokens:,} tokens in {lines:,} lines")
For DataFrames:
df_iter = (row.to_csv(index=False, header=False) for _, row in df.iterrows()) tokens, rows = estimate_tokens_streaming(df_iter)
Source code in datarobot_genai/core/utils/token_tracking.py
estimate_csv_rows_for_token_limit
estimate_csv_rows_for_token_limit(df: Any, max_tokens: int, initial_rows: int = 750) -> tuple[str, int]
Estimate the optimal number of rows for CSV data to fit within token limit.
Converts a DataFrame to CSV and iteratively reduces rows until the token count fits within the specified limit. Uses heuristic token estimation for fast, offline operation.
Parameters
df : pandas.DataFrame DataFrame to convert to CSV max_tokens : int Maximum allowed tokens for the CSV data initial_rows : int, optional Initial number of rows to try (default: 750)
Returns
tuple[str, int] (csv_string, final_token_count)
Examples
import pandas as pd df = pd.DataFrame({"a": range(1000), "b": range(1000)}) csv_text, tokens = estimate_csv_rows_for_token_limit(df, max_tokens=5000) print(f"CSV has {tokens} tokens")
Source code in datarobot_genai/core/utils/token_tracking.py
count_messages_tokens
Count tokens in a list of chat messages using heuristic estimation.
Parameters
messages : list List of chat messages (OpenAI format) model : str, optional Model name (unused, kept for API compatibility)
Returns
int Estimated token count for all messages