117 lines
4.0 KiB
Rust
117 lines
4.0 KiB
Rust
#![allow(
|
|||
|
|
clippy::cast_possible_truncation,
|
||
|
|
clippy::cast_sign_loss,
|
||
|
|
clippy::cast_precision_loss,
|
||
|
|
clippy::cast_possible_wrap
|
||
|
|
)]
|
||
|
|
//! In-memory conversation state: message history plus the system prompt and
|
||
|
|
//! model parameters used to drive the LLM.
|
||
|
|
use serde::{Deserialize, Serialize};
|
||
|
|
|
||
|
|
use super::message::{ChatMessage, Role};
|
||
|
|
|
||
|
|
/// A single conversation's message history and generation settings.
|
||
|
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||
|
|
pub struct Conversation {
|
||
|
|
pub messages: Vec<ChatMessage>,
|
||
|
|
pub system_prompt: String,
|
||
|
|
pub session_id: String,
|
||
|
|
pub model: String,
|
||
|
|
pub max_tokens: Option<u32>,
|
||
|
|
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 →
|
||
|
|
/// serialize to pretty JSON → write-then-rename with fsync.
|
||
|
|
///
|
||
|
|
/// Return: `Ok(())` on success, or an `io::Error` from any step.
|
||
|
|
pub fn save_conversation(&self, base_dir: &std::path::Path) -> std::io::Result<()> {
|
||
|
|
let dir = base_dir.join("sessions").join(&self.session_id);
|
||
|
|
std::fs::create_dir_all(&dir)?;
|
||
|
|
let path = dir.join("conversation.json");
|
||
|
|
let data = serde_json::to_string_pretty(self)?;
|
||
|
|
let tmp = dir.join("conversation.json.tmp");
|
||
|
|
std::fs::write(&tmp, data)?;
|
||
|
|
let f = std::fs::File::open(&tmp)?;
|
||
|
|
f.sync_all()?;
|
||
|
|
std::fs::rename(&tmp, path)?;
|
||
|
|
let _ = std::fs::File::open(&dir).and_then(|d| d.sync_all());
|
||
|
|
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");
|
||
|
|
let data = std::fs::read_to_string(path)?;
|
||
|
|
let conv: Conversation = serde_json::from_str(&data)?;
|
||
|
|
Ok(conv)
|
||
|
|
}
|
||
|
|
}
|