agentai_core/history.rs
1//! # Processing the history before it is sent
2//!
3//! Every model call sends the whole conversation again. A [`HistoryProcessor`] gets the
4//! messages right before each call and returns the ones to send, so it can drop, shorten or
5//! summarize them. Only the request changes: the history you own and the messages of the run
6//! keep everything.
7//!
8//! [`HistoryPruning`] is a ready-made processor: it removes media and the model's reasoning from
9//! the turns that are finished. A closure `Fn(Vec<Message>) -> Vec<Message>` is a processor too.
10//!
11//! Add processors with `Agent::with_history_processor` in `agentai`.
12
13use crate::message::{Media, Message, Part, Role};
14use async_trait::async_trait;
15
16/// Error returned by a [`HistoryProcessor`]. It stops the run with `AgentError::History` in
17/// `agentai`.
18pub type HistoryError = Box<dyn std::error::Error + Send + Sync>;
19
20/// Changes the messages sent to the model.
21///
22/// Called before every model call of a run with the history followed by the messages of the
23/// run so far, including the tool results of an unfinished tool loop. Keep an assistant
24/// message with tool calls together with its tool results, and keep the reasoning of an
25/// unfinished tool loop: Anthropic and Gemini reject the request otherwise.
26///
27/// The processor runs before every call, so return the same messages for the same input:
28/// prompt caching only works when what was sent before is sent the same way again.
29///
30/// ```rust
31/// use agentai_core::history::{HistoryError, HistoryProcessor};
32/// use agentai_core::message::Message;
33/// use async_trait::async_trait;
34///
35/// /// Sends only the last messages.
36/// struct KeepLast(usize);
37///
38/// #[async_trait]
39/// impl HistoryProcessor for KeepLast {
40/// async fn process(&self, messages: Vec<Message>) -> Result<Vec<Message>, HistoryError> {
41/// // A real processor must not separate tool calls from their results
42/// let start = messages.len().saturating_sub(self.0);
43/// Ok(messages[start..].to_vec())
44/// }
45/// }
46/// ```
47#[async_trait]
48pub trait HistoryProcessor: Send + Sync {
49 /// Returns the messages to send instead of `messages`.
50 async fn process(&self, messages: Vec<Message>) -> Result<Vec<Message>, HistoryError>;
51}
52
53#[async_trait]
54impl<F> HistoryProcessor for F
55where
56 F: Fn(Vec<Message>) -> Vec<Message> + Send + Sync,
57{
58 async fn process(&self, messages: Vec<Message>) -> Result<Vec<Message>, HistoryError> {
59 Ok(self(messages))
60 }
61}
62
63/// A [`HistoryProcessor`] that removes media and reasoning from the finished turns. Nothing is
64/// removed by default.
65///
66/// A turn is finished once the model gave its final answer: an assistant message without tool
67/// calls. Messages after the last such answer, for example the tool loop of the current run,
68/// are kept as they are.
69///
70/// ```rust
71/// # use agentai_core::history::HistoryPruning;
72/// # use agentai_core::message::Message;
73/// # let history: Vec<Message> = Vec::new();
74/// let pruning = HistoryPruning::default().with_media(true).with_reasoning(true);
75/// // Usually passed to `Agent::with_history_processor`; it can also be called directly
76/// let pruned: Vec<Message> = pruning.prune(&history);
77/// ```
78#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
79#[non_exhaustive]
80pub struct HistoryPruning {
81 /// Replace media (images, audio, files) in user messages and tool results with a short
82 /// text such as `[omitted image/png: cat.png]`, so the model knows a file was there. Tools
83 /// that return files should also say how to get them again, for example by an ID.
84 ///
85 /// The reasoning that follows replaced media in the same turn is removed too, even
86 /// without [`reasoning`](HistoryPruning::reasoning): Anthropic rejects thinking blocks
87 /// whose earlier content changed.
88 pub media: bool,
89 /// Remove the model's reasoning: [`Part::Reasoning`], [`Part::ReasoningSignature`],
90 /// [`Part::ProviderData`] and the signatures of tool calls.
91 pub reasoning: bool,
92}
93
94impl HistoryPruning {
95 /// Sets whether media in finished turns is replaced with text.
96 pub fn with_media(mut self, media: bool) -> Self {
97 self.media = media;
98 self
99 }
100
101 /// Sets whether reasoning in finished turns is removed.
102 pub fn with_reasoning(mut self, reasoning: bool) -> Self {
103 self.reasoning = reasoning;
104 self
105 }
106
107 /// Returns the history with the finished turns pruned. Messages left without any part are
108 /// dropped.
109 pub fn prune(&self, history: &[Message]) -> Vec<Message> {
110 let finished = history
111 .iter()
112 .rposition(|message| message.role == Role::Assistant && message.tool_calls().is_empty())
113 .map_or(0, |last_answer| last_answer + 1);
114 let (old, current) = history.split_at(finished);
115 // Set once media of the current turn was replaced: the reasoning after it is stale
116 let mut media_replaced = false;
117 let mut pruned = Vec::with_capacity(history.len());
118 for message in old {
119 if message.role == Role::User {
120 media_replaced = false;
121 }
122 let mut message = message.clone();
123 if self.reasoning || media_replaced {
124 message = message.without_reasoning();
125 }
126 if self.media && has_media(&message.parts) {
127 message = message.without_media();
128 media_replaced = true;
129 }
130 if !message.parts.is_empty() {
131 pruned.push(message);
132 }
133 }
134 pruned.extend(current.iter().cloned());
135 pruned
136 }
137}
138
139#[async_trait]
140impl HistoryProcessor for HistoryPruning {
141 async fn process(&self, messages: Vec<Message>) -> Result<Vec<Message>, HistoryError> {
142 Ok(self.prune(&messages))
143 }
144}
145
146impl Message {
147 /// Returns the message with every media part, also inside tool results, replaced with a
148 /// short text such as `[omitted image/png: cat.png]`.
149 pub fn without_media(mut self) -> Self {
150 self.parts = parts_without_media(self.parts);
151 self
152 }
153
154 /// Returns the message without the model's reasoning: [`Part::Reasoning`],
155 /// [`Part::ReasoningSignature`], [`Part::ProviderData`] and the signatures of tool calls.
156 ///
157 /// Only remove it from finished turns: during a tool loop, Anthropic and Gemini need the
158 /// reasoning back unchanged.
159 ///
160 /// Anthropic also rejects a stored history whose thinking was created with another system
161 /// prompt or other tools. After changing them, remove the reasoning once and save the
162 /// history again:
163 ///
164 /// ```rust
165 /// # use agentai_core::message::Message;
166 /// # let history: Vec<Message> = Vec::new();
167 /// let history: Vec<Message> = history
168 /// .into_iter()
169 /// .map(Message::without_reasoning)
170 /// .filter(|message| !message.parts.is_empty())
171 /// .collect();
172 /// ```
173 pub fn without_reasoning(mut self) -> Self {
174 self.parts.retain(|part| {
175 !matches!(
176 part,
177 Part::Reasoning(_) | Part::ReasoningSignature(_) | Part::ProviderData(_)
178 )
179 });
180 for part in &mut self.parts {
181 if let Part::ToolCall(call) = part {
182 call.signatures.clear();
183 }
184 }
185 self
186 }
187}
188
189fn has_media(parts: &[Part]) -> bool {
190 parts.iter().any(|part| match part {
191 Part::Media(_) => true,
192 Part::ToolResponse(response) => has_media(&response.content),
193 _ => false,
194 })
195}
196
197fn parts_without_media(parts: Vec<Part>) -> Vec<Part> {
198 parts
199 .into_iter()
200 .map(|part| match part {
201 Part::Media(media) => Part::Text(media_placeholder(&media)),
202 Part::ToolResponse(mut response) => {
203 response.content = parts_without_media(response.content);
204 Part::ToolResponse(response)
205 }
206 part => part,
207 })
208 .collect()
209}
210
211fn media_placeholder(media: &Media) -> String {
212 match &media.name {
213 Some(name) => format!("[omitted {}: {name}]", media.content_type),
214 None => format!("[omitted {}]", media.content_type),
215 }
216}
217
218#[cfg(test)]
219mod tests {
220 use super::*;
221 use crate::message::{ToolCall, ToolOutput, ToolResponse};
222 use serde_json::json;
223
224 fn image() -> Media {
225 Media::from_base64("image/png", "aGk=").with_name("cat.png")
226 }
227
228 /// One finished turn with a tool round, then a tool loop that has not answered yet.
229 fn history() -> Vec<Message> {
230 let call = ToolCall::new("1", "draw", json!({})).with_signatures(vec!["sig".into()]);
231 let tool_use = Message::new(
232 Role::Assistant,
233 vec![
234 Part::Reasoning("let me draw".into()),
235 Part::ReasoningSignature("sig".into()),
236 Part::ToolCall(call.clone()),
237 ],
238 );
239 let result = Message::tool_response(ToolResponse::new(
240 &call,
241 ToolOutput::from_text("Drew it").with_media(image()),
242 ));
243 vec![
244 Message::new(
245 Role::User,
246 vec![Part::Text("draw this".into()), Part::Media(image())],
247 ),
248 tool_use.clone(),
249 result.clone(),
250 // Only reasoning: dropped once the reasoning is removed
251 Message::new(Role::Assistant, vec![Part::Reasoning("done".into())]),
252 Message::assistant("Here it is"),
253 Message::user("again"),
254 tool_use,
255 result,
256 ]
257 }
258
259 #[test]
260 fn prunes_finished_turns_and_keeps_the_unfinished_one() {
261 let history = history();
262 let pruned = HistoryPruning::default()
263 .with_media(true)
264 .with_reasoning(true)
265 .prune(&history);
266
267 let call = ToolCall::new("1", "draw", json!({}));
268 let expected_old = [
269 Message::new(
270 Role::User,
271 vec![
272 Part::Text("draw this".into()),
273 Part::Text("[omitted image/png: cat.png]".into()),
274 ],
275 ),
276 Message::new(Role::Assistant, vec![Part::ToolCall(call.clone())]),
277 Message::tool_response(ToolResponse::new(
278 &call,
279 ToolOutput::from_text("Drew it").with_text("[omitted image/png: cat.png]"),
280 )),
281 Message::assistant("Here it is"),
282 ];
283 assert_eq!(pruned[..4], expected_old[..]);
284 assert_eq!(pruned[4..], history[5..]);
285 }
286
287 #[test]
288 fn media_alone_removes_the_reasoning_after_the_replaced_media_in_its_turn() {
289 let history = history();
290 let pruned = HistoryPruning::default().with_media(true).prune(&history);
291
292 let bare_call = ToolCall::new("1", "draw", json!({}));
293 // The user's image is replaced, so the tool call after it loses its reasoning
294 assert_eq!(
295 pruned[1],
296 Message::new(Role::Assistant, vec![Part::ToolCall(bare_call)])
297 );
298 assert_eq!(pruned[4..], history[5..]);
299
300 // A turn without media keeps its reasoning
301 let call = ToolCall::new("1", "draw", json!({}));
302 let text_only = vec![
303 Message::user("hi"),
304 history[1].clone(),
305 Message::tool_response(ToolResponse::new(&call, "Drew it")),
306 Message::assistant("done"),
307 ];
308 assert_eq!(
309 HistoryPruning::default().with_media(true).prune(&text_only),
310 text_only
311 );
312 }
313
314 #[test]
315 fn a_history_without_a_final_answer_is_kept() {
316 let history = history()[..3].to_vec();
317 let pruned = HistoryPruning::default()
318 .with_media(true)
319 .with_reasoning(true)
320 .prune(&history);
321 assert_eq!(pruned, history);
322 }
323}