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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
|
mod message;
mod role;
mod session;
use self::message::Message;
use self::role::Role;
use self::session::{Session, TEMP_SESSION_NAME};
use crate::client::openai::{OpenAIClient, OpenAIConfig};
use crate::client::{all_clients, create_client_config, list_models, ClientConfig, ModelInfo};
use crate::config::message::num_tokens_from_messages;
use crate::render::RenderOptions;
use crate::utils::{get_env_name, light_theme_from_colorfgbg, now};
use anyhow::{anyhow, bail, Context, Result};
use inquire::{Confirm, Select, Text};
use parking_lot::RwLock;
use serde::Deserialize;
use std::{
env,
fs::{create_dir_all, read_dir, read_to_string, remove_file, 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 MESSAGES_FILE_NAME: &str = "messages.md";
const SESSIONS_DIR_NAME: &str = "sessions";
const SET_COMPLETIONS: [&str; 7] = [
".set temperature",
".set save true",
".set save false",
".set highlight true",
".set highlight false",
".set dry_run true",
".set dry_run false",
];
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct Config {
/// LLM model
pub model: Option<String>,
/// What sampling temperature to use, between 0 and 2
#[serde(rename(serialize = "temperature", deserialize = "temperature"))]
pub default_temperature: Option<f64>,
/// Whether to persistently save non-session chat messages
pub save: bool,
/// Whether to disable highlight
pub highlight: bool,
/// Used only for debugging
pub dry_run: bool,
/// If set true, use light theme
pub light_theme: bool,
/// Specify the text-wrapping mode (no*, auto, <max-width>)
pub wrap: Option<String>,
/// Whethter wrap code block
pub wrap_code: bool,
/// Automatically copy the last output to the clipboard
pub auto_copy: bool,
/// REPL keybindings, possible values: emacs (default), vi
pub keybindings: Keybindings,
/// Setup AIs
pub clients: Vec<ClientConfig>,
/// Predefined roles
#[serde(skip)]
pub roles: Vec<Role>,
/// Current selected role
#[serde(skip)]
pub role: Option<Role>,
/// Current session
#[serde(skip)]
pub session: Option<Session>,
#[serde(skip)]
pub model_info: ModelInfo,
#[serde(skip)]
pub last_message: Option<(String, String)>,
#[serde(skip)]
pub temperature: Option<f64>,
}
impl Default for Config {
fn default() -> Self {
Self {
model: None,
default_temperature: None,
save: false,
highlight: true,
dry_run: false,
light_theme: false,
wrap: None,
wrap_code: false,
auto_copy: false,
keybindings: Default::default(),
clients: vec![ClientConfig::OpenAI(OpenAIConfig::default())],
roles: vec![],
role: None,
session: None,
model_info: Default::default(),
last_message: None,
temperature: None,
}
}
}
pub type SharedConfig = Arc<RwLock<Config>>;
impl Config {
pub fn init(is_interactive: bool) -> Result<Self> {
let config_path = Self::config_file()?;
let api_key = env::var("OPENAI_API_KEY").ok();
let exist_config_path = config_path.exists();
if is_interactive && api_key.is_none() && !exist_config_path {
create_config_file(&config_path)?;
}
let mut config = if api_key.is_some() && !exist_config_path {
Self::default()
} else {
Self::load_config(&config_path)?
};
// Compatible with old configuration files
if exist_config_path {
config.compat_old_config(&config_path)?;
}
if let Some(name) = config.model.clone() {
config.set_model(&name)?;
}
if let Some(wrap) = config.wrap.clone() {
config.set_wrap(&wrap)?;
}
config.temperature = config.default_temperature;
config.merge_env_vars();
config.load_roles()?;
config.ensure_sessions_dir()?;
config.check_term_theme()?;
Ok(config)
}
pub fn get_role(&self, name: &str) -> Option<Role> {
self.roles.iter().find(|v| v.match_name(name)).map(|v| {
let mut role = v.clone();
role.complete_prompt_args(name);
role
})
}
pub fn config_dir() -> Result<PathBuf> {
let env_name = get_env_name("config_dir");
let path = if let Some(v) = env::var_os(env_name) {
PathBuf::from(v)
} else {
let mut dir = dirs::config_dir().ok_or_else(|| anyhow!("Not found config dir"))?;
dir.push(env!("CARGO_CRATE_NAME"));
dir
};
Ok(path)
}
pub fn local_path(name: &str) -> Result<PathBuf> {
let mut path = Self::config_dir()?;
path.push(name);
Ok(path)
}
pub fn save_message(&mut self, input: &str, output: &str) -> Result<()> {
self.last_message = Some((input.to_string(), output.to_string()));
if self.dry_run {
return Ok(());
}
if let Some(session) = self.session.as_mut() {
session.add_message(input, output)?;
return Ok(());
}
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) => {
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_path(CONFIG_FILE_NAME)
}
pub fn roles_file() -> Result<PathBuf> {
let env_name = get_env_name("roles_file");
env::var(env_name).map_or_else(
|_| Self::local_path(ROLES_FILE_NAME),
|value| Ok(PathBuf::from(value)),
)
}
pub fn history_file() -> Result<PathBuf> {
Self::local_path(HISTORY_FILE_NAME)
}
pub fn messages_file() -> Result<PathBuf> {
Self::local_path(MESSAGES_FILE_NAME)
}
pub fn sessions_dir() -> Result<PathBuf> {
Self::local_path(SESSIONS_DIR_NAME)
}
pub fn session_file(name: &str) -> Result<PathBuf> {
let mut path = Self::sessions_dir()?;
path.push(&format!("{name}.yaml"));
Ok(path)
}
pub fn set_role(&mut self, name: &str) -> Result<String> {
match self.get_role(name) {
Some(role) => {
if let Some(session) = self.session.as_mut() {
session.update_role(Some(role.clone()))?;
}
let output = serde_yaml::to_string(&role)
.unwrap_or_else(|_| "Unable to echo role details".into());
self.temperature = role.temperature;
self.role = Some(role);
Ok(output)
}
None => bail!("Unknown role `{name}`"),
}
}
pub fn clear_role(&mut self) -> Result<()> {
if let Some(session) = self.session.as_mut() {
session.update_role(None)?;
}
self.temperature = self.default_temperature;
self.role = None;
Ok(())
}
pub fn get_temperature(&self) -> Option<f64> {
self.temperature
}
pub fn set_temperature(&mut self, value: Option<f64>) -> Result<()> {
self.temperature = value;
if let Some(session) = self.session.as_mut() {
session.temperature = value;
}
Ok(())
}
pub fn echo_messages(&self, content: &str) -> String {
if let Some(session) = self.session.as_ref() {
session.echo_messages(content)
} else if let Some(role) = self.role.as_ref() {
role.echo_messages(content)
} else {
content.to_string()
}
}
pub fn build_messages(&self, content: &str) -> Result<Vec<Message>> {
let messages = if let Some(session) = self.session.as_ref() {
session.build_emssages(content)
} else if let Some(role) = self.role.as_ref() {
role.build_messages(content)
} else {
let message = Message::new(content);
vec![message]
};
let tokens = num_tokens_from_messages(&messages);
if tokens >= self.model_info.max_tokens {
bail!("Exceed max tokens limit")
}
Ok(messages)
}
pub fn set_wrap(&mut self, value: &str) -> Result<()> {
if value == "no" {
self.wrap = None;
} else if value == "auto" {
self.wrap = Some(value.into());
} else {
value
.parse::<u16>()
.map_err(|_| anyhow!("Invalid wrap value"))?;
self.wrap = Some(value.into())
}
Ok(())
}
pub fn set_model(&mut self, value: &str) -> Result<()> {
let models = list_models(self);
let mut model_info = None;
if value.contains(':') {
if let Some(model) = models.iter().find(|v| v.stringify() == value) {
model_info = Some(model.clone());
}
} else if let Some(model) = models.iter().find(|v| v.client == value) {
model_info = Some(model.clone());
}
match model_info {
None => bail!("Invalid model"),
Some(model_info) => {
if let Some(session) = self.session.as_mut() {
session.set_model(&model_info.stringify())?;
}
self.model_info = model_info;
Ok(())
}
}
}
pub const fn get_reamind_tokens(&self) -> usize {
let mut tokens = self.model_info.max_tokens;
if let Some(session) = self.session.as_ref() {
tokens = tokens.saturating_sub(session.tokens);
}
tokens
}
pub fn info(&self) -> Result<String> {
let path_info = |path: &Path| {
let state = if path.exists() { "" } else { " ⚠️" };
format!("{}{state}", path.display())
};
let temperature = self
.temperature
.map_or_else(|| String::from("-"), |v| v.to_string());
let wrap = self
.wrap
.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.stringify()),
("temperature", temperature),
("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()),
("keybindings", self.keybindings.stringify().into()),
];
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(std::string::ToString::to_string));
completion.extend(
list_models(self)
.iter()
.map(|v| format!(".model {}", v.stringify())),
);
completion.extend(
list_models(self)
.iter()
.map(|v| format!(".model {}", v.stringify())),
);
let sessions = self.list_sessions().unwrap_or_default();
completion.extend(sessions.iter().map(|v| format!(".session {}", v)));
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 {
"temperature" => {
let value = if unset {
None
} else {
let value = value.parse().with_context(|| "Invalid value")?;
Some(value)
};
self.set_temperature(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;
}
"dry_run" => {
let value = value.parse().with_context(|| "Invalid value")?;
self.dry_run = value;
}
_ => bail!("Unknown key `{key}`"),
}
Ok(())
}
pub fn start_session(&mut self, session: &Option<String>) -> Result<()> {
if self.session.is_some() {
bail!("Already in a session, please use '.clear session' to exit the session first?");
}
match session {
None => {
let session_file = Self::session_file(TEMP_SESSION_NAME)?;
if session_file.exists() {
remove_file(session_file)
.with_context(|| "Failed to clean previous session")?;
}
self.session = Some(Session::new(
TEMP_SESSION_NAME,
&self.model_info.stringify(),
self.role.clone(),
));
}
Some(name) => {
let session_path = Self::session_file(name)?;
if !session_path.exists() {
self.session = Some(Session::new(
name,
&self.model_info.stringify(),
self.role.clone(),
));
} else {
let session = Session::load(name, &session_path)?;
let model = session.model.clone();
self.temperature = session.temperature;
self.session = Some(session);
self.set_model(&model)?;
}
}
}
if let Some(session) = self.session.as_mut() {
if session.is_empty() {
if let Some((input, output)) = &self.last_message {
let ans = Confirm::new(
"Start a session that incorporates the last question and answer?",
)
.with_default(false)
.prompt()?;
if ans {
session.add_message(input, output)?;
}
}
}
}
Ok(())
}
pub fn end_session(&mut self) -> Result<()> {
if let Some(mut session) = self.session.take() {
self.last_message = None;
self.temperature = self.default_temperature;
if session.should_save() {
let ans = Confirm::new("Save session?").with_default(true).prompt()?;
if !ans {
return Ok(());
}
let mut name = session.name.clone();
if session.is_temp() {
name = Text::new("Session name:").with_default(&name).prompt()?;
}
let session_path = Self::session_file(&name)?;
session.save(&session_path)?;
}
}
Ok(())
}
pub fn list_sessions(&self) -> Result<Vec<String>> {
let sessions_dir = Self::sessions_dir()?;
match read_dir(&sessions_dir) {
Ok(rd) => {
let mut names = vec![];
for entry in rd {
let entry = entry?;
let name = entry.file_name();
if let Some(name) = name.to_string_lossy().strip_suffix(".yaml") {
names.push(name.to_string());
}
}
Ok(names)
}
Err(_) => Ok(vec![]),
}
}
pub fn get_render_options(&self) -> RenderOptions {
RenderOptions::new(
self.highlight,
self.light_theme,
self.wrap.clone(),
self.wrap_code,
)
}
pub fn maybe_print_send_tokens(&self, input: &str) {
if self.dry_run {
if let Ok(messages) = self.build_messages(input) {
let tokens = num_tokens_from_messages(&messages);
println!(">>> This message consumes {tokens} tokens. <<<");
}
}
}
fn open_message_file(&self) -> Result<File> {
let path = Self::messages_file()?;
ensure_parent_exists(&path)?;
OpenOptions::new()
.create(true)
.append(true)
.open(&path)
.with_context(|| format!("Failed to create/append {}", path.display()))
}
fn load_config(config_path: &Path) -> Result<Self> {
let content = read_to_string(config_path)
.with_context(|| format!("Failed to load config at {}", config_path.display()))?;
let config: Self = serde_yaml::from_str(&content)
.with_context(|| format!("Invalid config at {}", config_path.display()))?;
Ok(config)
}
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(())
}
fn merge_env_vars(&mut self) {
if let Ok(value) = env::var("NO_COLOR") {
let mut no_color = false;
set_bool(&mut no_color, &value);
if no_color {
self.highlight = false;
}
}
}
fn ensure_sessions_dir(&self) -> Result<()> {
let sessions_dir = Self::sessions_dir()?;
if !sessions_dir.exists() {
create_dir_all(&sessions_dir).with_context(|| {
format!("Failed to create session_dir '{}'", sessions_dir.display())
})?;
}
Ok(())
}
fn check_term_theme(&mut self) -> Result<()> {
if self.light_theme {
return Ok(());
}
if let Ok(value) = env::var(get_env_name("light_theme")) {
set_bool(&mut self.light_theme, &value);
return Ok(());
} else if let Ok(value) = env::var("COLORFGBG") {
if let Some(light) = light_theme_from_colorfgbg(&value) {
self.light_theme = light
}
};
Ok(())
}
fn compat_old_config(&mut self, config_path: &PathBuf) -> Result<()> {
let content = read_to_string(config_path)?;
let value: serde_json::Value = serde_yaml::from_str(&content)?;
if value.get("clients").is_some() {
return Ok(());
}
if let Some(model_name) = value.get("model").and_then(|v| v.as_str()) {
if model_name.starts_with("gpt") {
self.model = Some(format!("{}:{}", OpenAIClient::name(), model_name));
}
}
if let Some(ClientConfig::OpenAI(client_config)) = self.clients.get_mut(0) {
if let Some(api_key) = value.get("api_key").and_then(|v| v.as_str()) {
client_config.api_key = Some(api_key.to_string())
}
if let Some(organization_id) = value.get("organization_id").and_then(|v| v.as_str()) {
client_config.organization_id = Some(organization_id.to_string())
}
if let Some(proxy) = value.get("proxy").and_then(|v| v.as_str()) {
client_config.proxy = Some(proxy.to_string())
}
if let Some(connect_timeout) = value.get("connect_timeout").and_then(|v| v.as_i64()) {
client_config.connect_timeout = Some(connect_timeout as _)
}
}
Ok(())
}
}
#[derive(Debug, Clone, Deserialize, Default)]
pub enum Keybindings {
#[serde(rename = "emacs")]
#[default]
Emacs,
#[serde(rename = "vi")]
Vi,
}
impl Keybindings {
pub fn is_vi(&self) -> bool {
matches!(self, Keybindings::Vi)
}
pub fn stringify(&self) -> &str {
match self {
Keybindings::Emacs => "emacs",
Keybindings::Vi => "vi",
}
}
}
fn create_config_file(config_path: &Path) -> Result<()> {
let ans = Confirm::new("No config file, create a new one?")
.with_default(true)
.prompt()
.map_err(|_| anyhow!("Not finish questionnaire, try again later."))?;
if !ans {
exit(0);
}
let client = Select::new("Select AI?", all_clients())
.prompt()
.map_err(|_| anyhow!("An error happened when selecting platform, try again later."))?;
let mut raw_config = create_client_config(client)?;
raw_config.push_str(&format!("model: {client}\n"));
let ans = Confirm::new("Save chat messages")
.with_default(true)
.prompt()
.map_err(|_| anyhow!("Not finish questionnaire, try again later."))?;
if ans {
raw_config.push_str("save: true\n");
}
ensure_parent_exists(config_path)?;
std::fs::write(config_path, raw_config).with_context(|| "Failed to write to config file")?;
#[cfg(unix)]
{
use std::os::unix::prelude::PermissionsExt;
let perms = std::fs::Permissions::from_mode(0o600);
std::fs::set_permissions(config_path, perms)?;
}
Ok(())
}
fn ensure_parent_exists(path: &Path) -> Result<()> {
if path.exists() {
return Ok(());
}
let parent = path
.parent()
.ok_or_else(|| anyhow!("Failed to write to {}, No parent path", path.display()))?;
if !parent.exists() {
create_dir_all(parent).with_context(|| {
format!(
"Failed to write {}, Cannot create parent directory",
path.display()
)
})?;
}
Ok(())
}
fn set_bool(target: &mut bool, value: &str) {
match value {
"1" | "true" => *target = true,
"0" | "false" => *target = false,
_ => {}
}
}
|