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
//! 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 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);
}

/// Request struct for the completion.
///
/// The default model is "text-davinci-003".
/// 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,
}

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,
        }
    }
}

/// 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> {
    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() {
                    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(),
        }
    }
}

/// struct for setting the chat options.
///
/// When `restart` is true, a new conversation will be created.
///
/// `restarted_sentence` will be used as `sentence` if a new conversation will be created.
///
/// A new conversation will be created in two cases:
/// 1. `restart` option is set to true
/// 2. There is no history for the `conversation_id`. The conversation history will be kept for 10
///    minutes after the last conversation.
///
#[derive(Debug, Default, Deserialize)]
pub struct ChatOptions<'a> {
    pub restart: bool,
    pub restarted_sentence: Option<&'a str>,
}

/// 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> {
    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={}&restart={}",
            OPENAI_API_PREFIX.as_str(),
            flows_user,
            flow_id,
            encode(account),
            encode(conversation_id),
            options.restart,
        );
        let uri = Uri::try_from(uri.as_str()).unwrap();
        let body = serde_json::to_vec(&serde_json::json!({
            "sentence": sentence,
            "restarted_sentence": options.restarted_sentence
        }))
        .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::<ChatResponse>(&writer).ok()
            }
            Err(_) => None,
        }
    }
}