pub fn estimate_tokens(text: &str) -> usize {
let n = if text.is_ascii() {
text.len()
} else {
text.chars().count()
};
n.div_ceil(4)
}
pub fn estimate_tokens_at_least_one(text: &str) -> usize {
estimate_tokens(text).max(1)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty_is_zero() {
assert_eq!(estimate_tokens(""), 0);
assert_eq!(estimate_tokens_at_least_one(""), 1);
}
#[test]
fn ascii_fast_path() {
assert_eq!(estimate_tokens("abcd"), 1);
assert_eq!(estimate_tokens("abcde"), 2);
assert_eq!(estimate_tokens("a"), 1); }
#[test]
fn unicode_counts_scalars() {
assert_eq!(estimate_tokens("🦀🦀🦀🦀"), 1);
assert_eq!(estimate_tokens("🦀🦀🦀🦀🦀"), 2);
}
#[test]
fn llm_wrapper_max_one() {
assert_eq!(estimate_tokens_at_least_one("a"), 1);
assert_eq!(estimate_tokens_at_least_one("abcd"), 1);
assert_eq!(estimate_tokens_at_least_one("abcde"), 2);
}
}