const CHARS_PER_TOKEN: usize = 4;
pub fn estimate_tokens(s: &str) -> usize {
s.len().div_ceil(CHARS_PER_TOKEN)
}
pub fn estimate_json_mode_tokens(query: &str, records: &[&str]) -> usize {
let envelope = 120;
let per_record = 50;
let mut total = envelope + estimate_tokens(query);
for r in records {
total += per_record / CHARS_PER_TOKEN;
total += estimate_tokens(r);
}
total
}
pub fn estimate_code_mode_tokens(query: &str, records: &[&str], host_calls: usize) -> usize {
let mut total = estimate_tokens(query) + host_calls * 4;
for r in records {
total += estimate_tokens(r);
}
total
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn estimate_is_monotonic_in_length() {
let a = estimate_tokens("hi");
let b = estimate_tokens("hi there friend");
assert!(b > a);
}
#[test]
fn json_mode_costs_more_than_code_mode() {
let query = "find me notes about the patient";
let records: Vec<String> = (0..5)
.map(|i| format!("Patient note {i}: persistent fatigue, hemoglobin low."))
.collect();
let refs: Vec<&str> = records.iter().map(|s| s.as_str()).collect();
let json = estimate_json_mode_tokens(query, &refs);
let code = estimate_code_mode_tokens(query, &refs, 1);
assert!(
json > code,
"expected json > code, got json={json} code={code}"
);
}
#[test]
fn long_conversation_savings_exceed_50_percent() {
let query = "what was discussed last time";
let records: Vec<String> = (0..5)
.map(|i| {
format!(
"Memory {i}: the patient discussed {} on a prior visit, lab values were within range.",
"treatment"
)
})
.collect();
let refs: Vec<&str> = records.iter().map(|s| s.as_str()).collect();
let json: usize = (0..200)
.map(|_| estimate_json_mode_tokens(query, &refs))
.sum();
let code: usize = (0..200)
.map(|_| estimate_code_mode_tokens(query, &refs, 1))
.sum();
assert!(
code * 100 / json <= 80,
"expected code-mode <= 80% of json-mode tokens, got json={json} code={code} \
ratio={}%",
code * 100 / json
);
}
}