Skip to main content

tycode_core/modules/memory/
prompt.rs

1//! Prompt component for rendering memory compaction in the system prompt.
2//!
3//! When a compaction exists, renders the compaction summary (compressed history).
4
5use std::sync::Arc;
6
7use crate::module::{PromptComponent, PromptComponentId};
8use crate::settings::config::Settings;
9
10use super::compaction::CompactionStore;
11use super::log::MemoryLog;
12
13pub const ID: PromptComponentId = PromptComponentId("memory_compaction");
14
15/// Renders memory compaction summary in the system prompt.
16pub struct CompactionPromptComponent {
17    memory_log: Arc<MemoryLog>,
18}
19
20impl CompactionPromptComponent {
21    pub fn new(memory_log: Arc<MemoryLog>) -> Self {
22        Self { memory_log }
23    }
24}
25
26impl PromptComponent for CompactionPromptComponent {
27    fn id(&self) -> PromptComponentId {
28        ID
29    }
30
31    fn build_prompt_section(&self, _settings: &Settings) -> Option<String> {
32        let memory_dir = self.memory_log.path().parent()?;
33        let store = CompactionStore::new(memory_dir.to_path_buf());
34
35        let compaction = match store.find_latest() {
36            Ok(Some(c)) => c,
37            Ok(None) => return None,
38            Err(e) => {
39                tracing::warn!("Failed to load compaction: {e:?}");
40                return None;
41            }
42        };
43
44        Some(format!(
45            "## Memories from Previous Conversations\n\n{}",
46            compaction.summary
47        ))
48    }
49}