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
//!
//! # OpenAI's API endpoints
//!
//! Note that for Audios and Images, an extended endpoint variant will be
//! needed.

////////////////////////////////////////////////////////////////////////////////

use std::fmt::Display;

use log::{debug, error, warn};
use reqwest::multipart::Form;
use serde::Serialize;

use super::types::model::Model;
use crate::utils::{config::Config, header::AdditionalHeaders};

/// Check if selected model is available to certain API endpoint
///
/// # Arguments
/// - `model` - A provided model enum variant
/// - `endpoint` - API endpoint name, e.g. `/v1/completions`
pub fn endpoint_filter(model: &Model, endpoint: &Endpoint) -> bool {
    match endpoint {
        Endpoint::ChatCompletion_v1 => [
            Model::GPT_3_5_TURBO,
            Model::GPT_3_5_TURBO_0301,
            Model::GPT_4,
            Model::GPT_4_0314,
            Model::GPT_4_32K,
            Model::GPT_4_32K_0314,
        ]
        .contains(&model),
        Endpoint::Completion_v1 => [
            Model::TEXT_DAVINCI_003,
            Model::TEXT_DAVINCI_002,
            Model::TEXT_CURIE_001,
            Model::TEXT_BABBAGE_001,
            Model::TEXT_ADA_001,
            Model::DAVINCI,
            Model::CURIE,
            Model::BABBAGE,
            Model::ADA,
        ]
        .contains(&model),
        Endpoint::Edit_v1 => {
            [Model::TEXT_DAVINCI_EDIT_001, Model::CODE_DAVINCI_EDIT_001].contains(&model)
        }
        Endpoint::Audio_v1 => [Model::WHISPER_1].contains(&model),
        Endpoint::FineTune_v1 => {
            [Model::DAVINCI, Model::CURIE, Model::BABBAGE, Model::ADA].contains(&model)
        }
        Endpoint::Embedding_v1 => [
            Model::TEXT_EMBEDDING_ADA_002,
            Model::TEXT_SEARCH_ADA_DOC_001,
        ]
        .contains(&model),
        Endpoint::Moderation_v1 => [
            Model::TEXT_MODERATION_LATEST,
            Model::TEXT_MODERATION_STABLE,
            Model::TEXT_MODERATION_004,
        ]
        .contains(&model),
        _ => false,
    }
}

/// Enum for endpoints that have several variants.
pub enum EndpointVariant {
    /// No sub variants.
    None,
    /// Denotes a variant of some endpoint.
    Extended(String),
}

impl From<String> for EndpointVariant {
    fn from(value: String) -> Self {
        Self::Extended(value)
    }
}

/// API endpoint definition enum
#[allow(non_camel_case_types)]
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Endpoint {
    ChatCompletion_v1,
    Completion_v1,
    Edit_v1,
    Image_v1,
    Audio_v1,
    FineTune_v1,
    Embedding_v1,
    Moderation_v1,
}

impl Display for Endpoint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", <Self as Into<&str>>::into(self.clone()))
    }
}

impl Into<&'static str> for Endpoint {
    fn into(self) -> &'static str {
        match self {
            Self::Audio_v1 => "/v1/audio",
            Self::ChatCompletion_v1 => "/v1/chat/completions",
            Self::Completion_v1 => "/v1/completions",
            Self::Edit_v1 => "/v1/edits",
            Self::Image_v1 => "/v1/images",
            Self::Embedding_v1 => "/v1/embeddings",
            Self::FineTune_v1 => "/v1/fine-tunes",
            Self::Moderation_v1 => "/v1/moderations",
        }
    }
}

/// Endpoint variants for Images
#[allow(non_camel_case_types)]
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum ImageEndpointVariant {
    Generation,
    Editing,
    Variation,
}

impl Into<String> for ImageEndpointVariant {
    fn into(self) -> String {
        String::from(match self {
            Self::Editing => "/edits",
            Self::Variation => "/variations",
            Self::Generation => "/generations",
        })
    }
}

/// Endpoint variants for Audios
#[allow(non_camel_case_types)]
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum AudioEndpointVariant {
    Transcription,
    Translation,
}

impl Into<String> for AudioEndpointVariant {
    fn into(self) -> String {
        String::from(match self {
            Self::Transcription => "/transcriptions",
            Self::Translation => "/translations",
        })
    }
}

/// Send request to remote endpoint using JSON.
///  
/// # Arguments
/// - `json` - the serialized contents to send
/// - `endpoint` - Endpoint enum variant
/// - `variant` - Endpoint variant enum
/// - `cb` - callback function that will be called when message received.
pub async fn request_endpoint<'a, T, F>(
    json: &'a T,
    endpoint: &'a Endpoint,
    variant: EndpointVariant,
    mut cb: F,
) -> Result<(), Box<dyn std::error::Error>>
where
    T: Serialize,
    F: FnMut(Result<String, Box<dyn std::error::Error>>),
{
    let client = reqwest::Client::new();
    let config = Config::load().unwrap();
    let url = if let EndpointVariant::Extended(var) = variant {
        format!(
            "{}{}{}",
            config.openai.base_endpoint(),
            endpoint,
            var.to_owned()
        )
    } else {
        format!("{}{}", config.openai.base_endpoint(), endpoint)
    };

    let mut req = client.post(url);

    // Load additional headers from environment variable
    let headers = AdditionalHeaders::from_var().provide();
    if headers.len() > 0 {
        req = req.headers(headers);
    }

    req = req.header("Authorization", format!("Bearer {}", config.openai.api_key));
    if config.openai.org_id.is_some() {
        req = req.header("OpenAI-Organization", config.openai.org_id.clone().unwrap());
    }

    if let Some(req_clone) = req.try_clone() {
        log::debug!(target: "requests", "Headers `{:?}`", req_clone.build().unwrap().headers());
    };

    let res = req.json(&json).send().await?;

    if let Ok(text) = res.text().await {
        debug!(target: "openai", "Received response from OpenAI: `{:?}`", text);
        cb(Ok(text.clone()));
    } else {
        error!(target: "openai", "Error receiving response from OpenAI");
        cb(Err("Error receiving response from OpenAI".into()))
    }

    Ok(())
}

/// Send request to remote endpoint using JSON but response will be streamed.
///  
/// # Arguments
/// - `json` - the serialized contents to send
/// - `endpoint` - Endpoint enum variant
/// - `variant` - Endpoint variant enum
/// - `cb` - callback function that will be called when message received. Note
/// the differences of the function parameters.
pub async fn request_endpoint_stream<'a, T>(
    json: &'a T,
    endpoint: &'a Endpoint,
    variant: EndpointVariant,
    mut cb: impl FnMut(Result<String, Box<dyn std::error::Error>>),
) -> Result<(), Box<dyn std::error::Error>>
where
    T: Serialize,
{
    let client = reqwest::Client::new();
    let config = Config::load().unwrap();
    let url = if let EndpointVariant::Extended(var) = variant {
        format!(
            "{}{}{}",
            config.openai.base_endpoint(),
            endpoint,
            var.to_owned()
        )
    } else {
        format!("{}{}", config.openai.base_endpoint(), endpoint)
    };

    let mut req = client.post(url);

    // Load additional headers from environment variable
    let headers = AdditionalHeaders::from_var().provide();
    if headers.len() > 0 {
        req = req.headers(headers);
    }

    req = req.header("Authorization", format!("Bearer {}", config.openai.api_key));
    if config.openai.org_id.is_some() {
        req = req.header("OpenAI-Organization", config.openai.org_id.clone().unwrap());
    }

    if let Some(req_clone) = req.try_clone() {
        log::debug!(target: "requests", "Headers `{:?}`", req_clone.build().unwrap().headers());
    };

    let mut res = req.json(&json).send().await?;

    while let Some(chunk) = res.chunk().await? {
        if let Ok(chunk_data_raw) = String::from_utf8(chunk.to_vec()) {
            debug!(target: "openai", "Received response chunk from OpenAI: `{:?}`", chunk_data_raw);
            cb(Ok(chunk_data_raw));
        } else {
            warn!(target: "openai", "Response chunk empty");
        }
    }

    Ok(())
}

/// Send request to remote endpoint using Form data.
///  
/// # Arguments
/// - `form` - the constructed HTTP form to send
/// - `endpoint` - Endpoint enum variant
/// - `variant` - Endpoint variant enum
/// - `cb` - callback function that will be called when message received.
pub async fn request_endpoint_form_data<'a, F>(
    form: Form,
    endpoint: &'a Endpoint,
    variant: EndpointVariant,
    mut cb: F,
) -> Result<(), Box<dyn std::error::Error>>
where
    F: FnMut(Result<String, Box<dyn std::error::Error>>),
{
    let client = reqwest::Client::new();
    let config = Config::load().unwrap();
    let url = if let EndpointVariant::Extended(var) = variant {
        format!(
            "{}{}{}",
            config.openai.base_endpoint(),
            endpoint,
            var.to_owned()
        )
    } else {
        format!("{}{}", config.openai.base_endpoint(), endpoint)
    };

    let mut req = client.post(url);

    // Load additional headers from environment variable
    let headers = AdditionalHeaders::from_var().provide();
    if headers.len() > 0 {
        req = req.headers(headers);
    }

    req = req.header("Authorization", format!("Bearer {}", config.openai.api_key));

    if let Some(req_clone) = req.try_clone() {
        log::debug!(target: "requests", "Headers `{:?}`", req_clone.build().unwrap().headers());
    };

    let res = req.multipart(form).send().await?;

    if let Ok(text) = res.text().await {
        debug!(target: "openai", "Received response from OpenAI: `{:?}`", text);
        cb(Ok(text.clone()));
    } else {
        error!(target: "openai", "Error receiving response from OpenAI");
        cb(Err("Error receiving response from OpenAI".into()))
    }

    Ok(())
}