use crate::redactor::preview_global;
#[derive(Debug, Clone, Copy, Default)]
pub struct TokenEstimate {
pub chars: usize,
pub estimated_tokens: u64,
}
#[derive(Debug, Clone, Default)]
pub struct TokenEstimator {
chars_per_token: f64,
json_overhead_per_struct_char: f64,
}
impl TokenEstimator {
pub fn new() -> Self {
Self {
chars_per_token: 4.0,
json_overhead_per_struct_char: 0.25,
}
}
pub fn estimate(&self, text: &str) -> TokenEstimate {
let chars = text.chars().count();
let struct_chars = text
.chars()
.filter(|c| matches!(c, '{' | '}' | '[' | ']' | ':' | ','))
.count();
let base = chars as f64 / self.chars_per_token;
let overhead = struct_chars as f64 * self.json_overhead_per_struct_char;
let estimated_tokens = (base + overhead).ceil().max(1.0) as u64;
TokenEstimate {
chars,
estimated_tokens,
}
}
pub fn estimate_with_preview(
&self,
text: &str,
max_preview: usize,
) -> (TokenEstimate, Option<String>) {
let estimate = self.estimate(text);
let preview = preview_global(text, max_preview);
(estimate, preview)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn estimates_tokens_for_short_text() {
let e = TokenEstimator::new();
let t = e.estimate("hello");
assert_eq!(t.estimated_tokens, 2);
}
#[test]
fn estimates_tokens_for_empty_text() {
let e = TokenEstimator::new();
let t = e.estimate("");
assert_eq!(t.estimated_tokens, 1); }
#[test]
fn json_overhead_increases_estimate() {
let e = TokenEstimator::new();
let plain = e.estimate("hello world");
let json = e.estimate(r#"{"hello":"world"}"#);
assert!(json.estimated_tokens >= plain.estimated_tokens);
}
#[test]
fn preview_is_redacted() {
let e = TokenEstimator::new();
let (_est, preview) =
e.estimate_with_preview("sk-abcdef1234567890abcdef1234567890abcdef", 100);
assert!(preview.is_some());
assert!(!preview.unwrap().contains("sk-abcdef"));
}
}