use crate::message::{Media, Message, Part, Role};
use async_trait::async_trait;
pub type HistoryError = Box<dyn std::error::Error + Send + Sync>;
#[async_trait]
pub trait HistoryProcessor: Send + Sync {
async fn process(&self, messages: Vec<Message>) -> Result<Vec<Message>, HistoryError>;
}
#[async_trait]
impl<F> HistoryProcessor for F
where
F: Fn(Vec<Message>) -> Vec<Message> + Send + Sync,
{
async fn process(&self, messages: Vec<Message>) -> Result<Vec<Message>, HistoryError> {
Ok(self(messages))
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct HistoryPruning {
pub media: bool,
pub reasoning: bool,
}
impl HistoryPruning {
pub fn with_media(mut self, media: bool) -> Self {
self.media = media;
self
}
pub fn with_reasoning(mut self, reasoning: bool) -> Self {
self.reasoning = reasoning;
self
}
pub fn prune(&self, history: &[Message]) -> Vec<Message> {
let finished = history
.iter()
.rposition(|message| message.role == Role::Assistant && message.tool_calls().is_empty())
.map_or(0, |last_answer| last_answer + 1);
let (old, current) = history.split_at(finished);
let mut media_replaced = false;
let mut pruned = Vec::with_capacity(history.len());
for message in old {
if message.role == Role::User {
media_replaced = false;
}
let mut message = message.clone();
if self.reasoning || media_replaced {
message = message.without_reasoning();
}
if self.media && has_media(&message.parts) {
message = message.without_media();
media_replaced = true;
}
if !message.parts.is_empty() {
pruned.push(message);
}
}
pruned.extend(current.iter().cloned());
pruned
}
}
#[async_trait]
impl HistoryProcessor for HistoryPruning {
async fn process(&self, messages: Vec<Message>) -> Result<Vec<Message>, HistoryError> {
Ok(self.prune(&messages))
}
}
impl Message {
pub fn without_media(mut self) -> Self {
self.parts = parts_without_media(self.parts);
self
}
pub fn without_reasoning(mut self) -> Self {
self.parts.retain(|part| {
!matches!(
part,
Part::Reasoning(_) | Part::ReasoningSignature(_) | Part::ProviderData(_)
)
});
for part in &mut self.parts {
if let Part::ToolCall(call) = part {
call.signatures.clear();
}
}
self
}
}
fn has_media(parts: &[Part]) -> bool {
parts.iter().any(|part| match part {
Part::Media(_) => true,
Part::ToolResponse(response) => has_media(&response.content),
_ => false,
})
}
fn parts_without_media(parts: Vec<Part>) -> Vec<Part> {
parts
.into_iter()
.map(|part| match part {
Part::Media(media) => Part::Text(media_placeholder(&media)),
Part::ToolResponse(mut response) => {
response.content = parts_without_media(response.content);
Part::ToolResponse(response)
}
part => part,
})
.collect()
}
fn media_placeholder(media: &Media) -> String {
match &media.name {
Some(name) => format!("[omitted {}: {name}]", media.content_type),
None => format!("[omitted {}]", media.content_type),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::message::{ToolCall, ToolOutput, ToolResponse};
use serde_json::json;
fn image() -> Media {
Media::from_base64("image/png", "aGk=").with_name("cat.png")
}
fn history() -> Vec<Message> {
let call = ToolCall::new("1", "draw", json!({})).with_signatures(vec!["sig".into()]);
let tool_use = Message::new(
Role::Assistant,
vec![
Part::Reasoning("let me draw".into()),
Part::ReasoningSignature("sig".into()),
Part::ToolCall(call.clone()),
],
);
let result = Message::tool_response(ToolResponse::new(
&call,
ToolOutput::from_text("Drew it").with_media(image()),
));
vec![
Message::new(
Role::User,
vec![Part::Text("draw this".into()), Part::Media(image())],
),
tool_use.clone(),
result.clone(),
Message::new(Role::Assistant, vec![Part::Reasoning("done".into())]),
Message::assistant("Here it is"),
Message::user("again"),
tool_use,
result,
]
}
#[test]
fn prunes_finished_turns_and_keeps_the_unfinished_one() {
let history = history();
let pruned = HistoryPruning::default()
.with_media(true)
.with_reasoning(true)
.prune(&history);
let call = ToolCall::new("1", "draw", json!({}));
let expected_old = [
Message::new(
Role::User,
vec![
Part::Text("draw this".into()),
Part::Text("[omitted image/png: cat.png]".into()),
],
),
Message::new(Role::Assistant, vec![Part::ToolCall(call.clone())]),
Message::tool_response(ToolResponse::new(
&call,
ToolOutput::from_text("Drew it").with_text("[omitted image/png: cat.png]"),
)),
Message::assistant("Here it is"),
];
assert_eq!(pruned[..4], expected_old[..]);
assert_eq!(pruned[4..], history[5..]);
}
#[test]
fn media_alone_removes_the_reasoning_after_the_replaced_media_in_its_turn() {
let history = history();
let pruned = HistoryPruning::default().with_media(true).prune(&history);
let bare_call = ToolCall::new("1", "draw", json!({}));
assert_eq!(
pruned[1],
Message::new(Role::Assistant, vec![Part::ToolCall(bare_call)])
);
assert_eq!(pruned[4..], history[5..]);
let call = ToolCall::new("1", "draw", json!({}));
let text_only = vec![
Message::user("hi"),
history[1].clone(),
Message::tool_response(ToolResponse::new(&call, "Drew it")),
Message::assistant("done"),
];
assert_eq!(
HistoryPruning::default().with_media(true).prune(&text_only),
text_only
);
}
#[test]
fn a_history_without_a_final_answer_is_kept() {
let history = history()[..3].to_vec();
let pruned = HistoryPruning::default()
.with_media(true)
.with_reasoning(true)
.prune(&history);
assert_eq!(pruned, history);
}
}