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
use crate::models::{Model, Role, LogitBias};
use log::debug;
use reqwest::{Client, StatusCode};
use serde::{Deserialize, Serialize};
use std::fmt;
pub struct ChatGPTClient {
base_url: String,
api_key: String,
client: Client,
}
#[derive(Debug, Serialize)]
pub struct ChatInput {
pub model: Model,
pub messages: Vec<Message>,
#[serde(skip_serializing_if = "Option::is_none")]
pub temperature: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub top_p: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub n: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub stream: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub stop: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_tokens: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub presence_penalty: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub frequency_penalty: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub logit_bias: Option<LogitBias>,
#[serde(skip_serializing_if = "Option::is_none")]
pub user: Option<String>,
}
impl Default for ChatInput {
fn default() -> Self {
Self {
model: Model::Gpt_4, messages: Vec::new(), temperature: None,
top_p: None,
n: None,
stream: None,
stop: None,
max_tokens: None,
presence_penalty: None,
frequency_penalty: None,
logit_bias: None,
user: None,
}
}
}
#[derive(Debug, Deserialize)]
pub struct ChatResponse {
pub id: String,
pub object: String,
pub created: i64,
pub model: String,
pub usage: Usage,
pub choices: Vec<Choice>,
}
#[derive(Debug, Deserialize)]
pub struct Usage {
pub prompt_tokens: i64,
pub completion_tokens: i64,
pub total_tokens: i64,
}
#[derive(Debug, Deserialize)]
pub struct Choice {
pub message: Message,
pub finish_reason: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct Message {
pub role: Role,
pub content: String,
}
#[derive(Debug)]
pub enum ChatGPTError {
RequestFailed(String),
Reqwest(reqwest::Error),
}
impl fmt::Display for ChatGPTError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ChatGPTError::RequestFailed(message) => write!(f, "{}", message),
ChatGPTError::Reqwest(error) => write!(f, "Reqwest error: {}", error),
}
}
}
impl std::error::Error for ChatGPTError {}
impl From<reqwest::Error> for ChatGPTError {
fn from(error: reqwest::Error) -> Self {
ChatGPTError::Reqwest(error)
}
}
impl ChatGPTClient {
pub fn new(api_key: &str, base_url: &str) -> Self {
env_logger::init();
Self {
base_url: base_url.to_string(),
api_key: api_key.to_string(),
client: Client::new(),
}
}
pub async fn chat(&self, input: ChatInput) -> Result<ChatResponse, ChatGPTError> {
let url = format!("{}/v1/chat/completions", self.base_url);
let response = self
.client
.post(&url)
.header("Authorization", format!("Bearer {}", self.api_key))
.json(&input)
.send()
.await?;
debug!(
"API call to url: {}\n with json payload: {:?}",
&url, &input
);
if response.status() == StatusCode::OK {
response
.json::<ChatResponse>()
.await
.map_err(ChatGPTError::from)
} else {
let status_code = response.status();
let headers = response.headers().clone();
let body = response.text().await?;
let error_message = format!(
"Request failed with status code: {}\nHeaders: {:?}\nBody: {}",
status_code, headers, body
);
Err(ChatGPTError::RequestFailed(error_message))
}
}
}