Expand description
Vocab-free heuristic LLM token-count estimation.
tokenx estimates how many tokens a language model would read in a string.
It uses no vocabulary or BPE table. It splits text into segments (words,
whitespace runs, punctuation runs), classifies each segment, and assigns a
token count per segment with a small set of chars-per-token rules. The result
is an estimate, not an exact count. It is not measured against any specific
tokenizer and can diverge from one on some text. See the limitations below.
Four functions make up the API:
estimate_token_countreturns the token estimate for a string.is_within_token_limitchecks the estimate against a limit.slice_by_tokensextracts a token range, likeArray.slice.split_by_tokenschunks text by a token budget, with optional overlap.
§Examples
use tokenx::estimate_token_count;
assert_eq!(estimate_token_count("Hello, world! This is a short sentence."), 11);Counting operates on UTF-16 code units for lengths and slicing, matching JavaScript string semantics. The CJK rule counts Unicode code points. For text in the Basic Multilingual Plane these agree.
§Limitations
The count is a heuristic with no measured error bound, so leave headroom when checking a hard context limit. Two biases are worth knowing:
- A whole-segment number counts as 1 token whatever its length. Real tokenizers split long digit runs, so numeric-heavy text such as logs, tables, and JSON undercounts. A 15-digit number is 1 token here but several in a typical tokenizer.
- Japanese hiragana uses the default fallback rate while katakana and kanji count one token per code point, so hiragana-heavy text undercounts.
Structs§
- Language
Config - A language rule. When
patternmatches a segment, the segment usesaverage_chars_per_tokeninstead of the default. - Split
ByTokens Options - Options for
crate::split_by_tokens. Adds chunk overlap. - Token
Estimation Options - Options for token estimation.
Functions§
- approximate_
token_ size Deprecated - Returns the token estimate for
text. Deprecated alias ofestimate_token_count. - estimate_
token_ count - Estimates the number of tokens in
text. - estimate_
token_ count_ with - Estimates the number of tokens in
textwith custom options. - is_
within_ token_ limit - Reports whether the estimate for
textis at or belowtoken_limit. - is_
within_ token_ limit_ with - Reports whether the estimate for
textis at or belowtoken_limit, with custom options. - slice_
by_ tokens - Extracts the substring covering token positions
[start, end). - slice_
by_ tokens_ with - Extracts a token range with custom options. See
slice_by_tokens. - split_
by_ tokens - Splits
textinto chunks, each holding up totokens_per_chunktokens. - split_
by_ tokens_ with - Splits
textinto chunks with custom options, including overlap. Seesplit_by_tokens.