/
chatgpt.rs
134 lines (127 loc) · 4.21 KB
/
chatgpt.rs
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
use clap::Parser;
use rustyline;
#[derive(Debug, Parser)]
#[command(version)]
struct Options {
#[arg(short, long, default_value = "gpt-3.5-turbo")]
model: String,
#[arg(short, long, default_value = None)]
temperature: Option<f64>,
#[arg(short, long)]
no_stream: bool,
#[arg(short, long, default_value = None)]
user: Option<String>,
args: Option<Vec<String>>,
}
fn request(
api_key: &str,
model: String,
temperature: Option<f64>,
stream: Option<bool>,
user: Option<String>,
messages: Vec<simple_chatgpt::Message>,
) -> String {
let request_body = simple_chatgpt::RequestBody {
model,
messages,
temperature,
stream,
user,
};
let contents = std::rc::Rc::new(std::cell::RefCell::new(String::new()));
let future = simple_chatgpt::completions(&api_key, &request_body, |cr, completion| match cr {
simple_chatgpt::CallbackReason::Start => {
// nothing to do
}
simple_chatgpt::CallbackReason::Data => {
let stdout = std::io::stdout();
let mut handle = stdout.lock();
let content = completion.unwrap().choices[0]
.delta
.content
.clone()
.unwrap();
let bytes = content.as_bytes();
std::io::Write::write_all(&mut handle, bytes).unwrap();
std::io::Write::flush(&mut handle).unwrap();
contents.borrow_mut().push_str(&content);
}
simple_chatgpt::CallbackReason::End => {
// nothing to do
}
simple_chatgpt::CallbackReason::Done => {
println!();
}
simple_chatgpt::CallbackReason::Error(line) => {
eprintln!("Error: {}", line);
}
});
let result = futures::executor::block_on(future);
if result.is_err() {
eprintln!("Error: {:?}", result.err().unwrap());
std::process::exit(1);
}
std::rc::Rc::try_unwrap(contents).unwrap().into_inner()
}
fn main() {
let options = Options::parse();
let api_key = std::env::var("OPENAI_API_KEY").expect("OPENAI_API_KEY is not defined");
let mut messages = Vec::new();
if let Some(args) = options.args {
messages.push(simple_chatgpt::Message {
role: Some(String::from("user")),
content: Some(args.join(" ")),
});
let reply = request(
&api_key,
options.model.clone(),
options.temperature.clone(),
if options.no_stream { None } else { Some(true) },
options.user.clone(),
messages.clone(),
);
messages.push(simple_chatgpt::Message {
role: Some(String::from("system")),
content: Some(reply),
});
}
let home = std::env::var("HOME").expect("HOME is not defined");
let history_file = format!("{}{}.chatgpt_history", home, std::path::MAIN_SEPARATOR);
let mut rl = rustyline::DefaultEditor::new().unwrap();
let _ = rl.load_history(&history_file);
loop {
let readline = rl.readline(">> ");
match readline {
Ok(line) => {
let _ = rl.add_history_entry(line.clone());
messages.push(simple_chatgpt::Message {
role: Some(String::from("user")),
content: Some(line),
});
let reply = request(
&api_key,
options.model.clone(),
options.temperature.clone(),
if options.no_stream { None } else { Some(true) },
options.user.clone(),
messages.clone(),
);
messages.push(simple_chatgpt::Message {
role: Some(String::from("system")),
content: Some(reply),
});
}
Err(rustyline::error::ReadlineError::Interrupted) => {
break;
}
Err(rustyline::error::ReadlineError::Eof) => {
break;
}
Err(err) => {
eprintln!("Error: {:?}", err);
break;
}
}
}
rl.save_history(&history_file).unwrap();
}