use super::{Memory, MemoryError};
use crate::message::Message;
#[derive(Debug, Default)]
pub struct InMemoryMemory {
messages: Vec<Message>,
}
#[async_trait::async_trait]
impl Memory for InMemoryMemory {
async fn record(&mut self, message: Message) -> Result<(), MemoryError> {
self.messages.push(message);
Ok(())
}
async fn context(&self) -> Result<Vec<Message>, MemoryError> {
Ok(self.messages.clone())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn record_preserves_order() {
let mut memory = InMemoryMemory::default();
memory.record(Message::system("setup")).await.unwrap();
memory.record(Message::user("hello")).await.unwrap();
memory.record(Message::assistant("hello!")).await.unwrap();
let context = memory.context().await.unwrap();
assert_eq!(context.len(), 3);
assert_eq!(context[0], Message::System("setup".into()));
assert_eq!(context[1], Message::user("hello"));
assert_eq!(context[2], Message::assistant("hello!"));
}
#[tokio::test]
async fn context_is_a_copy() {
let mut memory = InMemoryMemory::default();
memory.record(Message::user("a")).await.unwrap();
let mut context = memory.context().await.unwrap();
context.push(Message::assistant("b"));
assert_eq!(memory.context().await.unwrap().len(), 1);
}
}