Skip to main content

langchain_rust/schemas/
memory.rs

1use async_trait::async_trait;
2use thiserror::Error;
3
4use super::messages::Message;
5
6/// Errors returned by [`BaseMemory`] implementations (mostly persistent backends).
7#[derive(Error, Debug)]
8#[non_exhaustive]
9pub enum MemoryError {
10    #[error("Memory storage error: {0}")]
11    Storage(String),
12
13    #[error("Memory serialization error: {0}")]
14    Serialization(#[from] serde_json::Error),
15
16    #[error("Memory error: {0}")]
17    Other(String),
18}
19
20#[cfg(feature = "sqlx")]
21impl From<sqlx::Error> for MemoryError {
22    fn from(e: sqlx::Error) -> Self {
23        MemoryError::Storage(e.to_string())
24    }
25}
26
27#[cfg(feature = "redis")]
28impl From<redis::RedisError> for MemoryError {
29    fn from(e: redis::RedisError) -> Self {
30        MemoryError::Storage(e.to_string())
31    }
32}
33
34#[cfg(feature = "mongodb")]
35impl From<mongodb::error::Error> for MemoryError {
36    fn from(e: mongodb::error::Error) -> Self {
37        MemoryError::Storage(e.to_string())
38    }
39}
40
41/// Conversation memory used by chains and agents.
42///
43/// All methods are async and fallible so that memories can be backed by a database
44/// or a remote service (see `SqliteMessageHistory` / `PostgresMessageHistory`).
45#[async_trait]
46pub trait BaseMemory: Send + Sync {
47    async fn messages(&self) -> Result<Vec<Message>, MemoryError>;
48
49    async fn add_user_message(
50        &mut self,
51        message: &(dyn std::fmt::Display + Sync),
52    ) -> Result<(), MemoryError> {
53        self.add_message(Message::new_human_message(message.to_string()))
54            .await
55    }
56
57    async fn add_ai_message(
58        &mut self,
59        message: &(dyn std::fmt::Display + Sync),
60    ) -> Result<(), MemoryError> {
61        self.add_message(Message::new_ai_message(message.to_string()))
62            .await
63    }
64
65    async fn add_message(&mut self, message: Message) -> Result<(), MemoryError>;
66
67    async fn clear(&mut self) -> Result<(), MemoryError>;
68
69    async fn to_string(&self) -> Result<String, MemoryError> {
70        Ok(self
71            .messages()
72            .await?
73            .iter()
74            .map(|msg| {
75                format!(
76                    "{}: {}",
77                    msg.message_type.to_string(),
78                    msg.text_with_image_markers()
79                )
80            })
81            .collect::<Vec<String>>()
82            .join("\n"))
83    }
84}
85
86impl<M> From<M> for Box<dyn BaseMemory>
87where
88    M: BaseMemory + 'static,
89{
90    fn from(memory: M) -> Self {
91        Box::new(memory)
92    }
93}