use async_trait::async_trait;
use chrono::{DateTime, Utc};
use gadk_genai::Content;
use gadk_session::{Event, Session, SessionError};
use serde_json::{Map, Value};
#[async_trait]
pub trait MemoryService: Send + Sync {
async fn add_session_to_memory(&self, session: &dyn Session) -> Result<(), MemoryError>;
async fn search_memory(&self, req: SearchRequest) -> Result<SearchResponse, MemoryError>;
fn as_event_adder(&self) -> Option<&dyn EventAdder> {
None
}
}
#[async_trait]
pub trait EventAdder: Send + Sync {
async fn add_events(&self, req: AddEventsRequest) -> Result<(), MemoryError>;
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct AddEventsRequest {
pub app_name: String,
pub user_id: String,
pub session_id: String,
pub events: Vec<Event>,
pub custom_metadata: Map<String, Value>,
}
pub async fn add_events_to_memory(
svc: &dyn MemoryService,
req: AddEventsRequest,
) -> Result<(), MemoryError> {
let adder = svc
.as_event_adder()
.ok_or(MemoryError::AddEventsUnsupported)?;
adder.add_events(req).await
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct SearchRequest {
pub query: String,
pub user_id: String,
pub app_name: String,
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct SearchResponse {
pub memories: Vec<MemoryEntry>,
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct MemoryEntry {
pub id: String,
pub content: Option<Content>,
pub author: String,
pub timestamp: Option<DateTime<Utc>>,
pub custom_metadata: Map<String, Value>,
}
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum MemoryError {
#[error("{0}")]
InvalidRequest(String),
#[error(transparent)]
Session(#[from] SessionError),
#[error(transparent)]
Backend(Box<dyn std::error::Error + Send + Sync>),
#[error(
"memory: service does not support adding event deltas; call Service.AddSessionToMemory to ingest the full session"
)]
AddEventsUnsupported,
}