pub fn truncate_messages(
messages: &[Message],
keep: usize,
preserve_system: bool,
) -> Vec<Message>Expand description
Truncate message history, keeping recent messages
Always preserves the system prompt (if present) and keeps the most recent N messages. This is a simple truncation - it does NOT attempt to preserve tool chains or important context.
§Arguments
messages- List of messages to truncatekeep- Number of recent messages to keep (default: 10)preserve_system- Keep system message if present (default: true)
§Returns
Truncated message list (new Vec, original unchanged)
§Examples
use open_agent::{Message, Client, truncate_messages, estimate_tokens};
// Manual truncation when needed
let tokens = estimate_tokens(client.history());
if tokens > 28000 {
let truncated = truncate_messages(client.history(), 10, true);
*client.history_mut() = truncated;
}§Note
This is a SIMPLE truncation. For domain-specific needs (e.g., preserving tool call chains, keeping important context), implement your own logic or use this as a starting point.
Warning: Truncating mid-conversation may remove context that the model needs to properly respond. Use judiciously at natural breakpoints.