use crate::message::{Message, Role};
const MESSAGE_OVERHEAD: usize = 4;
const PICTURE_TOKENS: usize = 900;
pub fn estimate_text_tokens(text: &str) -> usize {
text.chars().count().div_ceil(4)
}
pub fn estimate_message_tokens(m: &Message) -> usize {
let mut chars = m.content.as_deref().map_or(0, |c| c.chars().count());
for call in &m.tool_calls {
chars += call.id.chars().count()
+ call.function.name.chars().count()
+ call.function.arguments.chars().count();
}
let mut tokens = chars.div_ceil(4) + MESSAGE_OVERHEAD;
for picture in &m.images {
tokens += PICTURE_TOKENS;
tokens += estimate_text_tokens(&picture.name);
if let Some(seen) = &picture.seen {
tokens += estimate_text_tokens(seen);
}
}
tokens
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Trimmed {
pub turns: usize,
pub messages: usize,
}
pub fn trim_note(t: Trimmed) -> String {
format!(
"[trimmed {} older turn{} ({} message{}) to fit the context budget; \
earlier conversation is not shown]",
t.turns,
if t.turns == 1 { "" } else { "s" },
t.messages,
if t.messages == 1 { "" } else { "s" },
)
}
pub fn compiled_tail(t: Trimmed) -> String {
format!(
"[compiled {} older turn{} ({} message{}) into the handoff above; every [#N] row is still \
in the session and one session_search away]",
t.turns,
if t.turns == 1 { "" } else { "s" },
t.messages,
if t.messages == 1 { "" } else { "s" },
)
}
pub const DEFAULT_PROTECT_LAST_N: usize = 20;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Windows {
pub head_end: usize,
pub tail_start: usize,
pub dropped: Trimmed,
}
impl Windows {
pub fn drops_anything(&self) -> bool {
self.tail_start > self.head_end
}
pub fn dropped(&self) -> std::ops::Range<usize> {
self.head_end..self.tail_start
}
}
fn turn_starts(history: &[Message]) -> Vec<usize> {
let mut starts: Vec<usize> = history
.iter()
.enumerate()
.filter(|(_, m)| m.role == Role::User)
.map(|(i, _)| i)
.collect();
if starts.first() != Some(&0) {
starts.insert(0, 0);
}
starts
}
fn turn_cost(history: &[Message], starts: &[usize], n: usize) -> usize {
let end = starts.get(n + 1).copied().unwrap_or(history.len());
history[starts[n]..end]
.iter()
.map(estimate_message_tokens)
.sum()
}
pub fn plan_forced(system: &Message, history: &[Message], protect_last_n: usize) -> Windows {
plan_windows(system, history, usize::MAX / 2, 0, protect_last_n)
}
pub fn plan_windows(
system: &Message,
history: &[Message],
budget_tokens: usize,
fixed_tokens: usize,
protect_last_n: usize,
) -> Windows {
let nothing = Windows::default();
if budget_tokens == 0 || history.is_empty() {
return nothing;
}
let used = estimate_message_tokens(system) + fixed_tokens;
let total: usize = history.iter().map(estimate_message_tokens).sum();
if used + total <= budget_tokens {
return nothing;
}
let starts = turn_starts(history);
if starts.len() < 2 {
return nothing;
}
let first_end = starts[1];
let head_cost: usize = history[..first_end]
.iter()
.map(estimate_message_tokens)
.sum();
let reserve = if head_cost * 2 <= budget_tokens {
head_cost
} else {
0
};
let mut tail_start = history.len();
let mut tail_used = used;
let keep = protect_last_n.max(1);
for n in (0..starts.len()).rev() {
if starts.len() - n > keep {
break;
}
let cost = turn_cost(history, &starts, n);
if tail_start != history.len() && tail_used + cost + reserve > budget_tokens {
break;
}
tail_used += cost;
tail_start = starts[n];
}
let head_end =
if reserve > 0 && first_end <= tail_start && head_cost + tail_used <= budget_tokens {
first_end
} else {
0
};
if head_end >= tail_start {
return nothing;
}
Windows {
head_end,
tail_start,
dropped: Trimmed {
turns: starts
.iter()
.filter(|&&s| s >= head_end && s < tail_start)
.count(),
messages: tail_start - head_end,
},
}
}
pub fn assemble(
system: &Message,
history: &[Message],
windows: Windows,
note: Option<&str>,
) -> Vec<Message> {
let mut sys = system.clone();
if let Some(note) = note {
sys.content = Some(match sys.content.take() {
Some(c) if !c.is_empty() => format!("{c}\n\n{note}"),
_ => note.to_string(),
});
}
let head = &history[..windows.head_end.min(history.len())];
let tail = &history[windows.tail_start.min(history.len())..];
let mut v = Vec::with_capacity(1 + head.len() + tail.len());
v.push(sys);
v.extend_from_slice(head);
v.extend_from_slice(tail);
v
}
pub fn trim_to_budget(
system: &Message,
history: &[Message],
budget_tokens: usize,
fixed_tokens: usize,
) -> (Vec<Message>, Trimmed) {
let windows = plan_windows(
system,
history,
budget_tokens,
fixed_tokens,
DEFAULT_PROTECT_LAST_N,
);
let note = windows.drops_anything().then(|| trim_note(windows.dropped));
(
assemble(system, history, windows, note.as_deref()),
windows.dropped,
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::message::{FunctionCall, ToolCall};
fn call(id: &str) -> Message {
Message::assistant_tool_calls(
None,
vec![ToolCall {
id: id.into(),
kind: "function".into(),
function: FunctionCall {
name: "shell".into(),
arguments: "{}".into(),
},
}],
)
}
fn history(n: usize) -> Vec<Message> {
let pad = "x".repeat(40);
(0..n)
.flat_map(|i| {
[
Message::user(format!("q{i} {pad}")),
call(&format!("c{i}")),
Message::tool_result(format!("c{i}"), format!("r{i} {pad}")),
Message::assistant(format!("a{i} {pad}")),
]
})
.collect()
}
fn total(msgs: &[Message]) -> usize {
msgs.iter().map(estimate_message_tokens).sum()
}
#[test]
fn estimate_is_chars_over_four() {
assert_eq!(estimate_text_tokens(""), 0);
assert_eq!(estimate_text_tokens("abcd"), 1);
assert_eq!(estimate_text_tokens("abcde"), 2);
assert_eq!(estimate_text_tokens("ééééé"), 2, "counts chars, not bytes");
let m = Message::user("a".repeat(40));
assert_eq!(estimate_message_tokens(&m), 10 + MESSAGE_OVERHEAD);
assert!(estimate_message_tokens(&call("c1")) > MESSAGE_OVERHEAD);
}
#[test]
fn disabled_budget_sends_everything() {
let h = history(5);
let (msgs, t) = trim_to_budget(&Message::system("sys"), &h, 0, 0);
assert_eq!(t, Trimmed::default());
assert_eq!(msgs.len(), h.len() + 1);
assert_eq!(msgs[0].content.as_deref(), Some("sys"));
}
#[test]
fn within_budget_is_untouched() {
let h = history(2);
let (msgs, t) = trim_to_budget(&Message::system("sys"), &h, 100_000, 0);
assert_eq!(t, Trimmed::default());
assert_eq!(msgs[0].content.as_deref(), Some("sys"));
assert_eq!(&msgs[1..], &h[..]);
}
#[test]
fn the_middle_is_dropped_and_named_and_the_system_prompt_stays() {
let h = history(6);
let sys = Message::system("be helpful");
let per_turn = total(&h[..4]);
let budget = estimate_message_tokens(&sys) + per_turn * 2 + 5;
let (msgs, t) = trim_to_budget(&sys, &h, budget, 0);
assert_eq!(
t,
Trimmed {
turns: 4,
messages: 16
}
);
assert_eq!(msgs.len(), 1 + 4 + 4, "the ask, then the newest turn");
let sys_text = msgs[0].content.as_deref().unwrap();
assert!(sys_text.starts_with("be helpful\n\n[trimmed 4 older turns (16 messages)"));
assert_eq!(&msgs[1..5], &h[..4], "the ask, verbatim and whole");
assert_eq!(&msgs[5..], &h[20..], "the newest turn, in order");
assert_eq!(msgs[1].role, Role::User, "never starts mid-turn");
assert_eq!(
msgs[5].role,
Role::User,
"and never resumes mid-turn either"
);
assert!(total(&msgs[1..]) + estimate_message_tokens(&sys) <= budget);
}
#[test]
fn tool_calls_stay_paired_with_their_results() {
let h = history(8);
for budget in (10..400).step_by(7) {
let (msgs, _) = trim_to_budget(&Message::system("s"), &h, budget, 0);
let calls: Vec<_> = msgs
.iter()
.flat_map(|m| m.tool_calls.iter().map(|c| c.id.clone()))
.collect();
let results: Vec<_> = msgs.iter().filter_map(|m| m.tool_call_id.clone()).collect();
assert_eq!(calls, results, "budget {budget}");
}
}
#[test]
fn latest_turn_is_kept_even_when_over_budget() {
let h = history(3);
let (msgs, t) = trim_to_budget(&Message::system("s"), &h, 1, 0);
assert_eq!(t.turns, 2);
assert_eq!(&msgs[1..], &h[8..]);
assert!(msgs[0]
.content
.as_deref()
.unwrap()
.contains("[trimmed 2 older turns"));
}
#[test]
fn fixed_tokens_such_as_tool_specs_count_against_the_budget() {
let h = history(4);
let sys = Message::system("s");
let budget = estimate_message_tokens(&sys) + total(&h) + 10;
assert_eq!(trim_to_budget(&sys, &h, budget, 0).1, Trimmed::default());
let (_, t) = trim_to_budget(&sys, &h, budget, total(&h[..8]));
assert!(t.turns >= 2, "{t:?}");
}
#[test]
fn single_turn_history_is_never_trimmed() {
let h = history(1);
let (msgs, t) = trim_to_budget(&Message::system("s"), &h, 1, 0);
assert_eq!(t, Trimmed::default());
assert_eq!(msgs.len(), 5);
}
#[test]
fn plan_and_assemble_match_trim_to_budget() {
let h = history(6);
let sys = Message::system("s");
let budget = estimate_message_tokens(&sys) + total(&h[..4]) * 2 + 5;
let w = plan_windows(&sys, &h, budget, 0, DEFAULT_PROTECT_LAST_N);
assert_eq!(
w,
Windows {
head_end: 4,
tail_start: 20,
dropped: Trimmed {
turns: 4,
messages: 16
}
},
"the ask and the newest turn; the middle pays"
);
let note = compiled_tail(w.dropped);
let msgs = assemble(&sys, &h, w, Some(¬e));
assert_eq!(&msgs[1..5], &h[..4]);
assert_eq!(&msgs[5..], &h[20..]);
let text = msgs[0].content.as_deref().unwrap();
assert!(
text.starts_with("s\n\n[compiled 4 older turns (16 messages)")
&& text.contains("one session_search away"),
"{text}"
);
assert!(
text.contains("one session_search away"),
"the note says how to reach what was left out: {text}"
);
let off = plan_windows(&sys, &h, 0, 0, DEFAULT_PROTECT_LAST_N);
assert_eq!(off, Windows::default());
assert_eq!(assemble(&sys, &h, off, None)[0], sys);
assert_eq!(assemble(&sys, &h, off, None).len(), h.len() + 1);
}
#[test]
fn the_first_turn_is_kept_when_the_tail_leaves_room_for_it() {
let h = history(8);
let sys = Message::system("s");
let budget = estimate_message_tokens(&sys) + total(&h[..4]) * 5;
let w = plan_windows(&sys, &h, budget, 0, DEFAULT_PROTECT_LAST_N);
assert_eq!(w.head_end, 4, "the first turn, whole");
assert_eq!(w.tail_start, 16, "four of the newest turns: {w:?}");
assert!(w.dropped.turns >= 1 && w.dropped.messages >= 4, "{w:?}");
let msgs = assemble(&sys, &h, w, None);
assert_eq!(&msgs[1..5], &h[..4], "the ask is verbatim");
assert_eq!(&msgs[5..], &h[w.tail_start..], "then the tail");
assert!(total(&msgs[1..]) + estimate_message_tokens(&sys) <= budget);
assert_eq!(msgs[1].content, h[0].content);
assert_eq!(msgs.last().unwrap().content, h.last().unwrap().content);
}
#[test]
fn the_tail_is_at_most_protect_last_n_turns() {
let h = history(10);
let sys = Message::system("s");
let budget = estimate_message_tokens(&sys) + total(&h) + 10; let w = plan_windows(&sys, &h, budget, 0, 20);
assert_eq!(w, Windows::default(), "under budget nothing is dropped");
let budget = estimate_message_tokens(&sys) + total(&h[..4]) * 5;
let w = plan_windows(&sys, &h, budget, 0, 2);
assert_eq!(
w.tail_start, 32,
"two turns, whatever the budget could hold: {w:?}"
);
}
#[test]
fn the_head_gives_way_rather_than_a_turn_being_split() {
let h = history(4);
let sys = Message::system("s");
let budget = estimate_message_tokens(&sys) + total(&h[..4]) + 1;
let w = plan_windows(&sys, &h, budget, 0, DEFAULT_PROTECT_LAST_N);
assert_eq!(w.head_end, 0, "{w:?}");
assert_eq!(w.tail_start, 12, "one turn: the newest is never dropped");
let calls: Vec<_> = assemble(&sys, &h, w, None)
.iter()
.flat_map(|m| m.tool_calls.iter().map(|c| c.id.clone()))
.collect();
let results: Vec<_> = assemble(&sys, &h, w, None)
.iter()
.filter_map(|m| m.tool_call_id.clone())
.collect();
assert_eq!(calls, results);
}
fn picture() -> crate::message::ImagePart {
crate::message::ImagePart {
name: "shot.png".into(),
mime: "image/png".into(),
url: "data:image/png;base64,AAAA".into(),
seen: None,
}
}
#[test]
fn a_picture_is_charged_so_a_window_of_them_cannot_overflow_silently() {
let mut with_picture = Message::user("q xxxx");
let text_only = estimate_message_tokens(&with_picture);
with_picture.images.push(picture());
let charged = estimate_message_tokens(&with_picture);
assert!(
charged >= text_only + PICTURE_TOKENS,
"a picture costs nothing, so a native turn full of them never plans a compaction: \
{text_only} -> {charged}"
);
let mut described = with_picture.clone();
described.images[0].seen = Some("a screenshot of a dashboard ".repeat(10));
assert!(estimate_message_tokens(&described) > charged);
}
#[test]
fn a_history_of_pictures_plans_a_compaction_it_used_to_miss() {
let mut h = history(16);
for m in h.iter_mut().filter(|m| m.role == Role::User) {
m.images.push(picture());
}
let text_chars: usize = total(&h) - 16 * PICTURE_TOKENS;
let budget = text_chars + 200;
let w = plan_windows(
&Message::system("sys"),
&h,
budget,
0,
DEFAULT_PROTECT_LAST_N,
);
assert!(
w.drops_anything(),
"16 pictures were counted as free, so nothing was planned to be dropped"
);
}
}