tokens: mask old large tool results in requests; compact inside a single long tool loop
This commit is contained in:
1 parent
3943243024
commit
80c0f83a68
3 files changed
+167
-11
No files matched your search
@@ -0,0 +1,116 @@
|
||||
//! Observation masking: old, large tool results are replaced by a one-line stub in the request
|
||||
//! (the session file keeps the original). Pure function of the message list, so the request prefix
|
||||
//! is byte-stable between steps and the prompt cache only breaks once per `STEP` assistant turns.
|
||||
|
||||
use hx_ai::{ContentBlock, Message, Role};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Results from the last `KEEP` assistant turns are never masked.
|
||||
const KEEP: usize = 8;
|
||||
/// The masking boundary moves in jumps of this many assistant turns (one cache break per jump).
|
||||
const STEP: usize = 8;
|
||||
/// Results smaller than this stay (a stub would not save much).
|
||||
const MIN_BYTES: usize = 4_000;
|
||||
|
||||
pub fn mask_old_results(msgs: Vec<Message>) -> Vec<Message> {
|
||||
let total = msgs.iter().filter(|m| m.role == Role::Assistant).count();
|
||||
let boundary = total.saturating_sub(KEEP) / STEP * STEP;
|
||||
if boundary == 0 {
|
||||
return msgs;
|
||||
}
|
||||
let mut calls: HashMap<String, String> = HashMap::new();
|
||||
let mut turn = 0; // assistant messages seen up to and including this one
|
||||
msgs.into_iter()
|
||||
.map(|mut m| {
|
||||
if m.role == Role::Assistant {
|
||||
turn += 1;
|
||||
for b in &m.content {
|
||||
if let ContentBlock::ToolUse { id, name, input } = b {
|
||||
let a: String = input.to_string().chars().take(80).collect();
|
||||
calls.insert(id.clone(), format!("{name} {a}"));
|
||||
}
|
||||
}
|
||||
} else if turn <= boundary {
|
||||
for b in &mut m.content {
|
||||
if let ContentBlock::ToolResult {
|
||||
tool_use_id,
|
||||
content,
|
||||
..
|
||||
} = b
|
||||
&& content.len() >= MIN_BYTES
|
||||
{
|
||||
let what = calls.get(tool_use_id).map_or("tool", |s| s.as_str());
|
||||
*content = format!(
|
||||
"[elided old tool result: {what} ({} bytes); run the tool again if you need it]",
|
||||
content.len()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
m
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn pair(i: usize, size: usize) -> [Message; 2] {
|
||||
[
|
||||
Message {
|
||||
role: Role::Assistant,
|
||||
content: vec![ContentBlock::ToolUse {
|
||||
id: format!("t{i}"),
|
||||
name: "bash".into(),
|
||||
input: serde_json::json!({"command": format!("c{i}")}),
|
||||
}],
|
||||
},
|
||||
Message {
|
||||
role: Role::User,
|
||||
content: vec![ContentBlock::ToolResult {
|
||||
tool_use_id: format!("t{i}"),
|
||||
content: "x".repeat(size),
|
||||
is_error: false,
|
||||
}],
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn result(m: &Message) -> &str {
|
||||
match &m.content[0] {
|
||||
ContentBlock::ToolResult { content, .. } => content,
|
||||
_ => panic!(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn masks_old_big_only_in_steps() {
|
||||
let build = |n: usize| -> Vec<Message> {
|
||||
let mut v = vec![Message::user("go")];
|
||||
for i in 0..n {
|
||||
v.extend(pair(i, if i == 1 { 100 } else { 5000 }));
|
||||
}
|
||||
v
|
||||
};
|
||||
// 15 turns: boundary = (15-8)/8*8 = 0 -> untouched
|
||||
let v = mask_old_results(build(15));
|
||||
assert!(v.iter().all(|m| m.text().is_empty() || m.text() == "go"));
|
||||
assert_eq!(result(&v[2]).len(), 5000);
|
||||
// 16 turns: boundary 8 -> first 8 big results masked, small one (i=1) kept, later ones kept
|
||||
let v = mask_old_results(build(16));
|
||||
assert!(
|
||||
result(&v[2]).starts_with("[elided old tool result: bash"),
|
||||
"{}",
|
||||
result(&v[2])
|
||||
);
|
||||
assert!(result(&v[2]).contains("c0"));
|
||||
assert_eq!(result(&v[4]).len(), 100);
|
||||
assert_eq!(result(&v[2 * 8 + 2]).len(), 5000); // turn 9 untouched
|
||||
// stable: same input -> same output (prefix bytes identical between calls)
|
||||
assert_eq!(mask_old_results(build(16)), v);
|
||||
// one more turn inside the same step does not change the masked prefix
|
||||
let w = mask_old_results(build(17));
|
||||
assert_eq!(&w[..17], &v[..17]);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user