Skip to main content

Token Utilities

Lightweight token counting and context-aware chunking utilities. Works without external dependencies, with optional accuracy boost from litellm.

Quick Start

Functions

estimate_tokens

Estimate token count without external dependencies.
Uses OpenAI’s heuristics: ~4 characters per token, ~0.75 tokens per word.
str
required
Text to estimate tokens for
str
default:"max"
Estimation method: chars, words, max, min, average

count_tokens

Count tokens accurately using litellm if available, otherwise estimate.
str
required
Text to count tokens for
str
default:"gpt-4o-mini"
Model name for tokenizer selection
bool
default:"True"
Whether to try litellm for accurate counting
For very large text (>100K chars), automatically falls back to estimation for performance.

get_context_length

Get the context window size for a model.
Lookups use partial matching by descending key length, so a specific versioned name (e.g. gpt-4-32k-0314) resolves to the more specific entry (gpt-4-32k → 32768) before falling back to a shorter prefix (gpt-4 → 8192). The shared budgeter path consults litellm’s model_cost registry first — the 128,000-token default only applies when both litellm and this static table miss. See How the context window is resolved.
str
required
Model name (e.g., “gpt-4o-mini”, “claude-3-5-sonnet-20241022”)
bool
default:"True"
Whether to try litellm for accurate info
The eval path resolves the union of the canonical MODEL_LIMITS and the eval-only _EVAL_EXTRA_LENGTHS.

needs_chunking

Determine if text needs to be chunked for the given model.
str
required
Text to evaluate
str
default:"gpt-4o-mini"
Model name to check context window for
float
default:"0.8"
Fraction of context window to use (leaves room for prompts)
bool
default:"False"
If True, return detailed info dict instead of bool
Get recommended chunk size in characters for a model.
str
default:"gpt-4o-mini"
Model name
int
default:"5"
Target number of chunks
float
default:"0.8"
Fraction of context to use

CLI Integration

Use auto-chunking with the recipe judge command:
1

Run Recipe

Execute your recipe to generate a trace
2

Judge with Auto-Chunk

Use --auto-chunk to automatically handle large outputs
3

Review Results

Get accurate evaluation even for large content

How It Works

Based on OpenAI’s guidance for English text:
  • 1 token ≈ 4 characters
  • 1 token ≈ 0.75 words
  • 100 tokens ≈ 75 words
The max method (default) uses the larger of character-based and word-based estimates for conservative results.