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
//! OpenAI integration for [Flows.network](https://flows.network)
//!
//! # Quick Start
//!
//! To get started, let's write a very tiny flow function.
//!
//! ```rust
//! use openai_flows::{CompletionRequest, create_completion};
//! use slack_flows::{listen_to_channel, send_message_to_channel};
//!
//! #[no_mangle]
//! pub fn run() {
//!     listen_to_channel("myworkspace", "mychannel", |sm| {
//!         let cr = CompletionRequest {
//!             prompt: sm.text,
//!             ..Default::default()
//!         };
//!         let r = create_completion("myaccount", cr);
//!         r.iter().for_each(|c| {
//!             send_message_to_channel("myworkspace", "mychannel", c.to_string());
//!         });
//!     });
//! }
//! ```
//!
//! When the Slack message is received, create completion
//! using [create_completion] then send the response to Slack.

use std::fmt;
use std::thread::sleep;
use std::time::Duration;

use http_req::{
    request::{Method, Request},
    uri::Uri,
};
use lazy_static::lazy_static;
use serde::{Deserialize, Serialize};
use urlencoding::encode;

lazy_static! {
    static ref OPENAI_API_PREFIX: String = String::from(
        std::option_env!("OPENAI_API_PREFIX")
            .unwrap_or("https://openai-flows-integration.vercel.app/api")
    );
}

extern "C" {
    fn get_flows_user(p: *mut u8) -> i32;
    fn get_flow_id(p: *mut u8) -> i32;
    fn set_error_log(p: *const u8, len: i32);
}

const MAX_RETRY_TIMES: u8 = 10;
const RETRY_INTERVAL: u64 = 10; // Wait 10 seconds before retry

/// Request struct for the completion.
///
/// The default model is "text-davinci-003".
/// Use retry_times to set the number of retries when requesting
/// OpenAI's api encounters a problem. Default is 2 and max number is 10.
/// For more detail about parameters, please refer to
/// [OpenAI docs](https://platform.openai.com/docs/api-reference/completions/create)
///
#[derive(Debug, Serialize)]
pub struct CompletionRequest {
    pub model: String,
    pub prompt: String,
    pub suffix: Option<String>,
    pub n: u8,
    pub best_of: u8,
    pub max_tokens: u16,
    pub temperature: f32,
    pub top_p: f32,
    pub logprobs: Option<u8>,
    pub presence_penalty: f32,
    pub frequency_penalty: f32,
    pub retry_times: u8,
}

impl Default for CompletionRequest {
    fn default() -> CompletionRequest {
        CompletionRequest {
            model: String::from("text-davinci-003"),
            prompt: String::from("<|endoftext|>"),
            suffix: None,
            n: 1,
            best_of: 1,
            max_tokens: 16,
            temperature: 1.0,
            top_p: 1.0,
            logprobs: None,
            presence_penalty: 0.0,
            frequency_penalty: 0.0,
            retry_times: 2,
        }
    }
}

/// Create completion for the provided prompt and parameters.
///
/// `account` is the account name when you connect
/// [Flows.network](https://flows.network) platform with your OpenAI account.
///
/// `params` is a [CompletionRequest] object.
///
/// If you have not connected your OpenAI account with [Flows.network platform](https://flows.network),
/// you will receive an error in the flow's building log or running log.
///
pub fn create_completion(account: &str, params: CompletionRequest) -> Vec<String> {
    let retry_times = match params.retry_times {
        r if r <= 0 => 1,
        r if r > MAX_RETRY_TIMES => MAX_RETRY_TIMES,
        r => r,
    };
    create_completion_inner(account, params, retry_times)
}

pub fn create_completion_inner(
    account: &str,
    params: CompletionRequest,
    retry_times: u8,
) -> Vec<String> {
    unsafe {
        let mut flows_user = Vec::<u8>::with_capacity(100);
        let c = get_flows_user(flows_user.as_mut_ptr());
        flows_user.set_len(c as usize);
        let flows_user = String::from_utf8(flows_user).unwrap();

        let mut writer = Vec::new();
        let uri = format!(
            "{}/{}/create_completion?account={}",
            OPENAI_API_PREFIX.as_str(),
            flows_user,
            encode(account),
        );
        let uri = Uri::try_from(uri.as_str()).unwrap();
        let body = serde_json::to_vec(&params).unwrap_or_default();
        match Request::new(&uri)
            .method(Method::POST)
            .header("Content-Type", "application/json")
            .header("Content-Length", &body.len())
            .body(&body)
            .send(&mut writer)
        {
            Ok(res) => {
                if !res.status_code().is_success() {
                    match res.status_code().into() {
                        409 | 429 | 503 => {
                            // 409 TryAgain 429 RateLimitError
                            // 503 ServiceUnavableila
                            if retry_times > 1 {
                                sleep(Duration::from_secs(RETRY_INTERVAL));
                                return create_completion_inner(account, params, retry_times - 1);
                            }
                        }
                        _ => {}
                    }
                    set_error_log(writer.as_ptr(), writer.len() as i32);
                }
                serde_json::from_slice(&writer).unwrap_or_default()
            }
            Err(_) => {
                vec![]
            }
        }
    }
}

/// Response struct for the chat completion.
///
/// `restarted` is the flag to show whether a new conversation is created.
///
/// `choice` is the response from ChatGPT.
///
#[derive(Debug, Deserialize)]
pub struct ChatResponse {
    pub restarted: bool,
    pub choice: String,
}

impl Default for ChatResponse {
    fn default() -> ChatResponse {
        ChatResponse {
            restarted: true,
            choice: String::new(),
        }
    }
}

/// Models for Chat
#[derive(Debug, Clone, Copy)]
pub enum ChatModel {
    GPT4_32K,
    GPT4,
    GPT35Turbo,
}

impl fmt::Display for ChatModel {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            ChatModel::GPT4_32K => write!(f, "gpt-4-32k"),
            ChatModel::GPT4 => write!(f, "gpt-4"),
            ChatModel::GPT35Turbo => write!(f, "gpt-3.5-turbo"),
        }
    }
}

impl Default for ChatModel {
    fn default() -> ChatModel {
        ChatModel::GPT35Turbo
    }
}

/// struct for setting the chat options.
///
/// When `restart` is true, a new conversation will be created.
///
/// Use retry_times to set the number of retries when requesting
/// OpenAI's api encounters a problem. The max number is 10.
///
/// `system_prompt` will be treated as the prompt of the system role.
///
#[derive(Debug, Default)]
pub struct ChatOptions<'a> {
    pub model: ChatModel,
    pub restart: bool,
    pub system_prompt: Option<&'a str>,
    pub retry_times: u8,
}

/// Create chat completion with the provided sentence.
/// It use OpenAI's [GPT-3.5](https://platform.openai.com/docs/models/gpt-3-5) model to make a conversation.
/// It will keep the conversation history for 10 minutes for you.
/// That means a new conversation will be created if you haven't call this method for 10 minutes.
///
/// `conversation_id` is the identity of the conversation. The history will be fetched and attached
/// to the `sentence` as a whole prompt for ChatGPT.
///
/// `account` is the account name when you connect
/// [Flows.network](https://flows.network) platform with your OpenAI account.
///
/// `sentence` is a String reprensent the sentence of the conversation.
///
/// If you have not connected your OpenAI account with [Flows.network platform](https://flows.network),
/// you will receive an error in the flow's building log or running log.
///
pub fn chat_completion(
    account: &str,
    conversation_id: &str,
    sentence: &str,
    options: &ChatOptions,
) -> Option<ChatResponse> {
    let retry_times = match options.retry_times {
        r if r <= 0 => 1,
        r if r > MAX_RETRY_TIMES => MAX_RETRY_TIMES,
        r => r,
    };
    chat_completion_inner(account, conversation_id, sentence, options, retry_times)
}

pub fn chat_completion_inner(
    account: &str,
    conversation_id: &str,
    sentence: &str,
    options: &ChatOptions,
    retry_times: u8,
) -> Option<ChatResponse> {
    unsafe {
        let mut flows_user = Vec::<u8>::with_capacity(100);
        let c = get_flows_user(flows_user.as_mut_ptr());
        flows_user.set_len(c as usize);
        let flows_user = String::from_utf8(flows_user).unwrap();

        let mut flow_id = Vec::<u8>::with_capacity(100);
        let c = get_flow_id(flow_id.as_mut_ptr());
        if c == 0 {
            panic!("Failed to get flow id");
        }
        flow_id.set_len(c as usize);
        let flow_id = String::from_utf8(flow_id).unwrap();

        let mut writer = Vec::new();
        let uri = format!(
            "{}/{}/{}/chat_completion?account={}&conversation={}&model={}&restart={}",
            OPENAI_API_PREFIX.as_str(),
            flows_user,
            flow_id,
            encode(account),
            encode(conversation_id),
            options.model,
            options.restart,
        );
        let uri = Uri::try_from(uri.as_str()).unwrap();
        let body = serde_json::to_vec(&serde_json::json!({
            "sentence": sentence,
            "system_prompt": options.system_prompt
        }))
        .unwrap_or_default();
        match Request::new(&uri)
            .method(Method::POST)
            .header("Content-Type", "application/json")
            .header("Content-Length", &body.len())
            .body(&body)
            .send(&mut writer)
        {
            Ok(res) => {
                if !res.status_code().is_success() {
                    match res.status_code().into() {
                        409 | 429 | 503 => {
                            // 409 TryAgain 429 RateLimitError
                            // 503 ServiceUnavableila
                            if retry_times > 1 {
                                sleep(Duration::from_secs(RETRY_INTERVAL));
                                return chat_completion_inner(
                                    account,
                                    conversation_id,
                                    sentence,
                                    options,
                                    retry_times - 1,
                                );
                            }
                        }
                        _ => {}
                    }
                    set_error_log(writer.as_ptr(), writer.len() as i32);
                }
                serde_json::from_slice::<ChatResponse>(&writer).ok()
            }
            Err(_) => None,
        }
    }
}

#[derive(Debug, Serialize)]
pub enum ImageSize {
    S256,
    S512,
    S1024,
}

impl fmt::Display for ImageSize {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            ImageSize::S256 => write!(f, "256x256"),
            ImageSize::S512 => write!(f, "512x512"),
            ImageSize::S1024 => write!(f, "1024x1024"),
        }
    }
}

/// Request struct for the image creation.
///
/// For more detail about parameters, please refer to
/// [OpenAI docs](https://platform.openai.com/docs/api-reference/images/create)
///
#[derive(Debug, Serialize)]
pub struct ImageRequest {
    pub prompt: String,
    pub n: u8,
    pub size: ImageSize,
}

/// Create image for the provided prompt and parameters.
///
/// `account` is the account name when you connect
/// [Flows.network](https://flows.network) platform with your OpenAI account.
///
/// `params` is a [ImageRequest] object.
///
/// If you have not connected your OpenAI account with [Flows.network platform](https://flows.network),
/// you will receive an error in the flow's building log or running log.
///
pub fn create_image(account: &str, params: ImageRequest) -> Vec<String> {
    unsafe {
        let mut flows_user = Vec::<u8>::with_capacity(100);
        let c = get_flows_user(flows_user.as_mut_ptr());
        flows_user.set_len(c as usize);
        let flows_user = String::from_utf8(flows_user).unwrap();

        let mut writer = Vec::new();
        let uri = format!(
            "{}/{}/create_image?account={}",
            OPENAI_API_PREFIX.as_str(),
            flows_user,
            encode(account),
        );
        let uri = Uri::try_from(uri.as_str()).unwrap();
        let body = serde_json::to_vec(&params).unwrap_or_default();
        match Request::new(&uri)
            .method(Method::POST)
            .header("Content-Type", "application/json")
            .header("Content-Length", &body.len())
            .body(&body)
            .send(&mut writer)
        {
            Ok(res) => {
                if !res.status_code().is_success() {
                    set_error_log(writer.as_ptr(), writer.len() as i32);
                }
                serde_json::from_slice(&writer).unwrap_or_default()
            }
            Err(_) => {
                vec![]
            }
        }
    }
}