2026-07-16 12:32:17 +07:00
|
|
|
|
//! In-memory conversation state: message history plus the system prompt and
|
|
|
|
|
|
//! model parameters used to drive the LLM.
|
2026-07-19 17:05:27 +07:00
|
|
|
|
//!
|
|
|
|
|
|
//! # Flow
|
|
|
|
|
|
//!
|
|
|
|
|
|
//! [`Conversation::new`] → [`push`](Conversation::push) to add messages →
|
|
|
|
|
|
//! [`to_api_messages`](Conversation::to_api_messages) to format for the LLM
|
|
|
|
|
|
//! API (system prompt prepended). Persisted via [`save_conversation`](Conversation::save_conversation)
|
|
|
|
|
|
//! and loaded via [`load_conversation`](Conversation::load_conversation).
|
|
|
|
|
|
//! The system prompt can be hot-swapped via [`rebuild_system`](Conversation::rebuild_system).
|
|
|
|
|
|
//!
|
|
|
|
|
|
//! # Components
|
|
|
|
|
|
//!
|
|
|
|
|
|
//! - `Conversation` — message vector + session metadata + generation params
|
|
|
|
|
|
//! - `push` / `rebuild_system` — mutation helpers
|
|
|
|
|
|
//! - `to_api_messages` — formats messages for API consumption
|
|
|
|
|
|
//! - `save_conversation` / `load_conversation` — filesystem persistence
|
2026-07-16 12:32:17 +07:00
|
|
|
|
use serde::{Deserialize, Serialize};
|
2026-07-19 17:05:27 +07:00
|
|
|
|
use tracing;
|
2026-07-16 12:32:17 +07:00
|
|
|
|
|
|
|
|
|
|
use super::message::{ChatMessage, Role};
|
|
|
|
|
|
|
|
|
|
|
|
/// A single conversation's message history and generation settings.
|
|
|
|
|
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
|
|
|
|
pub struct Conversation {
|
2026-07-19 17:05:27 +07:00
|
|
|
|
/// Ordered list of chat messages (user, assistant, tool, system).
|
2026-07-16 12:32:17 +07:00
|
|
|
|
pub messages: Vec<ChatMessage>,
|
2026-07-19 17:05:27 +07:00
|
|
|
|
/// System prompt prepended at request time (see `to_api_messages`).
|
2026-07-16 12:32:17 +07:00
|
|
|
|
pub system_prompt: String,
|
2026-07-19 17:05:27 +07:00
|
|
|
|
/// Foreign key referencing the owning session.
|
2026-07-16 12:32:17 +07:00
|
|
|
|
pub session_id: String,
|
2026-07-19 17:05:27 +07:00
|
|
|
|
/// Model identifier string, e.g. `"anthropic/claude-opus-4-8"`.
|
2026-07-16 12:32:17 +07:00
|
|
|
|
pub model: String,
|
2026-07-19 17:05:27 +07:00
|
|
|
|
/// Optional cap on output tokens.
|
2026-07-16 12:32:17 +07:00
|
|
|
|
pub max_tokens: Option<u32>,
|
2026-07-19 17:05:27 +07:00
|
|
|
|
/// Optional temperature (0.0 – 2.0).
|
2026-07-16 12:32:17 +07:00
|
|
|
|
pub temperature: Option<f32>,
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
impl Conversation {
|
|
|
|
|
|
/// Create an empty conversation with the given system prompt and
|
|
|
|
|
|
/// session id, using default model/token/temperature settings.
|
|
|
|
|
|
pub fn new(system_prompt: String, session_id: String) -> Self {
|
|
|
|
|
|
Conversation {
|
|
|
|
|
|
messages: Vec::new(),
|
|
|
|
|
|
system_prompt,
|
|
|
|
|
|
session_id,
|
|
|
|
|
|
model: "anthropic/claude-opus-4-8".to_string(),
|
|
|
|
|
|
max_tokens: None,
|
|
|
|
|
|
temperature: None,
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// Append a message to the conversation history.
|
|
|
|
|
|
pub fn push(&mut self, msg: ChatMessage) {
|
|
|
|
|
|
self.messages.push(msg);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// Replace the system prompt and strip any prior `System`-role
|
|
|
|
|
|
/// messages from history.
|
|
|
|
|
|
///
|
|
|
|
|
|
/// Why: the system prompt is re-injected fresh at request time via
|
|
|
|
|
|
/// `to_api_messages`, so stale `System` messages in `self.messages`
|
|
|
|
|
|
/// would be redundant/conflicting if left in place.
|
|
|
|
|
|
pub fn rebuild_system(&mut self, new_prompt: String) {
|
|
|
|
|
|
self.system_prompt = new_prompt;
|
|
|
|
|
|
self.messages.retain(|m| !matches!(m.role, Role::System));
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// Build the message list to send to the LLM API, with the system
|
|
|
|
|
|
/// prompt prepended.
|
|
|
|
|
|
///
|
|
|
|
|
|
/// Return: a new `Vec` (clone of history) with a synthesized system
|
|
|
|
|
|
/// message at index 0.
|
|
|
|
|
|
pub fn to_api_messages(&self) -> Vec<ChatMessage> {
|
|
|
|
|
|
let mut msgs = Vec::with_capacity(self.messages.len() + 1);
|
|
|
|
|
|
msgs.push(ChatMessage::system(&self.system_prompt));
|
|
|
|
|
|
msgs.extend(self.messages.iter().cloned());
|
|
|
|
|
|
msgs
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// Number of messages in the conversation history (excluding the
|
|
|
|
|
|
/// synthesized system message).
|
|
|
|
|
|
pub fn len(&self) -> usize {
|
|
|
|
|
|
self.messages.len()
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// Returns `true` if the conversation has no messages.
|
|
|
|
|
|
pub fn is_empty(&self) -> bool {
|
|
|
|
|
|
self.messages.is_empty()
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// Persist the conversation to a JSON file at the given base directory.
|
|
|
|
|
|
///
|
|
|
|
|
|
/// Flow: compute path from `session_id` → ensure directory exists →
|
2026-07-18 02:37:03 +07:00
|
|
|
|
/// atomically write pretty-printed JSON via `write_json_atomic`.
|
2026-07-16 12:32:17 +07:00
|
|
|
|
///
|
2026-07-18 02:37:03 +07:00
|
|
|
|
/// Return: `Ok(())` on success, or an `anyhow::Error` from any step.
|
|
|
|
|
|
pub fn save_conversation(&self, base_dir: &std::path::Path) -> anyhow::Result<()> {
|
2026-07-16 12:32:17 +07:00
|
|
|
|
let dir = base_dir.join("sessions").join(&self.session_id);
|
|
|
|
|
|
std::fs::create_dir_all(&dir)?;
|
|
|
|
|
|
let path = dir.join("conversation.json");
|
2026-07-19 17:05:27 +07:00
|
|
|
|
tracing::debug!(session_id = %self.session_id, path = %path.display(), "saving conversation");
|
2026-07-18 02:37:03 +07:00
|
|
|
|
zesdex_utils::write_json_atomic(&path, self, None)?;
|
2026-07-16 12:32:17 +07:00
|
|
|
|
Ok(())
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// Load a conversation from a JSON file for the given session id.
|
|
|
|
|
|
///
|
|
|
|
|
|
/// Flow: read `<base_dir>/sessions/<session_id>/conversation.json` →
|
|
|
|
|
|
/// JSON-parse.
|
|
|
|
|
|
///
|
|
|
|
|
|
/// Return: the parsed `Conversation`, or an `io::Error` if the file is
|
|
|
|
|
|
/// missing or malformed.
|
|
|
|
|
|
pub fn load_conversation(
|
|
|
|
|
|
session_id: &str,
|
|
|
|
|
|
base_dir: &std::path::Path,
|
|
|
|
|
|
) -> std::io::Result<Self> {
|
|
|
|
|
|
let path = base_dir
|
|
|
|
|
|
.join("sessions")
|
|
|
|
|
|
.join(session_id)
|
|
|
|
|
|
.join("conversation.json");
|
2026-07-19 17:05:27 +07:00
|
|
|
|
tracing::debug!(session_id = %session_id, path = %path.display(), "loading conversation");
|
|
|
|
|
|
let data = std::fs::read_to_string(&path)?;
|
2026-07-16 12:32:17 +07:00
|
|
|
|
let conv: Conversation = serde_json::from_str(&data)?;
|
|
|
|
|
|
Ok(conv)
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|