RustGLM/async_invoke_method/async_invoke/
history_message.rs

1use serde_json::json;
2use std::fs::{self, File};
3use std::io::{BufRead, BufReader};
4use std::path::{Path, PathBuf};
5
6const HISTORY_FILE: &str = "chatglm_history.json";
7
8pub struct HistoryMessage {
9    history_file_path: PathBuf,
10}
11
12impl HistoryMessage {
13    pub fn new() -> Self {
14        let history_file_path = PathBuf::from(HISTORY_FILE);
15        Self::create_history_file_if_not_exists(&history_file_path);
16
17        HistoryMessage { history_file_path }
18    }
19
20    fn create_history_file_if_not_exists(file_path: &Path) {
21        if !file_path.exists() {
22            if let Err(err) = File::create(file_path) {
23                eprintln!("Failed to create history file: {}", err);
24            }
25        }
26    }
27
28    pub fn add_history_to_file(&self, role: &str, content: &str) -> String {
29        let json = json!({
30            "role": role,
31            "content": content,
32        });
33
34        if let Err(err) = fs::write(&self.history_file_path, format!("{},\n", json)) {
35            eprintln!("Failed to write to history file: {}", err);
36        }
37
38        json.to_string()
39    }
40
41    pub fn load_history_from_file(&self) -> String {
42        if let Ok(file) = File::open(&self.history_file_path) {
43            let reader = BufReader::new(file);
44            reader.lines().filter_map(Result::ok).collect::<String>()
45        } else {
46            eprintln!("Failed to open history file for reading");
47            String::new()
48        }
49    }
50}