use crate::memory::{HnswMemoryIndex, MemoryEntry, MemoryManager, MemoryType, SemanticHit};
use std::sync::Arc;
pub struct MemoryApi {
pub(crate) memory_manager: Arc<MemoryManager>,
pub(crate) hnsw_index: Option<Arc<HnswMemoryIndex>>,
}
impl MemoryApi {
pub fn new(memory_manager: Arc<MemoryManager>) -> Self {
Self {
memory_manager,
hnsw_index: None,
}
}
pub fn set_hnsw_index(&mut self, index: Arc<HnswMemoryIndex>) {
self.hnsw_index = Some(index);
}
pub async fn remember(&self, entry: MemoryEntry) -> anyhow::Result<String> {
self.memory_manager.remember(entry).await
}
pub async fn search(
&self,
query: &str,
memory_type: Option<MemoryType>,
limit: usize,
) -> anyhow::Result<Vec<MemoryEntry>> {
self.memory_manager.search(query, memory_type, limit).await
}
pub async fn recall(&self, query: &str) -> anyhow::Result<Vec<MemoryEntry>> {
self.memory_manager.recall(query).await
}
pub async fn get(
&self,
id: &str,
memory_type: MemoryType,
) -> anyhow::Result<Option<MemoryEntry>> {
self.memory_manager.get(id, memory_type).await
}
pub async fn forget(&self, id: &str, memory_type: MemoryType) -> anyhow::Result<bool> {
self.memory_manager.forget(id, memory_type).await
}
pub async fn list(
&self,
memory_type: MemoryType,
limit: usize,
) -> anyhow::Result<Vec<MemoryEntry>> {
self.memory_manager.list(memory_type, limit).await
}
pub async fn search_semantic(
&self,
query: &str,
limit: usize,
) -> anyhow::Result<Vec<SemanticHit>> {
if let Some(hnsw) = &self.hnsw_index {
let _ = hnsw; let entries = self.memory_manager.search(query, None, limit).await?;
Ok(entries
.into_iter()
.map(|e| SemanticHit {
entry: e,
distance: 0.0,
similarity: 1.0,
})
.collect())
} else {
let entries = self.memory_manager.search(query, None, limit).await?;
Ok(entries
.into_iter()
.map(|e| SemanticHit {
entry: e,
distance: 0.0,
similarity: 1.0,
})
.collect())
}
}
pub async fn stats(&self) -> (usize, usize) {
(
self.memory_manager.total_entries().await,
self.memory_manager.vector_index_size(),
)
}
pub async fn rebuild_hnsw_index(&self) -> anyhow::Result<usize> {
if let Some(hnsw) = &self.hnsw_index {
self.memory_manager.rebuild_index().await?;
Ok(hnsw.len())
} else {
Ok(0)
}
}
pub fn manager(&self) -> &Arc<MemoryManager> {
&self.memory_manager
}
}