From 444f4ebe9de8aa68afdf8d39b734a8543b9b5c4b Mon Sep 17 00:00:00 2001 From: sigoden Date: Thu, 2 Nov 2023 09:53:54 +0800 Subject: refactor: improve code quanity (#196) - rewrite Repl, remove ReplHandler - move ReplyStreamHandler to repl/ and rename it to ReplyHandler - deprecate utils::print_now - refactor session info --- src/config/mod.rs | 62 ++++++++++++++++++++++++++++++--------- src/config/model_info.rs | 2 +- src/config/role.rs | 2 +- src/config/session.rs | 75 +++++++++++++++++++++++++----------------------- 4 files changed, 90 insertions(+), 51 deletions(-) (limited to 'src/config') diff --git a/src/config/mod.rs b/src/config/mod.rs index ea45897..731cc10 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -12,7 +12,7 @@ use crate::client::{ all_models, create_client_config, list_client_types, ClientConfig, ExtraConfig, OpenAIClient, SendData, }; -use crate::render::RenderOptions; +use crate::render::{MarkdownRender, RenderOptions}; use crate::utils::{get_env_name, light_theme_from_colorfgbg, now, prompt_op_err}; use anyhow::{anyhow, bail, Context, Result}; @@ -336,7 +336,7 @@ impl Config { } } - pub fn info(&self) -> Result { + pub fn sys_info(&self) -> Result { let path_info = |path: &Path| { let state = if path.exists() { "" } else { " ⚠️" }; format!("{}{state}", path.display()) @@ -349,27 +349,63 @@ impl Config { .clone() .map_or_else(|| String::from("no"), |v| v.to_string()); let items = vec![ - ("config_file", path_info(&Self::config_file()?)), - ("roles_file", path_info(&Self::roles_file()?)), - ("messages_file", path_info(&Self::messages_file()?)), - ("sessions_dir", path_info(&Self::sessions_dir()?)), ("model", self.model_info.full_name()), ("temperature", temperature), + ("dry_run", self.dry_run.to_string()), ("save", self.save.to_string()), ("highlight", self.highlight.to_string()), - ("light_theme", self.light_theme.to_string()), ("wrap", wrap), ("wrap_code", self.wrap_code.to_string()), - ("dry_run", self.dry_run.to_string()), + ("light_theme", self.light_theme.to_string()), ("keybindings", self.keybindings.stringify().into()), + ("config_file", path_info(&Self::config_file()?)), + ("roles_file", path_info(&Self::roles_file()?)), + ("messages_file", path_info(&Self::messages_file()?)), + ("sessions_dir", path_info(&Self::sessions_dir()?)), ]; - let mut output = String::new(); - for (name, value) in items { - output.push_str(&format!("{name:<20}{value}\n")); - } + let output = items + .iter() + .map(|(name, value)| format!("{name:<20}{value}")) + .collect::>() + .join("\n"); Ok(output) } + pub fn role_info(&self) -> Result { + if let Some(role) = &self.role { + role.info() + } else { + bail!("No role") + } + } + + pub fn session_info(&self) -> Result { + if let Some(session) = &self.session { + let render_options = self.get_render_options()?; + let mut markdown_render = MarkdownRender::init(render_options)?; + session.render(&mut markdown_render) + } else { + bail!("No session") + } + } + + pub fn info(&self) -> Result { + if let Some(session) = &self.session { + session.export() + } else if let Some(role) = &self.role { + role.info() + } else { + self.sys_info() + } + } + + pub fn last_reply(&self) -> &str { + self.last_message + .as_ref() + .map(|(_, reply)| reply.as_str()) + .unwrap_or_default() + } + pub fn repl_completions(&self) -> Vec { let mut completion: Vec = self .roles @@ -423,7 +459,7 @@ impl Config { Ok(()) } - pub fn start_session(&mut self, session: &Option) -> Result<()> { + pub fn start_session(&mut self, session: Option<&str>) -> Result<()> { if self.session.is_some() { bail!("Already in a session, please use '.clear session' to exit the session first?"); } diff --git a/src/config/model_info.rs b/src/config/model_info.rs index 793c014..7a52e63 100644 --- a/src/config/model_info.rs +++ b/src/config/model_info.rs @@ -1,4 +1,4 @@ -use super::Message; +use super::message::Message; use crate::utils::count_tokens; diff --git a/src/config/role.rs b/src/config/role.rs index 16a6400..819cc12 100644 --- a/src/config/role.rs +++ b/src/config/role.rs @@ -19,7 +19,7 @@ impl Role { pub fn info(&self) -> Result { let output = serde_yaml::to_string(&self) .with_context(|| format!("Unable to show info about role {}", &self.name))?; - Ok(output) + Ok(output.trim_end().to_string()) } pub fn embedded(&self) -> bool { diff --git a/src/config/session.rs b/src/config/session.rs index 62c1b09..7ed5714 100644 --- a/src/config/session.rs +++ b/src/config/session.rs @@ -82,12 +82,12 @@ impl Session { if let Some(temperature) = self.temperature() { data["temperature"] = temperature.into(); } - data["total-tokens"] = tokens.into(); + data["total_tokens"] = tokens.into(); if let Some(max_tokens) = self.model_info.max_tokens { - data["max-tokens"] = max_tokens.into(); + data["max_tokens"] = max_tokens.into(); } if percent != 0.0 { - data["total/max-tokens"] = format!("{}%", percent).into(); + data["total/max"] = format!("{}%", percent).into(); } data["messages"] = json!(self.messages); @@ -97,43 +97,46 @@ impl Session { } pub fn render(&self, render: &mut MarkdownRender) -> Result { - let path = self.path.clone().unwrap_or_else(|| "-".to_string()); - - let temperature = self - .temperature() - .map_or_else(|| String::from("-"), |v| v.to_string()); - - let max_tokens = self - .model_info - .max_tokens - .map(|v| v.to_string()) - .unwrap_or_else(|| '-'.to_string()); - - let items = vec![ - ("path", path), - ("model", self.model().to_string()), - ("temperature", temperature), - ("max_tokens", max_tokens), - ]; - let mut lines = vec![]; - for (name, value) in items { - lines.push(format!("{name:<20}{value}")); + let mut items = vec![]; + + if let Some(path) = &self.path { + items.push(("path", path.to_string())); } - lines.push("".into()); - for message in &self.messages { - match message.role { - MessageRole::System => { - continue; - } - MessageRole::Assistant => { - lines.push(render.render(&message.content)); - lines.push("".into()); - } - MessageRole::User => { - lines.push(format!("{}){}", self.name, message.content)); + + items.push(("model", self.model_info.full_name())); + + if let Some(temperature) = self.temperature() { + items.push(("temperature", temperature.to_string())); + } + + if let Some(max_tokens) = self.model_info.max_tokens { + items.push(("max_tokens", max_tokens.to_string())); + } + + let mut lines: Vec = items + .iter() + .map(|(name, value)| format!("{name:<20}{value}")) + .collect(); + + if !self.is_empty() { + lines.push("".into()); + + for message in &self.messages { + match message.role { + MessageRole::System => { + continue; + } + MessageRole::Assistant => { + lines.push(render.render(&message.content)); + lines.push("".into()); + } + MessageRole::User => { + lines.push(format!("{}){}", self.name, message.content)); + } } } } + let output = lines.join("\n"); Ok(output) } -- cgit v1.2.3