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
//! OpenAI integration for [Flows.network](https://flows.network)
//!
//! # Quick Start
//!
//! To get started, let's write a tiny flow function.
//!
//! ```rust
//! use openai_flows::{
//!     chat::ChatOptions,
//!     OpenAIFlows,
//! };
//! use lambda_flows::{request_received, send_response};
//! use serde_json::Value;
//! use std::collections::HashMap;
//!
//! #[no_mangle]
//! #[tokio::main(flavor = "current_thread")]
//! pub async fn run() {
//!     request_received(handler).await;
//! }
//!
//! async fn handler(_qry: HashMap<String, Value>, body: Vec<u8>) {
//!     let co = ChatOptions::default();
//!     let of = OpenAIFlows::new();
//!
//!     let r = match of.chat_completion(
//!         "any_conversation_id",
//!         String::from_utf8_lossy(&body).into_owned().as_str(),
//!         &co,
//!     )
//!     .await
//!     {
//!         Ok(c) => c.choice,
//!         Err(e) => e,
//!     };
//!     
//!     send_response(
//!         200,
//!         vec![(
//!             String::from("content-type"),
//!             String::from("text/plain; charset=UTF-8"),
//!         )],
//!         r.as_bytes().to_vec(),
//!     );
//! }
//! ```
//!
//! When the Lambda request is received, chat
//! using [chat_completion] then send the response.
//!
//! # Real World Example
//! [HackerNews Alert](https://github.com/flows-network/hacker-news-alert) uses openai_flows chat_completion function to summarize a news article.
//! ```
//! use anyhow;
//! use chrono::{Duration, Utc};
//! use dotenv::dotenv;
//! use http_req::{request, request::Method, request::Request, uri::Uri};
//! use openai_flows::{
//!     chat::{ChatModel, ChatOptions},
//!     OpenAIFlows,
//! };
//! use schedule_flows::schedule_cron_job;
//! use serde::{Deserialize, Serialize};
//! use serde_json::{json, Value};
//! use slack_flows::{listen_to_channel, send_message_to_channel};
//! use std::env;
//! use std::net::SocketAddr;
//! use std::time::{SystemTime, UNIX_EPOCH};
//! use web_scraper_flows::get_page_text;
//!
//! #[no_mangle]
//! pub fn run() {
//!     dotenv().ok();
//!     let keyword = std::env::var("KEYWORD").unwrap_or("chatGPT".to_string());
//!     schedule_cron_job(String::from("02 * * * *"), keyword, callback);
//! }
//!
//! #[no_mangle]
//! #[tokio::main(flavor = "current_thread")]
//! async fn callback(keyword: Vec<u8>) {
//!     let workspace = env::var("slack_workspace").unwrap_or("secondstate".to_string());
//!     let channel = env::var("slack_channel").unwrap_or("github-status".to_string());
//!     let query = String::from_utf8_lossy(&keyword);
//!     let now = SystemTime::now();
//!     let dura = now.duration_since(UNIX_EPOCH).unwrap().as_secs() - 3600;
//!     let url = format!("https://hn.algolia.com/api/v1/search_by_date?tags=story&query={query}&numericFilters=created_at_i>{dura}");

//!     let mut writer = Vec::new();
//!     if let Ok(_) = request::get(url, &mut writer) {
//!         if let Ok(search) = serde_json::from_slice::<Search>(&writer) {
//!             for hit in search.hits {
//!                 let title = &hit.title;
//!                 let url = &hit.url;
//!                 let object_id = &hit.object_id;
//!                 let author = &hit.author;
//!                 let post = format!("https://news.ycombinator.com/item?id={object_id}");
//!
//!                 match url {
//!                     Some(u) => {
//!                         let source = format!("(<{u}|source>)");
//!                         if let Ok(text) = get_page_text(u).await {
//!                             let text = text.split_whitespace().collect::<Vec<&str>>().join(" ");
//!                             match get_summary_truncated(&text).await {
//!                                 Ok(summary) => {
//!                                     let msg = format!(
//!                                         "- *{title}*\n<{post} | post>{source} by {author}\n{text}"
//!                                     );
//!                                     send_message_to_channel(&workspace, &channel, msg).await;
//!                                 }
//!                                 Err(_e) => {
//!                                     // Err(anyhow::Error::msg(_e.to_string()))
//!                                 }
//!                             }
//!                         }
//!                     }
//!                     None => {
//!                         if let Ok(text) = get_page_text(&post).await {
//!                             let text = text.split_whitespace().collect::<Vec<&str>>().join(" ");
//!                             if let Ok(summary) = get_summary_truncated(&text).await {
//!                                 let msg =
//!                                     format!("- *{title}*\n<{post} | post> by {author}\n{summary}");
//!                                 send_message_to_channel(&workspace, &channel, msg).await;
//!                             }
//!                         }
//!                     }
//!                 };
//!             }
//!         }
//!     }
//! }
//!
//! #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
//! pub struct Search {
//!     pub hits: Vec<Hit>,
//! }
//!
//! #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
//! #[serde(rename_all = "snake_case")]
//! pub struct Hit {
//!     pub title: String,
//!     pub url: Option<String>,
//!     #[serde(rename = "objectID")]
//!     pub object_id: String,
//!     pub author: String,
//!     pub created_at_i: i64,
//! }
//! // texts in the news webpage could exceed the maximum token limit of the language model,
//! // it is truncated to 11000 space delimited words in this code, when tokenized,
//! // the total token count shall be within the 16k limit of the model used.
//! async fn get_summary_truncated(inp: &str) -> anyhow::Result<String> {
//!     let mut openai = OpenAIFlows::new();
//!     openai.set_retry_times(3);
//!
//!     let news_body = inp
//!         .split_ascii_whitespace()
//!         .take(11000)
//!         .collect::<Vec<&str>>()
//!         .join(" ");
//!
//!     let chat_id = format!("news-summary-N");
//!     let system = &format!("You're a news editor AI.");
//!
//!     let co = ChatOptions {
//!         model: ChatModel::GPT35Turbo16K,
//!         restart: true,
//!         system_prompt: Some(system),
//!         ..chatOptions::default()
//!     };
//!
//!     let question = format!("Make a concise summary within 200 words on this: {news_body}.");
//!
//!     match openai.chat_completion(&chat_id, &question, &co).await {
//!         Ok(r) => Ok(r.choice),
//!         Err(_e) => Err(anyhow::Error::msg(_e.to_string())),
//!     }
//! }
//! ```

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

pub mod chat;
pub mod completion;
pub mod embeddings;
pub mod image;

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

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

unsafe fn _get_flows_user() -> String {
    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);
    String::from_utf8(flows_user).unwrap()
}

unsafe fn _get_flow_id() -> String {
    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);
    String::from_utf8(flow_id).unwrap()
}

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

/// The account name you provide to
/// [Flows.network](https://flows.network) platform,
/// which is tied to your OpenAI API key.
///
/// If set as `Default`, the 'Default' named account will be used.
/// If there is no 'Default' named account,
/// a random one will be selected from all your connected accounts.
///
pub enum FlowsAccount {
    Default,
    Provided(String),
}

/// The main struct for setting the basic configuration
/// for OpenAI interface.
pub struct OpenAIFlows {
    /// A [FlowsAccount] used to select your tied OpenAI API key.
    account: FlowsAccount,
    /// Use retry_times to set the number of retries when requesting
    /// OpenAI's api encounters a problem. Default is 0 and max number is 10.
    retry_times: u8,
}

impl OpenAIFlows {
    pub fn new() -> OpenAIFlows {
        OpenAIFlows {
            account: FlowsAccount::Default,
            retry_times: 0,
        }
    }

    pub fn set_flows_account(&mut self, account: FlowsAccount) {
        self.account = account;
    }

    pub fn set_retry_times(&mut self, retry_times: u8) {
        self.retry_times = retry_times;
    }

    fn keep_trying<T, F>(&self, f: F) -> Result<T, String>
    where
        F: Fn(&str) -> Retry<T>,
    {
        let account = match &self.account {
            FlowsAccount::Default => "",
            FlowsAccount::Provided(s) => s.as_str(),
        };
        let mut retry_times = match self.retry_times {
            r if r > MAX_RETRY_TIMES => MAX_RETRY_TIMES,
            r => r,
        };

        loop {
            match f(account) {
                Retry::Yes(s) => match retry_times > 0 {
                    true => {
                        sleep(Duration::from_secs(crate::RETRY_INTERVAL));
                        retry_times = retry_times - 1;
                        continue;
                    }
                    false => return Err(s),
                },
                Retry::No(r) => return r,
            }
        }
    }
}

enum Retry<T> {
    Yes(String),
    No(Result<T, String>),
}