conversation: add persistent chat sessions with token-aware compaction #7
No files matched your search
Generated
+48
-7
@@ -95,7 +95,7 @@ version = "1.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
|
||||
dependencies = [
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -106,7 +106,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"once_cell_polyfill",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -356,6 +356,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aebf35691d1bfb0ac386a69bac2fde4dd276fb618cf8bf4f5318fe285e821bb2"
|
||||
dependencies = [
|
||||
"find-msvc-tools",
|
||||
"jobserver",
|
||||
"libc",
|
||||
"shlex",
|
||||
]
|
||||
|
||||
@@ -790,7 +792,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1560,6 +1562,16 @@ version = "1.0.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2"
|
||||
|
||||
[[package]]
|
||||
name = "jobserver"
|
||||
version = "0.1.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "js-sys"
|
||||
version = "0.3.87"
|
||||
@@ -2109,7 +2121,7 @@ version = "0.50.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
|
||||
dependencies = [
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2238,6 +2250,7 @@ dependencies = [
|
||||
"toml 0.8.23",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"zstd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2899,7 +2912,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3275,10 +3288,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0136791f7c95b1f6dd99f9cc786b91bb81c3800b639b3478e561ddb7be95e5f1"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"getrandom 0.3.4",
|
||||
"getrandom 0.4.1",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4487,3 +4500,31 @@ name = "zmij"
|
||||
version = "1.0.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
|
||||
|
||||
[[package]]
|
||||
name = "zstd"
|
||||
version = "0.13.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a"
|
||||
dependencies = [
|
||||
"zstd-safe",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zstd-safe"
|
||||
version = "7.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d"
|
||||
dependencies = [
|
||||
"zstd-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zstd-sys"
|
||||
version = "2.0.16+zstd.1.5.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"pkg-config",
|
||||
]
|
||||
@@ -23,6 +23,7 @@ tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
|
||||
toml = "0.8"
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
zstd = "0.13"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
@@ -3,6 +3,7 @@ use anyhow::bail;
|
||||
pub enum Command {
|
||||
Help,
|
||||
Clear,
|
||||
Compact,
|
||||
Context,
|
||||
Memory,
|
||||
}
|
||||
@@ -15,6 +16,7 @@ impl TryFrom<&str> for Command {
|
||||
match cmd {
|
||||
"/help" => Ok(Command::Help),
|
||||
"/clear" => Ok(Command::Clear),
|
||||
"/compact" => Ok(Command::Compact),
|
||||
"/context" => Ok(Command::Context),
|
||||
"/memory" => Ok(Command::Memory),
|
||||
_ => bail!("Unknown command: {cmd}"),
|
||||
@@ -26,6 +28,7 @@ impl Command {
|
||||
pub fn help_text() -> &'static str {
|
||||
"/help - Show this help message\n\
|
||||
/clear - Clear conversation history\n\
|
||||
/compact - Compact conversation history now\n\
|
||||
/context - Show current conversation context\n\
|
||||
/memory - Show memory/personality status"
|
||||
}
|
||||
|
||||
@@ -10,6 +10,35 @@ pub struct Config {
|
||||
pub llm: LlmConfig,
|
||||
#[serde(default)]
|
||||
pub memory: MemoryConfig,
|
||||
#[serde(default)]
|
||||
pub conversation: ConversationConfig,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Clone)]
|
||||
pub struct ConversationConfig {
|
||||
/// Compact when prompt tokens exceed this threshold.
|
||||
#[serde(default = "default_compact_at_tokens")]
|
||||
pub compact_at_tokens: usize,
|
||||
/// Number of recent messages to keep after compaction.
|
||||
#[serde(default = "default_compact_retain")]
|
||||
pub compact_retain: usize,
|
||||
}
|
||||
|
||||
impl Default for ConversationConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
compact_at_tokens: default_compact_at_tokens(),
|
||||
compact_retain: default_compact_retain(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn default_compact_at_tokens() -> usize {
|
||||
200_000
|
||||
}
|
||||
|
||||
fn default_compact_retain() -> usize {
|
||||
20
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Clone)]
|
||||
|
||||
@@ -0,0 +1,403 @@
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::time::SystemTime;
|
||||
|
||||
use anyhow::Context as _;
|
||||
use anyhow::Result;
|
||||
use matrix_sdk::ruma::OwnedRoomId;
|
||||
use matrix_sdk::ruma::RoomId;
|
||||
use sha2::Digest as _;
|
||||
use sha2::Sha256;
|
||||
use tokio::fs;
|
||||
use tokio::io::AsyncWriteExt as _;
|
||||
use tokio::sync::Mutex;
|
||||
use tracing::info;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::config::ConversationConfig;
|
||||
use crate::llm::ChatMessage;
|
||||
use crate::llm::LlmClient;
|
||||
|
||||
struct RoomState {
|
||||
messages: Vec<ChatMessage>,
|
||||
last_prompt_tokens: Option<usize>,
|
||||
}
|
||||
|
||||
pub struct ConversationStore {
|
||||
dir: PathBuf,
|
||||
archive_dir: PathBuf,
|
||||
config: ConversationConfig,
|
||||
rooms: Mutex<HashMap<OwnedRoomId, RoomState>>,
|
||||
}
|
||||
|
||||
impl ConversationStore {
|
||||
pub async fn new(state_dir: &std::path::Path, config: ConversationConfig) -> Result<Self> {
|
||||
let dir = state_dir.join("conversations");
|
||||
let archive_dir = dir.join("archive");
|
||||
fs::create_dir_all(&dir)
|
||||
.await
|
||||
.context("failed to create conversations directory")?;
|
||||
fs::create_dir_all(&archive_dir)
|
||||
.await
|
||||
.context("failed to create conversations archive directory")?;
|
||||
|
||||
Ok(Self {
|
||||
dir,
|
||||
archive_dir,
|
||||
config,
|
||||
rooms: Mutex::new(HashMap::new()),
|
||||
})
|
||||
}
|
||||
|
||||
/// Append a message, persist to disk, return the full history.
|
||||
pub async fn push_message(
|
||||
&self,
|
||||
room_id: &RoomId,
|
||||
message: ChatMessage,
|
||||
) -> Result<Vec<ChatMessage>> {
|
||||
let mut rooms = self.rooms.lock().await;
|
||||
let state = self.ensure_loaded(&mut rooms, room_id).await?;
|
||||
state.messages.push(message.clone());
|
||||
self.append_to_disk(room_id, &message).await?;
|
||||
Ok(state.messages.clone())
|
||||
}
|
||||
|
||||
/// Store the prompt token count from the last LLM response.
|
||||
pub async fn set_last_prompt_tokens(&self, room_id: &RoomId, tokens: usize) {
|
||||
let mut rooms = self.rooms.lock().await;
|
||||
if let Some(state) = rooms.get_mut(room_id) {
|
||||
state.last_prompt_tokens = Some(tokens);
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the last known prompt token count for a room.
|
||||
pub async fn last_prompt_tokens(&self, room_id: &RoomId) -> Option<usize> {
|
||||
let rooms = self.rooms.lock().await;
|
||||
rooms.get(room_id).and_then(|s| s.last_prompt_tokens)
|
||||
}
|
||||
|
||||
/// Check if compaction is needed based on prompt token count and perform it.
|
||||
pub async fn maybe_compact(
|
||||
&self,
|
||||
room_id: &RoomId,
|
||||
prompt_tokens: usize,
|
||||
llm: &LlmClient,
|
||||
) -> Result<bool> {
|
||||
if prompt_tokens < self.config.compact_at_tokens {
|
||||
return Ok(false);
|
||||
}
|
||||
self.compact(room_id, llm).await?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Force compaction regardless of token count (for `/compact` command).
|
||||
pub async fn force_compact(&self, room_id: &RoomId, llm: &LlmClient) -> Result<()> {
|
||||
self.compact(room_id, llm).await
|
||||
}
|
||||
|
||||
/// Clear a room's history from memory and disk (archives are kept).
|
||||
pub async fn clear(&self, room_id: &RoomId) -> Result<()> {
|
||||
let mut rooms = self.rooms.lock().await;
|
||||
rooms.remove(room_id);
|
||||
|
||||
let path = self.room_file(room_id);
|
||||
if path.exists() {
|
||||
fs::remove_file(&path).await?;
|
||||
}
|
||||
let sidecar = self.room_sidecar(room_id);
|
||||
if sidecar.exists() {
|
||||
let _ = fs::remove_file(&sidecar).await;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Number of messages for a room.
|
||||
pub async fn message_count(&self, room_id: &RoomId) -> Result<usize> {
|
||||
let mut rooms = self.rooms.lock().await;
|
||||
let state = self.ensure_loaded(&mut rooms, room_id).await?;
|
||||
Ok(state.messages.len())
|
||||
}
|
||||
|
||||
// --- Private helpers ---
|
||||
|
||||
async fn compact(&self, room_id: &RoomId, llm: &LlmClient) -> Result<()> {
|
||||
let (to_summarize, to_keep) = {
|
||||
let mut rooms = self.rooms.lock().await;
|
||||
let state = self.ensure_loaded(&mut rooms, room_id).await?;
|
||||
|
||||
if state.messages.len() <= self.config.compact_retain {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let split = state.messages.len() - self.config.compact_retain;
|
||||
let to_summarize: Vec<ChatMessage> = state.messages[..split].to_vec();
|
||||
let to_keep: Vec<ChatMessage> = state.messages[split..].to_vec();
|
||||
(to_summarize, to_keep)
|
||||
};
|
||||
|
||||
if to_summarize.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
info!(
|
||||
room = %room_id,
|
||||
summarizing = to_summarize.len(),
|
||||
retaining = to_keep.len(),
|
||||
"Compacting conversation history",
|
||||
);
|
||||
|
||||
// Archive the current log file before overwriting.
|
||||
self.archive_log(room_id).await?;
|
||||
|
||||
// Summarize the old messages via the LLM.
|
||||
let summary = self.summarize(&to_summarize, llm).await?;
|
||||
|
||||
// Build new history: summary + retained messages.
|
||||
let mut new_history = Vec::with_capacity(1 + to_keep.len());
|
||||
new_history.push(ChatMessage::system(summary));
|
||||
new_history.extend(to_keep);
|
||||
|
||||
// Write the new active log.
|
||||
self.write_full_history(room_id, &new_history).await?;
|
||||
|
||||
// Update in-memory state.
|
||||
let mut rooms = self.rooms.lock().await;
|
||||
if let Some(state) = rooms.get_mut(room_id) {
|
||||
state.messages = new_history;
|
||||
state.last_prompt_tokens = None; // stale after compaction
|
||||
}
|
||||
|
||||
info!(room = %room_id, "Compaction complete");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn archive_log(&self, room_id: &RoomId) -> Result<()> {
|
||||
let src = self.room_file(room_id);
|
||||
if !src.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let epoch = SystemTime::now()
|
||||
.duration_since(SystemTime::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs();
|
||||
let hash = Self::room_hash(room_id);
|
||||
let dest = self.archive_dir.join(format!("{hash}-{epoch}.jsonl.zst"));
|
||||
|
||||
let raw = fs::read(&src)
|
||||
.await
|
||||
.context("failed to read log for archival")?;
|
||||
let compressed = tokio::task::spawn_blocking(move || zstd::encode_all(raw.as_slice(), 3))
|
||||
.await
|
||||
.context("zstd task panicked")?
|
||||
.context("zstd compression failed")?;
|
||||
|
||||
fs::write(&dest, compressed).await?;
|
||||
info!(
|
||||
room = %room_id,
|
||||
archive = %dest.display(),
|
||||
"Archived conversation log",
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn summarize(&self, messages: &[ChatMessage], llm: &LlmClient) -> Result<String> {
|
||||
let mut prompt_messages = Vec::with_capacity(messages.len() + 2);
|
||||
prompt_messages.push(ChatMessage::system(
|
||||
"You are a conversation summarizer. Summarize the following conversation \
|
||||
into a concise but comprehensive summary. Preserve key facts, decisions, \
|
||||
user preferences, and any ongoing topics. The summary will be used as \
|
||||
context for continuing the conversation. Write in third person, referring \
|
||||
to the participants as 'the user' and 'the assistant'. Be thorough but \
|
||||
concise.",
|
||||
));
|
||||
prompt_messages.extend_from_slice(messages);
|
||||
prompt_messages.push(ChatMessage::user(
|
||||
"Please summarize the above conversation.",
|
||||
));
|
||||
|
||||
let result = llm
|
||||
.chat_completion_with_tools(&prompt_messages, &[], &crate::tools::ToolExecutor::noop())
|
||||
.await
|
||||
.context("failed to generate conversation summary")?;
|
||||
|
||||
Ok(format!("[Conversation summary]\n{}", result.reply))
|
||||
}
|
||||
|
||||
async fn ensure_loaded<'a>(
|
||||
&self,
|
||||
rooms: &'a mut HashMap<OwnedRoomId, RoomState>,
|
||||
room_id: &RoomId,
|
||||
) -> Result<&'a mut RoomState> {
|
||||
if !rooms.contains_key(room_id) {
|
||||
let messages = self.load_from_disk(room_id).await?;
|
||||
rooms.insert(
|
||||
room_id.to_owned(),
|
||||
RoomState {
|
||||
messages,
|
||||
last_prompt_tokens: None,
|
||||
},
|
||||
);
|
||||
}
|
||||
Ok(rooms.get_mut(room_id).unwrap())
|
||||
}
|
||||
|
||||
fn room_hash(room_id: &RoomId) -> String {
|
||||
let hash = Sha256::digest(room_id.as_bytes());
|
||||
format!("{:x}", hash)[..16].to_owned()
|
||||
}
|
||||
|
||||
fn room_file(&self, room_id: &RoomId) -> PathBuf {
|
||||
self.dir.join(format!("{}.jsonl", Self::room_hash(room_id)))
|
||||
}
|
||||
|
||||
fn room_sidecar(&self, room_id: &RoomId) -> PathBuf {
|
||||
self.dir
|
||||
.join(format!("{}.room_id", Self::room_hash(room_id)))
|
||||
}
|
||||
|
||||
async fn load_from_disk(&self, room_id: &RoomId) -> Result<Vec<ChatMessage>> {
|
||||
let path = self.room_file(room_id);
|
||||
if !path.exists() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let content = fs::read_to_string(&path)
|
||||
.await
|
||||
.context("failed to read conversation file")?;
|
||||
|
||||
let mut messages = Vec::new();
|
||||
for (i, line) in content.lines().enumerate() {
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
match serde_json::from_str::<ChatMessage>(line) {
|
||||
Ok(msg) => messages.push(msg),
|
||||
Err(err) => {
|
||||
warn!(
|
||||
line = i + 1,
|
||||
error = %err,
|
||||
"Skipping malformed line in conversation file",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
info!(
|
||||
room = %room_id,
|
||||
count = messages.len(),
|
||||
"Loaded conversation history from disk",
|
||||
);
|
||||
Ok(messages)
|
||||
}
|
||||
|
||||
async fn append_to_disk(&self, room_id: &RoomId, message: &ChatMessage) -> Result<()> {
|
||||
let path = self.room_file(room_id);
|
||||
|
||||
// Write sidecar on first write for debuggability.
|
||||
let sidecar = self.room_sidecar(room_id);
|
||||
if !sidecar.exists() {
|
||||
let _ = fs::write(&sidecar, room_id.as_str()).await;
|
||||
}
|
||||
|
||||
let mut line = serde_json::to_string(message)?;
|
||||
line.push('\n');
|
||||
|
||||
let mut file = fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&path)
|
||||
.await
|
||||
.context("failed to open conversation file for append")?;
|
||||
|
||||
file.write_all(line.as_bytes()).await?;
|
||||
file.flush().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn write_full_history(&self, room_id: &RoomId, messages: &[ChatMessage]) -> Result<()> {
|
||||
let path = self.room_file(room_id);
|
||||
let mut content = String::new();
|
||||
for msg in messages {
|
||||
let line = serde_json::to_string(msg)?;
|
||||
content.push_str(&line);
|
||||
content.push('\n');
|
||||
}
|
||||
fs::write(&path, content).await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn test_room_id() -> OwnedRoomId {
|
||||
"!test:example.com".try_into().unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn push_and_load_persists() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let config = ConversationConfig::default();
|
||||
let room_id = test_room_id();
|
||||
|
||||
// Push messages in one store instance.
|
||||
let store = ConversationStore::new(dir.path(), config.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
store
|
||||
.push_message(&room_id, ChatMessage::user("hello"))
|
||||
.await
|
||||
.unwrap();
|
||||
store
|
||||
.push_message(&room_id, ChatMessage::assistant("hi"))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(store.message_count(&room_id).await.unwrap(), 2);
|
||||
|
||||
// New store instance should load from disk.
|
||||
let store2 = ConversationStore::new(dir.path(), config).await.unwrap();
|
||||
assert_eq!(store2.message_count(&room_id).await.unwrap(), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn clear_removes_active_log() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let config = ConversationConfig::default();
|
||||
let room_id = test_room_id();
|
||||
|
||||
let store = ConversationStore::new(dir.path(), config.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
store
|
||||
.push_message(&room_id, ChatMessage::user("hello"))
|
||||
.await
|
||||
.unwrap();
|
||||
store.clear(&room_id).await.unwrap();
|
||||
|
||||
// New store should see empty history.
|
||||
let store2 = ConversationStore::new(dir.path(), config).await.unwrap();
|
||||
assert_eq!(store2.message_count(&room_id).await.unwrap(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn prompt_tokens_tracking() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let config = ConversationConfig::default();
|
||||
let room_id = test_room_id();
|
||||
|
||||
let store = ConversationStore::new(dir.path(), config).await.unwrap();
|
||||
store
|
||||
.push_message(&room_id, ChatMessage::user("hello"))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(store.last_prompt_tokens(&room_id).await, None);
|
||||
store.set_last_prompt_tokens(&room_id, 42).await;
|
||||
assert_eq!(store.last_prompt_tokens(&room_id).await, Some(42));
|
||||
}
|
||||
}
|
||||
+86
-24
@@ -1,19 +1,17 @@
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use matrix_sdk::Room;
|
||||
use matrix_sdk::ruma::OwnedRoomId;
|
||||
use matrix_sdk::ruma::OwnedUserId;
|
||||
use matrix_sdk::ruma::events::room::message::MessageType;
|
||||
use matrix_sdk::ruma::events::room::message::OriginalSyncRoomMessageEvent;
|
||||
use matrix_sdk::ruma::events::room::message::RoomMessageEventContent;
|
||||
use serde_json::Value;
|
||||
use tokio::sync::Mutex;
|
||||
use tracing::info;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::command::Command;
|
||||
use crate::conversation::ConversationStore;
|
||||
use crate::llm::ChatMessage;
|
||||
use crate::llm::LlmClient;
|
||||
use crate::personality::Personality;
|
||||
@@ -22,7 +20,7 @@ use crate::tools::ToolExecutor;
|
||||
pub struct AppState {
|
||||
pub llm: LlmClient,
|
||||
pub trusted_users: Vec<OwnedUserId>,
|
||||
pub conversations: Mutex<HashMap<OwnedRoomId, Vec<ChatMessage>>>,
|
||||
pub conversations: Arc<ConversationStore>,
|
||||
pub personality: Personality,
|
||||
pub tool_executor: ToolExecutor,
|
||||
pub tool_defs: Vec<Value>,
|
||||
@@ -63,16 +61,47 @@ async fn handle_command(input: &str, room: &Room, state: &AppState) {
|
||||
Ok(Command::Help) => Command::help_text().to_owned(),
|
||||
|
||||
Ok(Command::Clear) => {
|
||||
let mut convos = state.conversations.lock().await;
|
||||
convos.remove(room.room_id());
|
||||
if let Err(err) = state.conversations.clear(room.room_id()).await {
|
||||
warn!(error = %err, "Failed to clear conversation");
|
||||
"Failed to clear conversation history.".to_owned()
|
||||
} else {
|
||||
"Conversation history cleared.".to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Command::Compact) => {
|
||||
match state
|
||||
.conversations
|
||||
.force_compact(room.room_id(), &state.llm)
|
||||
.await
|
||||
{
|
||||
Ok(()) => {
|
||||
let count = state
|
||||
.conversations
|
||||
.message_count(room.room_id())
|
||||
.await
|
||||
.unwrap_or(0);
|
||||
format!("Compaction complete. Messages in history: {count}")
|
||||
}
|
||||
Err(err) => {
|
||||
warn!(error = %err, "Compaction failed");
|
||||
format!("Compaction failed: {err}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Command::Context) => {
|
||||
let convos = state.conversations.lock().await;
|
||||
let count = convos.get(room.room_id()).map_or(0, |m| m.len());
|
||||
let count = state
|
||||
.conversations
|
||||
.message_count(room.room_id())
|
||||
.await
|
||||
.unwrap_or(0);
|
||||
let model = &state.llm.default_model.name;
|
||||
format!("Model: {model}\nMessages in history: {count}")
|
||||
let tokens = match state.conversations.last_prompt_tokens(room.room_id()).await {
|
||||
Some(t) => format!("{t}"),
|
||||
None => "unknown".to_owned(),
|
||||
};
|
||||
format!("Model: {model}\nMessages: {count}\nLast prompt tokens: {tokens}")
|
||||
}
|
||||
|
||||
Ok(Command::Memory) => {
|
||||
@@ -119,32 +148,65 @@ async fn handle_chat(body: &str, room: &Room, state: &AppState) {
|
||||
let system_prompt = state.personality.build_system_prompt().await;
|
||||
|
||||
// Add user message and prepare messages for the LLM.
|
||||
let messages = {
|
||||
let mut convos = state.conversations.lock().await;
|
||||
let history = convos.entry(room_id).or_default();
|
||||
history.push(ChatMessage::user(body));
|
||||
let history = match state
|
||||
.conversations
|
||||
.push_message(&room_id, ChatMessage::user(body))
|
||||
.await
|
||||
{
|
||||
Ok(h) => h,
|
||||
Err(err) => {
|
||||
warn!(error = %err, room = %room.room_id(), "Failed to persist user message");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
// Prepend system message (not stored in history).
|
||||
let mut msgs = vec![ChatMessage::system(system_prompt)];
|
||||
msgs.extend(history.clone());
|
||||
msgs
|
||||
};
|
||||
let mut messages = vec![ChatMessage::system(system_prompt)];
|
||||
messages.extend(history);
|
||||
|
||||
match state
|
||||
.llm
|
||||
.chat_completion_with_tools(&messages, &state.tool_defs, &state.tool_executor)
|
||||
.await
|
||||
{
|
||||
Ok((reply, intermediate_messages)) => {
|
||||
{
|
||||
let mut convos = state.conversations.lock().await;
|
||||
if let Some(history) = convos.get_mut(room.room_id()) {
|
||||
Ok(result) => {
|
||||
// Store tool call round trips so the LLM has context on next turn.
|
||||
history.extend(intermediate_messages);
|
||||
history.push(ChatMessage::assistant(&reply));
|
||||
for msg in &result.intermediate_messages {
|
||||
if let Err(err) = state
|
||||
.conversations
|
||||
.push_message(&room_id, msg.clone())
|
||||
.await
|
||||
{
|
||||
warn!(error = %err, "Failed to persist intermediate message");
|
||||
}
|
||||
}
|
||||
send_reply(room, &reply).await;
|
||||
|
||||
if let Err(err) = state
|
||||
.conversations
|
||||
.push_message(&room_id, ChatMessage::assistant(&result.reply))
|
||||
.await
|
||||
{
|
||||
warn!(error = %err, "Failed to persist assistant message");
|
||||
}
|
||||
|
||||
// Track prompt tokens and check if compaction is needed.
|
||||
if let Some(tokens) = result.prompt_tokens {
|
||||
state
|
||||
.conversations
|
||||
.set_last_prompt_tokens(&room_id, tokens)
|
||||
.await;
|
||||
if let Err(err) = state
|
||||
.conversations
|
||||
.maybe_compact(&room_id, tokens, &state.llm)
|
||||
.await
|
||||
{
|
||||
warn!(error = %err, room = %room.room_id(), "Compaction failed");
|
||||
}
|
||||
}
|
||||
|
||||
if !result.reply.is_empty() {
|
||||
send_reply(room, &result.reply).await;
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
warn!(error = %err, room = %room.room_id(), "LLM chat completion failed");
|
||||
|
||||
+34
-8
@@ -101,6 +101,12 @@ struct ChatCompletionRequest {
|
||||
#[derive(Deserialize)]
|
||||
struct ChatCompletionResponse {
|
||||
choices: Vec<Choice>,
|
||||
usage: Option<Usage>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Usage {
|
||||
prompt_tokens: usize,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -114,6 +120,16 @@ struct ResponseMessage {
|
||||
tool_calls: Option<Vec<ToolCall>>,
|
||||
}
|
||||
|
||||
/// Result of a chat completion with tool calling.
|
||||
pub struct CompletionResult {
|
||||
/// The final assistant reply text.
|
||||
pub reply: String,
|
||||
/// Intermediate messages (tool calls + tool results) generated during the loop.
|
||||
pub intermediate_messages: Vec<ChatMessage>,
|
||||
/// Prompt token count from the final API response (if provided).
|
||||
pub prompt_tokens: Option<usize>,
|
||||
}
|
||||
|
||||
// -- Implementation --
|
||||
|
||||
/// Maximum number of tool-call round trips before we bail.
|
||||
@@ -167,14 +183,15 @@ impl LlmClient {
|
||||
|
||||
/// Send a chat completion request and handle tool calls in a loop.
|
||||
///
|
||||
/// Returns the final assistant reply text and any intermediate messages
|
||||
/// (tool calls + tool results) that were generated during the loop.
|
||||
/// Returns the final assistant reply text, any intermediate messages
|
||||
/// (tool calls + tool results), and the prompt token count from the
|
||||
/// final response (if the API provided it).
|
||||
pub async fn chat_completion_with_tools(
|
||||
&self,
|
||||
messages: &[ChatMessage],
|
||||
tools: &[Value],
|
||||
tool_executor: &ToolExecutor,
|
||||
) -> Result<(String, Vec<ChatMessage>)> {
|
||||
) -> Result<CompletionResult> {
|
||||
let mut all_messages = messages.to_vec();
|
||||
let tools_param = if tools.is_empty() {
|
||||
None
|
||||
@@ -183,7 +200,8 @@ impl LlmClient {
|
||||
};
|
||||
|
||||
for _ in 0..MAX_TOOL_ITERATIONS {
|
||||
let response = self.send_completion(&all_messages, &tools_param).await?;
|
||||
let (response, prompt_tokens) =
|
||||
self.send_completion(&all_messages, &tools_param).await?;
|
||||
|
||||
if let Some(tool_calls) = &response.tool_calls
|
||||
&& !tool_calls.is_empty()
|
||||
@@ -213,7 +231,11 @@ impl LlmClient {
|
||||
// No tool calls — this is the final response.
|
||||
let reply = response.content.unwrap_or_default();
|
||||
let new_messages = all_messages[messages.len()..].to_vec();
|
||||
return Ok((reply, new_messages));
|
||||
return Ok(CompletionResult {
|
||||
reply,
|
||||
intermediate_messages: new_messages,
|
||||
prompt_tokens,
|
||||
});
|
||||
}
|
||||
|
||||
anyhow::bail!("Tool calling loop exceeded {MAX_TOOL_ITERATIONS} iterations")
|
||||
@@ -223,7 +245,7 @@ impl LlmClient {
|
||||
&self,
|
||||
messages: &[ChatMessage],
|
||||
tools: &Option<Vec<Value>>,
|
||||
) -> Result<ResponseMessage> {
|
||||
) -> Result<(ResponseMessage, Option<usize>)> {
|
||||
let url = format!(
|
||||
"{}/chat/completions",
|
||||
self.default_model.base_url.trim_end_matches('/')
|
||||
@@ -255,10 +277,14 @@ impl LlmClient {
|
||||
.await
|
||||
.context("Failed to parse chat completion response")?;
|
||||
|
||||
body.choices
|
||||
let prompt_tokens = body.usage.map(|u| u.prompt_tokens);
|
||||
let message = body
|
||||
.choices
|
||||
.into_iter()
|
||||
.next()
|
||||
.map(|c| c.message)
|
||||
.context("Chat completion returned no choices")
|
||||
.context("Chat completion returned no choices")?;
|
||||
|
||||
Ok((message, prompt_tokens))
|
||||
}
|
||||
}
|
||||
+9
-1
@@ -6,6 +6,7 @@ use tracing_subscriber::EnvFilter;
|
||||
|
||||
mod command;
|
||||
mod config;
|
||||
mod conversation;
|
||||
mod handler;
|
||||
mod llm;
|
||||
mod matrix;
|
||||
@@ -35,5 +36,12 @@ async fn main() -> Result<()> {
|
||||
let config_contents = std::fs::read_to_string(&cli.config)?;
|
||||
let config: config::Config = toml::from_str(&config_contents)?;
|
||||
|
||||
matrix::run(config.state_dir, config.matrix, config.llm, config.memory).await
|
||||
matrix::run(
|
||||
config.state_dir,
|
||||
config.matrix,
|
||||
config.llm,
|
||||
config.memory,
|
||||
config.conversation,
|
||||
)
|
||||
.await
|
||||
}
|
||||
+8
-3
@@ -1,4 +1,3 @@
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
@@ -22,13 +21,14 @@ use serde::Serialize;
|
||||
use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
use tokio::fs;
|
||||
use tokio::sync::Mutex;
|
||||
use tracing::info;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::config::ConversationConfig;
|
||||
use crate::config::LlmConfig;
|
||||
use crate::config::MatrixConfig;
|
||||
use crate::config::MemoryConfig;
|
||||
use crate::conversation::ConversationStore;
|
||||
use crate::handler;
|
||||
use crate::handler::AppState;
|
||||
use crate::llm::LlmClient;
|
||||
@@ -50,6 +50,7 @@ pub async fn run(
|
||||
config: MatrixConfig,
|
||||
llm_config: LlmConfig,
|
||||
memory_config: MemoryConfig,
|
||||
conv_config: ConversationConfig,
|
||||
) -> Result<()> {
|
||||
let memory_path = state_dir.join("memory");
|
||||
let matrix_path = state_dir.join("matrix");
|
||||
@@ -101,10 +102,14 @@ pub async fn run(
|
||||
"Personality system initialized",
|
||||
);
|
||||
|
||||
let conversation_store = ConversationStore::new(&state_dir, conv_config)
|
||||
.await
|
||||
.context("failed to initialize conversation store")?;
|
||||
|
||||
let app_state = Arc::new(AppState {
|
||||
llm: llm_client,
|
||||
trusted_users: config.trusted_users.clone(),
|
||||
conversations: Mutex::new(HashMap::new()),
|
||||
conversations: Arc::new(conversation_store),
|
||||
personality,
|
||||
tool_executor,
|
||||
tool_defs,
|
||||
|
||||
@@ -21,6 +21,14 @@ impl ToolExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
/// A no-op executor for internal LLM calls that don't need tools.
|
||||
pub fn noop() -> Self {
|
||||
Self {
|
||||
memory_path: PathBuf::new(),
|
||||
write_enabled: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn execute(&self, name: &str, args: &Value) -> Result<String> {
|
||||
match name {
|
||||
"memory_read" => self.memory_read(args).await,
|
||||
|
||||
Reference in new issue
Block a user