2025-04-25 12:08:18 -07:00
|
|
|
use crate::models::ResponseItem;
|
|
|
|
|
|
2025-07-23 10:37:45 -07:00
|
|
|
/// Transcript of conversation history
|
|
|
|
|
#[derive(Debug, Clone, Default)]
|
2025-05-08 21:46:06 -07:00
|
|
|
pub(crate) struct ConversationHistory {
|
2025-04-25 12:08:18 -07:00
|
|
|
/// The oldest items are at the beginning of the vector.
|
|
|
|
|
items: Vec<ResponseItem>,
|
|
|
|
|
}
|
|
|
|
|
|
2025-05-08 21:46:06 -07:00
|
|
|
impl ConversationHistory {
|
2025-04-25 12:08:18 -07:00
|
|
|
pub(crate) fn new() -> Self {
|
|
|
|
|
Self { items: Vec::new() }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Returns a clone of the contents in the transcript.
|
|
|
|
|
pub(crate) fn contents(&self) -> Vec<ResponseItem> {
|
|
|
|
|
self.items.clone()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// `items` is ordered from oldest to newest.
|
|
|
|
|
pub(crate) fn record_items<I>(&mut self, items: I)
|
|
|
|
|
where
|
2025-05-19 16:08:18 -07:00
|
|
|
I: IntoIterator,
|
|
|
|
|
I::Item: std::ops::Deref<Target = ResponseItem>,
|
2025-04-25 12:08:18 -07:00
|
|
|
{
|
|
|
|
|
for item in items {
|
|
|
|
|
if is_api_message(&item) {
|
|
|
|
|
// Note agent-loop.ts also does filtering on some of the fields.
|
|
|
|
|
self.items.push(item.clone());
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-07-31 21:34:32 -07:00
|
|
|
|
|
|
|
|
pub(crate) fn keep_last_messages(&mut self, n: usize) {
|
|
|
|
|
if n == 0 {
|
|
|
|
|
self.items.clear();
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Collect the last N message items (assistant/user), newest to oldest.
|
|
|
|
|
let mut kept: Vec<ResponseItem> = Vec::with_capacity(n);
|
|
|
|
|
for item in self.items.iter().rev() {
|
|
|
|
|
if let ResponseItem::Message { role, content, .. } = item {
|
|
|
|
|
kept.push(ResponseItem::Message {
|
|
|
|
|
// we need to remove the id or the model will complain that messages are sent without
|
|
|
|
|
// their reasonings
|
|
|
|
|
id: None,
|
|
|
|
|
role: role.clone(),
|
|
|
|
|
content: content.clone(),
|
|
|
|
|
});
|
|
|
|
|
if kept.len() == n {
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Preserve chronological order (oldest to newest) within the kept slice.
|
|
|
|
|
kept.reverse();
|
|
|
|
|
self.items = kept;
|
|
|
|
|
}
|
2025-04-25 12:08:18 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Anything that is not a system message or "reasoning" message is considered
|
|
|
|
|
/// an API message.
|
|
|
|
|
fn is_api_message(message: &ResponseItem) -> bool {
|
|
|
|
|
match message {
|
|
|
|
|
ResponseItem::Message { role, .. } => role.as_str() != "system",
|
2025-05-16 14:38:08 -07:00
|
|
|
ResponseItem::FunctionCallOutput { .. }
|
|
|
|
|
| ResponseItem::FunctionCall { .. }
|
2025-07-23 10:37:45 -07:00
|
|
|
| ResponseItem::LocalShellCall { .. }
|
|
|
|
|
| ResponseItem::Reasoning { .. } => true,
|
|
|
|
|
ResponseItem::Other => false,
|
2025-04-25 12:08:18 -07:00
|
|
|
}
|
|
|
|
|
}
|