1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
|
mod conversation;
use self::conversation::Session;
use crate::utils::{emphasis, now};
use anyhow::{anyhow, bail, Context, Result};
use inquire::{Confirm, Text};
use parking_lot::Mutex;
use serde::Deserialize;
use serde_json::{json, Value};
use std::{
env,
fs::{create_dir_all, read_to_string, File, OpenOptions},
io::Write,
path::{Path, PathBuf},
process::exit,
sync::Arc,
};
const CONFIG_FILE_NAME: &str = "config.yaml";
const ROLES_FILE_NAME: &str = "roles.yaml";
const HISTORY_FILE_NAME: &str = "history.txt";
const MESSAGE_FILE_NAME: &str = "messages.md";
const TEMP_ROLE_NAME: &str = "%PROMPT%";
const SET_COMPLETIONS: [&str; 9] = [
".set api_key",
".set temperature",
".set save true",
".set save false",
".set highlight true",
".set highlight false",
".set proxy",
".set dry_run true",
".set dry_run false",
];
#[derive(Debug, Clone, Deserialize)]
pub struct Config {
/// Openai api key
pub api_key: String,
/// What sampling temperature to use, between 0 and 2
pub temperature: Option<f64>,
/// Whether to persistently save chat messages
#[serde(default)]
pub save: bool,
/// Whether to disable highlight
#[serde(default = "highlight_value")]
pub highlight: bool,
/// Set proxy
pub proxy: Option<String>,
/// Used only for debugging
#[serde(default)]
pub dry_run: bool,
/// Predefined roles
#[serde(default, skip)]
pub roles: Vec<Role>,
/// Current selected role
#[serde(default, skip)]
pub role: Option<Role>,
/// Current conversation
#[serde(default, skip)]
pub conversation: Option<Session>,
}
pub type SharedConfig = Arc<Mutex<Config>>;
impl Config {
pub fn init(is_interactive: bool) -> Result<Config> {
let config_path = Config::config_file()?;
if is_interactive && !config_path.exists() {
create_config_file(&config_path)?;
}
let content = read_to_string(&config_path)
.with_context(|| format!("Failed to load config at {}", config_path.display()))?;
let mut config: Config = serde_yaml::from_str(&content)
.with_context(|| format!("Invalid config at {}", config_path.display()))?;
config.load_roles()?;
Ok(config)
}
pub fn find_role(&self, name: &str) -> Option<Role> {
self.roles.iter().find(|v| v.name == name).cloned()
}
pub fn config_dir() -> Result<PathBuf> {
let env_name = format!(
"{}_CONFIG_DIR",
env!("CARGO_CRATE_NAME").to_ascii_uppercase()
);
let path = match env::var(env_name) {
Ok(v) => PathBuf::from(v),
Err(_) => {
let mut dir = dirs::config_dir().ok_or_else(|| anyhow!("Not found config dir"))?;
dir.push(env!("CARGO_CRATE_NAME"));
dir
}
};
if !path.exists() {
create_dir_all(&path).map_err(|err| {
anyhow!("Failed to create config dir at {}, {err}", path.display())
})?;
}
Ok(path)
}
pub fn local_file(name: &str) -> Result<PathBuf> {
let mut path = Self::config_dir()?;
path.push(name);
Ok(path)
}
pub fn save_message(&self, input: &str, output: &str) -> Result<()> {
if !self.save {
return Ok(());
}
let mut file = self.open_message_file()?;
if output.is_empty() || !self.save {
return Ok(());
}
let timestamp = now();
let output = match self.role.as_ref() {
None => {
format!("# CHAT:[{timestamp}]\n{input}\n--------\n{output}\n--------\n\n",)
}
Some(v) => {
if v.name == TEMP_ROLE_NAME {
format!(
"# CHAT:[{timestamp}]\n{}\n{input}\n--------\n{output}\n--------\n\n",
v.prompt
)
} else {
format!(
"# CHAT:[{timestamp}] ({})\n{input}\n--------\n{output}\n--------\n\n",
v.name,
)
}
}
};
file.write_all(output.as_bytes())
.with_context(|| "Failed to save message")
}
pub fn config_file() -> Result<PathBuf> {
Self::local_file(CONFIG_FILE_NAME)
}
pub fn roles_file() -> Result<PathBuf> {
Self::local_file(ROLES_FILE_NAME)
}
pub fn history_file() -> Result<PathBuf> {
Self::local_file(HISTORY_FILE_NAME)
}
pub fn messages_file() -> Result<PathBuf> {
Self::local_file(MESSAGE_FILE_NAME)
}
pub fn change_role(&mut self, name: &str) -> Result<String> {
self.ensure_no_conversation()?;
if self.conversation.is_some() {
bail!("")
}
match self.find_role(name) {
Some(role) => {
let temperature = match role.temperature {
Some(v) => format!("{v}"),
None => "null".into(),
};
let output = format!(
"{}: {}\n{}: {}\n{}: {}",
emphasis("name"),
role.name,
emphasis("prompt"),
role.prompt.trim(),
emphasis("temperature"),
temperature
);
self.role = Some(role);
Ok(output)
}
None => bail!("Error: Unknown role"),
}
}
pub fn create_temp_role(&mut self, prompt: &str) -> Result<()> {
self.ensure_no_conversation()?;
self.role = Some(Role {
name: TEMP_ROLE_NAME.into(),
prompt: prompt.into(),
temperature: self.temperature,
});
Ok(())
}
pub fn get_temperature(&self) -> Option<f64> {
self.role
.as_ref()
.and_then(|v| v.temperature)
.or(self.temperature)
}
pub fn echo_messages(&self, content: &str) -> String {
if let Some(conversation) = self.conversation.as_ref() {
conversation.echo_messages(content)
} else if let Some(role) = self.role.as_ref() {
format!("{}\n{content}", role.prompt.trim())
} else {
content.to_string()
}
}
pub fn build_messages(&self, content: &str) -> Value {
let user_message = json!({ "role": "user", "content": content });
if let Some(conversation) = self.conversation.as_ref() {
conversation.build_emssages(content)
} else if let Some(role) = self.role.as_ref() {
let system_message = json!({ "role": "system", "content": role.prompt.trim() });
json!([system_message, user_message])
} else {
json!([user_message])
}
}
pub fn info(&self) -> Result<String> {
let file_info = |path: &Path| {
let state = if path.exists() { "" } else { " ⚠️" };
format!("{}{state}", path.display())
};
let proxy = self
.proxy
.as_ref()
.map(|v| v.to_string())
.unwrap_or("-".into());
let temperature = self
.temperature
.map(|v| v.to_string())
.unwrap_or("-".into());
let role_name = self
.role
.as_ref()
.map(|v| v.name.to_string())
.unwrap_or("-".into());
let items = vec![
("config_file", file_info(&Config::config_file()?)),
("roles_file", file_info(&Config::roles_file()?)),
("messages_file", file_info(&Config::messages_file()?)),
("role", role_name),
("api_key", self.api_key.clone()),
("temperature", temperature),
("save", self.save.to_string()),
("highlight", self.highlight.to_string()),
("proxy", proxy),
("dry_run", self.dry_run.to_string()),
];
let mut output = String::new();
for (name, value) in items {
output.push_str(&format!("{name:<20}{value}\n"));
}
Ok(output)
}
pub fn repl_completions(&self) -> Vec<String> {
let mut completion: Vec<String> = self
.roles
.iter()
.map(|v| format!(".role {}", v.name))
.collect();
completion.extend(SET_COMPLETIONS.map(|v| v.to_string()));
completion
}
pub fn update(&mut self, data: &str) -> Result<()> {
let parts: Vec<&str> = data.split_whitespace().collect();
if parts.len() != 2 {
bail!("Usage: .set <key> <value>. If value is null, unset key.");
}
let key = parts[0];
let value = parts[1];
let unset = value == "null";
match key {
"api_key" => {
if unset {
bail!("Error: Not allowed");
} else {
self.api_key = value.to_string();
}
}
"temperature" => {
if unset {
self.temperature = None;
} else {
let value = value.parse().with_context(|| "Invalid value")?;
self.temperature = Some(value);
}
}
"save" => {
let value = value.parse().with_context(|| "Invalid value")?;
self.save = value;
}
"highlight" => {
let value = value.parse().with_context(|| "Invalid value")?;
self.highlight = value;
}
"proxy" => {
if unset {
self.proxy = None;
} else {
self.proxy = Some(value.to_string());
}
}
"dry_run" => {
let value = value.parse().with_context(|| "Invalid value")?;
self.dry_run = value;
}
_ => bail!("Error: Unknown key `{key}`"),
}
Ok(())
}
pub fn start_conversation(&mut self) -> Result<()> {
if self.conversation.is_some() {
let ans = Confirm::new("Already in a conversation, start a new one?")
.with_default(true)
.prompt()?;
if !ans {
return Ok(());
}
}
let mut conversation = Session::new();
if let Some(role) = self.role.as_ref() {
conversation.add_prompt(&role.prompt);
}
self.conversation = Some(conversation);
Ok(())
}
pub fn end_conversation(&mut self) {
self.conversation = None;
}
pub fn record_conversation(&mut self, input: &str, output: &str) -> Result<()> {
if let Some(conversation) = self.conversation.as_mut() {
conversation.add_conversatoin(input, output)?;
}
Ok(())
}
fn open_message_file(&self) -> Result<File> {
let path = Config::messages_file()?;
OpenOptions::new()
.create(true)
.append(true)
.open(&path)
.with_context(|| format!("Failed to create/append {}", path.display()))
}
fn ensure_no_conversation(&self) -> Result<()> {
if self.conversation.is_some() {
bail!("Error: Cannot perform this action in a conversation");
}
Ok(())
}
fn load_roles(&mut self) -> Result<()> {
let path = Self::roles_file()?;
if !path.exists() {
return Ok(());
}
let content = read_to_string(&path)
.with_context(|| format!("Failed to load roles at {}", path.display()))?;
let roles: Vec<Role> =
serde_yaml::from_str(&content).with_context(|| "Invalid roles config")?;
self.roles = roles;
Ok(())
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct Role {
/// Role name
pub name: String,
/// Prompt text send to ai for setting up a role
pub prompt: String,
/// What sampling temperature to use, between 0 and 2
pub temperature: Option<f64>,
}
fn create_config_file(config_path: &Path) -> Result<()> {
let confirm_map_err = |_| anyhow!("Error with questionnaire, try again later");
let text_map_err = |_| anyhow!("An error happened when asking for your key, try again later.");
let ans = Confirm::new("No config file, create a new one?")
.with_default(true)
.prompt()
.map_err(confirm_map_err)?;
if !ans {
exit(0);
}
let api_key = Text::new("Openai API Key:")
.prompt()
.map_err(text_map_err)?;
let mut raw_config = format!("api_key: {api_key}\n");
let ans = Confirm::new("Use proxy?")
.with_default(false)
.prompt()
.map_err(confirm_map_err)?;
if ans {
let proxy = Text::new("Set proxy:").prompt().map_err(text_map_err)?;
raw_config.push_str(&format!("proxy: {proxy}\n"));
}
let ans = Confirm::new("Save chat messages")
.with_default(false)
.prompt()
.map_err(confirm_map_err)?;
if ans {
raw_config.push_str("save: true\n");
}
std::fs::write(config_path, raw_config).with_context(|| "Failed to write to config file")?;
Ok(())
}
fn highlight_value() -> bool {
true
}
|