print history each time when running

This commit is contained in:
b1ek 2024-10-22 14:13:40 +10:00
parent bab5cdaf2e
commit a432cddf79
Signed by: blek
GPG Key ID: A622C22C9BC616B2
3 changed files with 56 additions and 4 deletions

View File

@ -155,9 +155,10 @@ pub async fn get_res<'a>(cli: &Client, query: String, vqd: String, config: &Conf
}
}
}
println!("\n");
if let Some(err) = error {
eprintln!("Error while writing to session: {err:#?}");
eprintln!("Session may be broken.");
}
println!("\n");
}

View File

@ -42,6 +42,13 @@ async fn main() {
let args = Args::parse();
let query = args.query.join(" ").trim().to_string();
{
let session = Session::create_or_restore("");
if session.is_restored() {
session.print_history();
}
}
if query.len() == 0 {
exit(0);
}

View File

@ -7,13 +7,17 @@ use chrono::{DateTime, Local};
use serde::{Deserialize, Serialize};
use crate::api::{ChatChunk, ChatMessagePayload};
use crate::{BLUE, GRAY, GREEN, RESET};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Session {
session_id: String,
ttl: DateTime<Local>,
messages: Vec<ChatMessagePayload>,
vqd: String
vqd: String,
#[serde(skip)]
restored: bool
}
impl Session {
@ -68,6 +72,7 @@ impl Session {
match inner(Self::path_for_id(id)) {
Ok(mut session) => {
session.restored = true;
if session.is_expired() {
session.destroy().expect("Couldn't destroy expired session");
None
@ -94,11 +99,16 @@ impl Session {
session_id: id.into(),
ttl: Self::get_ttl(),
messages: vec![],
vqd: vqd.into()
vqd: vqd.into(),
restored: false
}
}
fn save(&self) -> Result<(), Box<dyn std::error::Error>> {
if self.messages.len() == 0 {
return Ok(());
}
fs::write(self.path(), serde_json::to_string_pretty(self)?)?;
Ok(())
}
@ -107,6 +117,40 @@ impl Session {
self.ttl < Local::now()
}
pub fn is_restored(&self) -> bool {
self.restored
}
pub fn print_history(&self) {
println!("{GRAY}* start restored conversation *{RESET}");
println!();
for message in self.messages.iter() {
let user = &message.role;
let msg = &message.content;
let role_color = {
if user == "user" { GREEN }
else if user == "assistant" { BLUE }
else { GRAY }
};
let short_user = {
if user == "user" { "you" }
else if user == "assistant" { "ai" }
else { user }
}.to_string();
println!("{role_color}{short_user}{RESET}\t: {msg}{RESET}");
if user == "assistant" {
println!();
}
}
println!("{GRAY}* end restored conversation *{RESET}");
}
pub fn destroy(&self) -> Result<(), Box<dyn std::error::Error>> {
Ok(fs::remove_file(self.path())?)
}
@ -114,7 +158,7 @@ impl Session {
pub fn create_or_restore<T: Into<String>>(vqd: T) -> Self {
let session_id: String = Self::terminal_session_id();
match Self::restore_with_id(&session_id) {
Some(session) => session,
Some(session) => { session },
None => {
let session = Self::new(&session_id, vqd);
session.save().expect("Couldn't save new session");