open_ai 0.1.5

OpenAI library for Rust
Documentation
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
pub mod core;
mod openai_error;
mod pagination;
mod resource;
mod shared;
pub mod error;
pub mod library;
pub mod resources;
pub mod streaming;

// use resources::chat;
use std::cell::RefCell;
use std::collections::HashMap;
use std::env;
use std::rc::Rc;
use std::time::Duration;
use serde::{Deserialize, Serialize};
use crate::resources::completions::Completions;
use std::collections::HashSet;
use std::sync::{Arc, Mutex};
use lazy_static::lazy_static;
use crate::core::{APIClient, Headers};
use crate::resources::beta::Beta;
use crate::resources::chat::Chat;

#[derive(Debug, Clone)]
pub struct ClientOptions {
    /// Defaults to env::var['OPENAI_API_KEY'].
    pub api_key: Option<String>,
    /// Defaults to env::var['OPENAI_ORG_ID'].
    pub organization: Option<String>,

    /// Defaults to env::var['OPENAI_PROJECT_ID'].
    pub project: Option<String>,

    /// Override the default base URL for the API, e.g., "https://api.example.com/v2/"
    ///
    /// Defaults to env::var['OPENAI_BASE_URL'].
    pub base_url: Option<String>,

    /// The maximum amount of time (in milliseconds) that the client should wait for a response
    /// from the server before timing out a single request.
    ///
    /// Note that request timeouts are retried by default, so in a worst-case scenario you may wait
    /// much longer than this timeout before the promise succeeds or fails.
    pub timeout: Option<Duration>,

    /// An HTTP agent used to manage HTTP(S) connections.
    pub http_agent: Option<APIClient>,

    /// Specify a custom `fetch` function implementation.
    pub fetch: Option<APIClient>,

    /// The maximum number of times that the client will retry a request in case of a
    /// temporary failure, like a network error or a 5XX error from the server.
    ///
    /// @default 2
    pub max_retries: Option<u32>,

    /// Default headers to include with every request to the API.
    ///
    /// These can be removed in individual requests by explicitly setting the
    /// header to `None` in request options.
    pub default_headers: Option<HashMap<String, String>>,

    /// Default query parameters to include with every request to the API.
    ///
    /// These can be removed in individual requests by explicitly setting the
    /// param to `None` in request options.
    pub default_query: Option<HashMap<String, String>>,

    /// By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.
    /// Only set this option to `true` if you understand the risks and have appropriate mitigations in place.
    pub dangerously_allow_browser: bool,
}

impl ClientOptions {
    pub fn new() -> Self {
        ClientOptions {
            api_key: env::var("OPENAI_API_KEY").ok(),
            organization: env::var("OPENAI_ORG_ID").ok(),
            project: env::var("OPENAI_PROJECT_ID").ok(),
            base_url: env::var("OPENAI_BASE_URL").ok(),
            timeout: Some(Duration::from_secs(600)),
            http_agent: None,
            fetch: None,
            max_retries: Some(2),
            default_headers: None,
            default_query: None,
            dangerously_allow_browser: false,
        }
    }

    pub fn default() -> Self {
        ClientOptions::new()
    }
}

#[derive(Debug, Clone)]
pub struct OpenAI {
    pub api_key: String,
    pub organization: Option<String>,
    pub project: Option<String>,
    pub options: ClientOptions,
    pub client: APIClient,
    pub completions: Completions,
    pub chat: Chat,
    pub beta: Beta,
}

impl OpenAI {
    pub fn new(opts: ClientOptions) -> Result<Self, String> {
        let api_key = match opts.api_key.clone() {
            Some(key) => key,
            None => return Err("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option.".to_string()),
        };

        if opts.dangerously_allow_browser && cfg!(target_arch = "wasm32") {
            return Err("It looks like you're running in a browser-like environment. This is disabled by default, as it risks exposing your secret API credentials to attackers. If you understand the risks and have appropriate mitigations in place, you can set the `dangerouslyAllowBrowser` option to `true`.".to_string());
        }

        let client = APIClient::new(
            opts.base_url.clone().unwrap_or("https://api.openai.com/v1".to_string()),
            opts.max_retries.unwrap_or(2),
            opts.timeout.unwrap_or(Duration::from_secs(600)),
            reqwest::Client::new(),
        );

        let mut openai = OpenAI {
            api_key,
            organization: opts.organization.clone(),
            project: opts.project.clone(),
            options: opts,
            client,
            completions: Completions::new(),
            chat: Chat::new(),
            beta: Beta::new(),
        };

        openai.client.additional_auth_headers = Some(openai.auth_headers());
        // openai.completions.client = Some(Rc::new(RefCell::new(openai.client.clone())));
        openai.completions.client = Some(Arc::new(Mutex::new(openai.client.clone())));
        // openai.chat.set_client(Rc::new(RefCell::new(openai.client.clone())));
        openai.chat.set_client(Arc::new(Mutex::new(openai.client.clone())));
        // openai.beta.set_client(Rc::new(RefCell::new(openai.client.clone())));
        openai.beta.set_client(Arc::new(Mutex::new(openai.client.clone())));

        Ok(openai)
    }

    pub fn default() -> Result<Self, String> {
        OpenAI::new(ClientOptions::new())
    }

    // fn default_headers(&self) -> HashMap<String, String> {
    //     let mut headers = HashMap::new();
    //     if let Some(ref org) = self.organization {
    //         headers.insert("OpenAI-Organization".to_string(), org.clone());
    //     }
    //     if let Some(ref proj) = self.project {
    //         headers.insert("OpenAI-Project".to_string(), proj.clone());
    //     }
    //     if let Some(ref default_headers) = self.options.default_headers {
    //         for (key, value) in default_headers {
    //             headers.insert(key.clone(), value.clone());
    //         }
    //     }
    //     headers
    // }

    fn auth_headers(&self) -> Headers {
        let mut headers = HashMap::new();
        headers.insert("Authorization".to_string(), Some(format!("Bearer {}", self.api_key)));
        headers
    }

    // fn build_request(
    //     &self,
    //     method: Method,
    //     path: &str,
    //     params: Option<&HashMap<String, String>>
    // ) -> RequestBuilder {
    //     let url = format!(
    //         "{}/{}",
    //         self.options.base_url.as_ref().unwrap_or(&"https://api.openai.com/v1".to_string()),
    //         path
    //     );
    //
    //     let headers_map = self.auth_headers();
    //     let mut headers = HeaderMap::new();
    //     for (key, value) in headers_map {
    //         headers.insert(
    //             HeaderName::from_str(&key).unwrap(),
    //             HeaderValue::from_str(&value).unwrap(),
    //         );
    //     }
    //
    //     let request = self.client.request(method, &url).headers(headers);
    //
    //     if let Some(params) = params {
    //         request.json(params)
    //     } else {
    //         request
    //     }
    // }

    // pub async fn completions(&self, params: HashMap<String, String>) -> Result<reqwest::Response, reqwest::Error> {
    //     self.build_request(reqwest::Method::POST, "completions", Some(&params)).send().await
    // }

    // pub async fn chat(&self, params: HashMap<String, String>) -> Result<reqwest::Response, reqwest::Error> {
    //     self.build_request(reqwest::Method::POST, "chat/completions", Some(&params)).send().await
    // }
    //
    // pub async fn embeddings(&self, params: HashMap<String, String>) -> Result<reqwest::Response, reqwest::Error> {
    //     self.build_request(reqwest::Method::POST, "embeddings", Some(&params)).send().await
    // }
    //
    // pub async fn files(&self) -> Result<reqwest::Response, reqwest::Error> {
    //     self.build_request(reqwest::Method::GET, "files", None).send().await
    // }
    //
    // pub async fn images(&self, params: HashMap<String, String>) -> Result<reqwest::Response, reqwest::Error> {
    //     self.build_request(reqwest::Method::POST, "images/generations", Some(&params)).send().await
    // }
    //
    // pub async fn audio(&self, params: HashMap<String, String>) -> Result<reqwest::Response, reqwest::Error> {
    //     self.build_request(reqwest::Method::POST, "audio/transcriptions", Some(&params)).send().await
    // }
    //
    // pub async fn moderations(&self, params: HashMap<String, String>) -> Result<reqwest::Response, reqwest::Error> {
    //     self.build_request(reqwest::Method::POST, "moderations", Some(&params)).send().await
    // }
    //
    // pub async fn models(&self) -> Result<reqwest::Response, reqwest::Error> {
    //     self.build_request(reqwest::Method::GET, "models", None).send().await
    // }
    //
    // pub async fn fine_tuning(&self, params: HashMap<String, String>) -> Result<reqwest::Response, reqwest::Error> {
    //     self.build_request(reqwest::Method::POST, "fine-tuning", Some(&params)).send().await
    // }
    //
    // pub async fn beta(&self, params: HashMap<String, String>) -> Result<reqwest::Response, reqwest::Error> {
    //     self.build_request(reqwest::Method::POST, "beta", Some(&params)).send().await
    // }
    //
    // pub async fn batches(&self, params: HashMap<String, String>) -> Result<reqwest::Response, reqwest::Error> {
    //     self.build_request(reqwest::Method::POST, "batches", Some(&params)).send().await
    // }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorResponse {
    pub error: ErrorObject,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorObject {
    pub message: String,
    pub type_: String,
    pub param: Option<String>,
    pub code: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FunctionDefinition {
    pub name: String,
    pub description: Option<String>,
    pub parameters: FunctionParameters,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FunctionParameters {
    pub type_: String,
    pub properties: HashMap<String, Property>,
    pub required: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Property {
    pub type_: String,
    pub description: Option<String>,
}


#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OpenAIObject {
    #[default]
    #[serde(rename = "chat.completion")]
    ChatCompletion,
    TextCompletion,
    Thread,
}

lazy_static! {
    static ref DEPLOYMENTS_ENDPOINTS: HashSet<&'static str> = {
        let mut m = HashSet::new();
        m.insert("/completions");
        m.insert("/chat/completions");
        m.insert("/embeddings");
        m.insert("/audio/transcriptions");
        m.insert("/audio/translations");
        m.insert("/audio/speech");
        m.insert("/images/generations");
        m
    };
}


#[cfg(test)]
mod tests {
    use std::env;
    use std::error::Error;
    use futures::StreamExt;
    use reqwest_eventsource::Event;
    use serde_json::json;
    use crate::{ClientOptions, OpenAI};
    use crate::library::assistant_stream::AssistantStream;
    use crate::resources::beta::assistants::Assistant;
    use crate::resources::beta::assistants::AssistantTool::{self, CodeInterpreter};
    use crate::resources::beta::assistants::assistant::ToolResources;
    use crate::resources::beta::assistants::assistant::tool_resources::FileSearch;
    use crate::resources::beta::assistants::{assistant_list_params, AssistantCreateParams, AssistantListParams};
    use crate::resources::beta::assistants;
    use crate::resources::beta::threads::messages::{message, message_create_params};
    use crate::resources::beta::threads::runs::runs::RunStatus;
    use crate::resources::beta::threads::{Message, MessageContentDelta, MessageCreateParams, MessageListParams, messages, RunCreateParams, RunSubmitToolOutputsParams, ThreadCreateParams};
    use crate::resources::beta::threads::runs::runs::run_submit_tool_outputs_params::ToolOutput;
    use crate::resources::beta::threads::runs::steps::run_step_delta::StepDetails::ToolCalls;
    use crate::resources::beta::threads::runs::steps::ToolCallDelta;
    use crate::resources::chat::ChatCompletionContent::Text;
    use crate::resources::chat::ChatCompletionContentPart::Image;
    use crate::resources::chat::ChatModel;
    use crate::resources::chat::chat_completion_content_part_image::{ImageURL, Detail};
    use crate::resources::chat::{ChatCompletionCreateParams, ChatCompletionMessageParam, ChatCompletionContent::{self, Multiple}, ChatCompletionContentPart};
    use crate::resources::completions::CompletionCreateParams;

    #[tokio::test]
    async fn test_completions() -> Result<(), Box<dyn Error>> {
        let openai = OpenAI::default()?;

        let mut completion = openai.completions.create(CompletionCreateParams {
            model: "gpt-3.5-turbo-instruct".to_string(),
            prompt: Some(json!("Write a tagline for an ice cream shop.")),
            stream: Some(true),
            ..Default::default()
        }).into_stream();

        while let Some(event) = completion.next().await {
            match event {
                Ok(t) => {
                    // println!("{:?}", t);
                    let text = t.choices.first().unwrap().text.as_str().to_owned();
                    print!("{}", text);
                },
                Err(_) => {
                    println!("Error: {:?}", event);
                    // break;
                }
            }
        }

        // assert!(completion.is_ok());
        // println!("{:?}", completion.unwrap().choices.first().unwrap().text);

        Ok(())
    }

    #[tokio::test]
    async fn test_chat_completions() -> Result<(), Box<dyn Error>> {
        let openai = OpenAI::new(ClientOptions::new())?;
        let mut completion = openai.chat.completions.create(ChatCompletionCreateParams {
            // model: ChatModel::Gpt4o.into(),
            model: "gpt-4o-mini",
            messages: vec![
                ChatCompletionMessageParam::System{ content: "You are a helpful assistant.", name: None },
                ChatCompletionMessageParam::User{ content: Text("Who won the world series in 2020?"), name: None },
                ChatCompletionMessageParam::Assistant{ content: Some("The Los Angeles Dodgers won the World Series in 2020."), name: None, tool_calls: None },
                ChatCompletionMessageParam::User{ content: Text("Where was it played?"), name: None },
                // ChatCompletionMessageParam::User{
                //     content: Multiple(vec![
                //         ChatCompletionContentPart::Text{ text: "What happened to my car?".to_string() },
                //         Image {
                //             image_url: ImageURL {
                //                 url: "https://media.infopay.net/thumbnails/lx1gBJsFEGfwcXqKPxMkSpi5FGv2k0TtWniTAvTv.webp".to_string(),
                //                 detail: Some(Detail::Auto),
                //             }
                //         },
                //     ]),
                //     name: None,
                // },
            ],
            stream: Some(true),
            ..Default::default()
        }).into_stream();

        while let Some(event) = completion.next().await {
            match event {
                Ok(t) => {
                    // println!("chunk: {:?}", t);
                    let first = t.choices.first();
                    if  first.is_none() {
                        continue;
                    }
                    let text = first.unwrap().delta.content.as_ref().clone().to_owned();
                    if let Some(text) = text {
                        print!("{}", text);
                    }
                },
                Err(_) => {
                    println!("Error: {:?}", event);
                    // break;
                }
            }
        }

        // match &completion {
        //     Ok(response) => {
        //         println!("success: {:?}", response.choices.first().unwrap().message);
        //     }
        //     Err(e) => {
        //         let error = e.to_string();
        //         println!("error: {:?}", error);
        //     }
        // }

        // assert!(completion.is_ok());
        // println!("{:?}", completion.unwrap().choices.first().unwrap().message);

        Ok(())
    }

    // #[tokio::test]
    // async fn test_chat_completions_with_image() -> Result<(), Box<dyn Error>> {
    //     let openai = OpenAI::default()?;
    //
    //     // let list = openai.beta.assistants.list(
    //     //     AssistantListParams {
    //     //         order: Some(assistant_list_params::Order::Asc),
    //     //         limit: Some(20),
    //     //         ..Default::default()
    //     //     },
    //     //     None,
    //     // ).await.unwrap();
    //     //
    //     // list.get_next_page();
    //     //
    //     // list.has_next_page();
    //     //
    //     //     list.iter_pages();
    //     //
    //     // let b = list.data;
    //
    //     let completion = openai.chat.completions.create(ChatCompletionCreateParams {
    //         model: "gpt-4o",// ChatModel::Gpt4o.into(),
    //         messages: vec![
    //             ChatCompletionMessageParam::System{
    //                 content: "You are a helpful assistant.",
    //                 name: None,
    //             },
    //             ChatCompletionMessageParam::User{
    //                 content: Multiple(vec![Image {
    //                     image_url: ImageURL {
    //                         url: "https://inovaveterinaria.com.br/wp-content/uploads/2015/04/gato-sem-raca-INOVA-2048x1365.jpg".to_string(),
    //                         detail: Some(Detail::Auto),
    //                     }
    //                 }]),
    //                 name: None,
    //             },
    //         ],
    //         ..Default::default()
    //     }).await;
    //
    //     match &completion {
    //         Ok(response) => {
    //             println!("success: {:?}", response.choices.first().unwrap().message);
    //         }
    //         Err(e) => {
    //             let error = e.to_string();
    //             println!("error: {:?}", error);
    //         }
    //     }
    //
    //     assert!(completion.is_ok());
    //     println!("{:?}", completion.unwrap().choices.first().unwrap().message);
    //
    //     Ok(())
    // }
    //
    // // #[tokio::test]
    // // async fn test_create_assistant() -> Result<(), Box<dyn Error>> {
    // //
    // //     let openai = OpenAI::default()?;
    // //
    // //     let my_assistant = openai.beta.assistants.create(
    // //         AssistantCreateParams {
    // //             name: Some("Math Tutor".to_string()),
    // //             instructions: Some("You are a personal math tutor. When asked a question, write and run Python code to answer the question.".to_string()),
    // //             tools: Some(vec![CodeInterpreter]),
    // //             model: "gpt-4o".to_string(),
    // //             ..Default::default()
    // //         },
    // //         None,
    // //     ).await?;
    // //
    // //     println!("{:?}", my_assistant);
    // //
    // //     Ok(())
    // // }
    //
    // #[tokio::test]
    // async fn test_retrieve_assistant() -> Result<(), Box<dyn Error>> {
    //     let assistant_id = env::var("ASSISTANT_ID").ok().expect("ASSISTANT_ID is not set");
    //
    //     let test = Assistant {
    //         id: assistant_id.clone(),
    //         object: assistants::assistant::Object::Assistant,
    //         created_at: 1719335980,
    //         name: Some("Maia".to_string()),
    //         description: None,
    //         model: "gpt-4o".to_string(),
    //         instructions: Some("Objective:\nThe Roadr Assistant is designed to help users with all aspects of the Roadr services. It should provide clear, friendly, and helpful responses, simulating human-like expressions. It should never state explicitly that it is just an assistant but instead use alternative responses to convey similar messages. Your name is Maia, and you should looks like a person\n\nTone and Style:\n\n\t1.\tFriendly and Approachable: Always greet users warmly and respond in a friendly, conversational tone.\n\t2.\tProfessional and Polite: Maintain a level of professionalism and politeness in all interactions.\n\t3.\tHuman-like Expressions: Use natural language and expressions to simulate a human-like conversation. Avoid robotic or overly formal language.\n\nInteraction Guidelines:\n\n\t1.\tAvoid Self-referencing as an Assistant: Instead of saying “I’m just an assistant,” use phrases like “Let me help you with that,” or “Here’s some information you might find useful.”\n\t2.\tProvide Clear and Concise Answers: Ensure that responses are straightforward and easy to understand. Break down complex information into manageable parts.\n\t3.\tEmpathy and Understanding: Show empathy where appropriate. For example, if a user is frustrated, acknowledge their feelings and offer a solution.\n\t4.\tOffer Assistance Proactively: If a user seems unsure or stuck, offer additional help or suggest next steps without waiting for them to ask.\n\t5.\tPersonalization: Use the user’s name if provided and remember previous interactions to create a personalized experience.\n\nResponse Examples:\n\n\t•\tGreeting:\n\t•\t“Hi there! How can I assist you with Roadr services today?”\n\t•\t“Hello! What can I help you with?”\n\t•\tAssistance with Services:\n\t•\t“Sure, I can help you with booking a service. Which service are you interested in?”\n\t•\t“Let me guide you through the process of scheduling a pick-up.”\n\t•\tHandling Uncertainty:\n\t•\t“I’m here to help! Could you please provide a bit more detail about your issue?”\n\t•\t“I understand this can be confusing. Let’s work through it together.”\n\t•\tEmpathy and Reassurance:\n\t•\t“I’m sorry to hear that you’re having trouble. Let’s see how we can fix this.”\n\t•\t“I understand your frustration. Let’s get this sorted out.”\n\t•\tOffering Further Assistance:\n\t•\t“Is there anything else I can help you with?”\n\t•\t“Feel free to ask if you have more questions!”\n\nError Handling:\n\n\t1.\tAcknowledgment: Recognize when you don’t have enough information or when a mistake is made.\n\t•\t“I’m sorry, I didn’t quite catch that. Could you please clarify?”\n\t2.\tAlternative Solutions: Offer alternative ways to find the information or solve the problem.\n\t•\t“I might not have the exact answer, but you can find more details here [link].”\n\nKnowledge Base:\n\n\t1.\tServices Information: Be well-versed with all Roadr services, features, and processes.\n\t2.\tCommon Issues and FAQs: Have quick access to solutions for common problems and frequently asked questions.\n\t3.\tUpdates and News: Stay updated with the latest changes and updates to Roadr \n\nDetails:\n\nYou can't provide the reference of the vector store. It will not be displayed to the user.\n\nDon't use \"from the Document\" when answering a question. Never use it.\n\nNever also answering by referring to the files you've uploaded to the user. Always sound like a human and willing to help the user but never telling the user about Documents or files.\n\nTry not to answer with very long messages. Keep it clear and concise for the user to understand.\n\nDon't use \"from the files related\" when answering a question to the user. Always sound like a human a provide a straight answer.\n\nDon't use based on the documents provided.\n\nWhen the user asks for: Vehicle diagnostics, Vehicle won't start, Vehicle safety tips, find the user's vehicles and give the response based on those vehicles.\n\nSimply provide the service detail to the client and the client should be the one contacting the company.\n\nMake sure to select for  the service that suits the vehicle that the user has saved in data base. For instance the right type of tow based on vehicle that the user has saved. Don't provide a standard tow solution to a vehicle that can only be towed using flatbed.\n\nProvide phone numbers using the country format.\n\nDon't mention \"Base\" when providing pricing information. Simply provide the type of service and the price.\n\nRoadr Support number, since it's a USA based phone number use only the USA country code.\n".to_string()),
    //         tools: vec![],
    //         top_p: Some(1.0),
    //         temperature: Some(1.0),
    //         tool_resources: Some(ToolResources {
    //             file_search: Some(FileSearch {
    //                 vector_store_ids: Some(vec!["vs_thrV9nOtEaKwID1AHefXqhMi".to_string()]),
    //             }),
    //             code_interpreter: None,
    //         }),
    //         metadata: Some(json!({})),
    //         response_format: None,
    //     };
    //     let json_test = serde_json::to_string(&test).unwrap();
    //     println!("{:?}", test);
    //     println!("{:?}", json_test);
    //
    //     let openai = OpenAI::default()?;
    //
    //     let my_assistant = openai.beta.assistants.retrieve(
    //         &assistant_id,
    //         None,
    //     ).await;
    //
    //     println!("{:?}", my_assistant);
    //
    //     match &my_assistant {
    //         Ok(response) => {
    //             println!("success: {:#?}", response);
    //         }
    //         Err(e) => {
    //             let error = e.to_string();
    //             println!("error: {:?}", error);
    //         }
    //     }
    //
    //     assert!(my_assistant.is_ok());
    //     println!("{:?}", my_assistant);
    //
    //     Ok(())
    // }
    //
    // #[tokio::test]
    // async fn test_create_thread() -> Result<(), Box<dyn Error>> {
    //     let openai = OpenAI::default()?;
    //
    //     let empty_thread = openai.beta.threads.create(ThreadCreateParams::default()).await;
    //
    //     println!("{:?}", empty_thread);
    //
    //     match &empty_thread {
    //         Ok(response) => {
    //             println!("success: {:#?}", response);
    //         }
    //         Err(e) => {
    //             let error = e.to_string();
    //             println!("error: {:?}", error);
    //         }
    //     }
    //
    //     assert!(empty_thread.is_ok());
    //     println!("{:?}", empty_thread);
    //
    //     Ok(())
    // }
    //
    // #[tokio::test]
    // async fn test_create_thread_and_create_message() -> Result<(), Box<dyn Error>> {
    //     let openai = OpenAI::default()?;
    //
    //     let test = Message {
    //         id: "msg_INmSdEzy0wQ5OOGWFObGCUP8".to_string(),
    //         object: message::Object::ThreadMessage,
    //         created_at: 1721873547,
    //         assistant_id: None,
    //         thread_id: "thread_851X8yY9z3GhV9AdkVvNvkjs".to_string(),
    //         run_id: None,
    //         role: message::Role::User,
    //         content: vec![
    //             messages::MessageContent::Text {
    //                 text: messages::Text {
    //                     value: "I need to solve the equation `3x + 11 = 14`. Can you help me?".to_string(),
    //                     annotations: vec![]
    //                 }
    //             }
    //         ],
    //         attachments: Some(vec![]),
    //         metadata: Some(json!({})),
    //         incomplete_at: None,
    //         completed_at: None,
    //         incomplete_details: None,
    //         status: Default::default(),
    //     };
    //     let json_test = serde_json::to_string(&test).unwrap();
    //     println!("{:?}", test);
    //     println!("{:?}", json_test);
    //
    //
    //     let thread = openai.beta.threads.create(ThreadCreateParams::default()).await?;
    //
    //     println!("{:?}", thread);
    //
    //     let message = openai.beta.threads.messages.create(
    //         &thread.id,
    //         MessageCreateParams {
    //             role: message_create_params::Role::User,
    //             content: message_create_params::Content::Text("I need to solve the equation `3x + 11 = 14`. Can you help me?".to_string()),
    //             ..Default::default()
    //         },
    //         None,
    //     ).await;
    //
    //     println!("{:?}", message);
    //
    //     match &message {
    //         Ok(response) => {
    //             println!("success: {:#?}", response);
    //         }
    //         Err(e) => {
    //             let error = e.to_string();
    //             println!("error: {:?}", error);
    //         }
    //     }
    //
    //     assert!(message.is_ok());
    //     println!("{:?}", message);
    //
    //     Ok(())
    // }
    //
    //
    #[tokio::test]
    async fn test_create_thread_and_create_message_and_create_run_and_poll() -> Result<(), Box<dyn Error>> {
        let assistant_id = env::var("ASSISTANT_ID").ok().expect("ASSISTANT_ID is not set");

        let openai = OpenAI::new(ClientOptions::default())?;

        let thread = openai.beta.threads.create(ThreadCreateParams::default()).await?;

        println!("{:?}", thread);

        let message = openai.beta.threads.messages.create(
            &thread.id,
            MessageCreateParams {
                role: message_create_params::Role::User,
                content: message_create_params::Content::Text("I need to solve the equation `3x + 11 = 14`. Can you help me?".to_string()),
                ..Default::default()
            },
            None,
        ).await?;

        let run = openai.beta.threads.runs.create_and_poll(
            &thread.id,
            RunCreateParams {
                assistant_id: assistant_id.to_string(),
                additional_instructions: Some("Please address the user as Jane Doe. The user has a premium account.".to_string()),
                ..Default::default()
            },
            None
        ).await?;

        println!("{:?}", message);

        if run.status == RunStatus::Completed {
            let messages = openai.beta.threads.messages.list(
                &run.thread_id,
                None,
                None,
            ).await?;

            for message in messages.data.iter().rev() {
                match &message.content.first().unwrap() {
                    messages::MessageContent::Text { text } => {
                        println!("{:?} > {:?}", message.role, text.value);
                    }
                    _ => {}
                }
            }
        } else {
            println!("{:?}", run.status);
            panic!("Run not completed");
        }


        Ok(())
    }

    #[tokio::test]
    async fn test_create_thread_and_create_message_and_create_run_with_stream() -> Result<(), Box<dyn Error>> {
        let assistant_id = env::var("ASSISTANT_ID").ok().expect("ASSISTANT_ID is not set");

        let openai = OpenAI::new(ClientOptions::default())?;

        let thread = openai.beta.threads.create(ThreadCreateParams::default()).await?;

        println!("{:?}", thread);

        let message = openai.beta.threads.messages.create(
            &thread.id,
            MessageCreateParams {
                role: message_create_params::Role::User,
                // content: message_create_params::Content::Text("I need to solve the equation `3x + 11 = 14`. Can you help me?".to_string()),
                content: message_create_params::Content::Text("What vehicles I have?".to_string()),
                ..Default::default()
            },
            None,
        ).await?;

        println!("{:?}", message);

        let mut run = openai.beta.threads.runs.stream(
            &thread.id,
            RunCreateParams {
                assistant_id: assistant_id.to_string(),
                additional_instructions: Some("Please address the user as Jane Doe. The user has a premium account.".to_string()),
                stream: Some(true),
                ..Default::default()
            },
            None
        ).into_stream();

        while let Some(event) = run.next().await {
            match event {
                Ok(AssistantStream::MessageDelta(message)) => {
                    message.delta.content.iter().for_each(|content| {
                        for delta in content.iter() {
                            match delta {
                                MessageContentDelta::TextDeltaBlock( text) => {
                                    if let Some(text) = text.text.as_ref() {
                                        if let Some(text) = text.value.as_ref() {
                                            print!("{}", text);
                                        }
                                    }
                                }
                                _ => {}
                            }
                        }
                    });
                    // message.content.iter().for_each(|content| {
                    //     for delta in content.iter() {
                    //         match delta {
                    //             MessageContentDelta::TextDeltaBlock( text) => {
                    //                 println!("{:?} > {:?}", message.role, text.text);
                    //             }
                    //             _ => {}
                    //         }
                    //     }
                    // });
                    // println!("chunk: {:?}", message);

                    // let first = t.choices.first();
                    // if  first.is_none() {
                    //     continue;
                    // }
                    // let text = first.unwrap().delta.content.as_ref().clone().to_owned();
                    // if let Some(text) = text {
                    //     print!("{}", text);
                    // }
                },
                Ok(AssistantStream::ToolCallDelta(tool_call)) => {
                    println!("tool_call: {:?}", tool_call);
                }
                Ok(AssistantStream::Run(message)) => {
                    println!("run: {:?}", message);
                },
                Err(_) => {
                    println!("Error: {:?}", event);
                    break;
                },
                _ => {continue}
            }
        }
        
        // if run.status == RunStatus::Completed {
        //     let messages = openai.beta.threads.messages.list(
        //         &run.thread_id,
        //         None,
        //         None,
        //     ).await?;
        //
        //     for message in messages.data.iter().rev() {
        //         match &message.content.first().unwrap() {
        //             messages::MessageContent::Text { text } => {
        //                 println!("{:?} > {:?}", message.role, text.value);
        //             }
        //             _ => {}
        //         }
        //     }
        // } else {
        //     println!("{:?}", run.status);
        //     panic!("Run not completed");
        // }


        Ok(())
    }

    #[tokio::test]
    async fn test_create_thread_and_create_message_and_create_run_with_stream_and_function() -> Result<(), Box<dyn Error>> {
        let assistant_id = env::var("ASSISTANT_ID").ok().expect("ASSISTANT_ID is not set");

        let openai = OpenAI::new(ClientOptions::default())?;

        let thread = openai.beta.threads.create(ThreadCreateParams::default()).await?;

        println!("{:?}", thread);

        let message = openai.beta.threads.messages.create(
            &thread.id,
            MessageCreateParams {
                role: message_create_params::Role::User,
                // content: message_create_params::Content::Text("I need to solve the equation `3x + 11 = 14`. Can you help me?".to_string()),
                content: message_create_params::Content::Text("What vehicles I have?".to_string()),
                ..Default::default()
            },
            None,
        ).await?;

        println!("{:?}", message);

        let mut run = openai.beta.threads.runs.stream(
            &thread.id,
            RunCreateParams {
                assistant_id: assistant_id.to_string(),
                additional_instructions: Some("Please address the user as Jane Doe. The user has a premium account.".to_string()),
                stream: Some(true),
                ..Default::default()
            },
            None
        ).into_stream();

        while let Some(event) = run.next().await {
            match event {
                Ok(AssistantStream::MessageDelta(message)) => {
                    message.delta.content.iter().for_each(|content| {
                        for delta in content.iter() {
                            match delta {
                                MessageContentDelta::TextDeltaBlock( text) => {
                                    if let Some(text) = text.text.as_ref() {
                                        if let Some(text) = text.value.as_ref() {
                                            print!("{}", text);
                                        }
                                    }
                                }
                                _ => {}
                            }
                        }
                    });
                    // message.content.iter().for_each(|content| {
                    //     for delta in content.iter() {
                    //         match delta {
                    //             MessageContentDelta::TextDeltaBlock( text) => {
                    //                 println!("{:?} > {:?}", message.role, text.text);
                    //             }
                    //             _ => {}
                    //         }
                    //     }
                    // });
                    // println!("chunk: {:?}", message);

                    // let first = t.choices.first();
                    // if  first.is_none() {
                    //     continue;
                    // }
                    // let text = first.unwrap().delta.content.as_ref().clone().to_owned();
                    // if let Some(text) = text {
                    //     print!("{}", text);
                    // }
                },
                Ok(AssistantStream::ToolCallDelta(tool_call)) => {
                    println!("tool_call: {:?}", tool_call);
                }
                Ok(AssistantStream::Run(message)) => {
                    println!("run: {:?}", message);
                    let tool_call_id: String = if let Some(first) = message.required_action.unwrap_or_default().submit_tool_outputs.tool_calls.first() {
                        first.id.clone()
                    } else { "".to_string() };

                    let tool_outputs = RunSubmitToolOutputsParams {
                        tool_outputs: vec![ToolOutput{ output: Some("Fusquinha".to_string()), tool_call_id: Some(tool_call_id) }],
                        stream: Some(true),
                    };

                    // Use the submitToolOutputsStream helper
                    let mut stream = openai.beta.threads.runs.submit_tool_outputs_stream(
                        &thread.id,
                        &message.id,
                        tool_outputs,
                        None,
                    ).into_stream();

                    while let Some(evt) = stream.next().await {
                        match evt {
                            Ok(AssistantStream::MessageDelta(message)) => {
                                message.delta.content.iter().for_each(|content| {
                                    for delta in content.iter() {
                                        match delta {
                                            MessageContentDelta::TextDeltaBlock(text) => {
                                                if let Some(text) = text.text.as_ref() {
                                                    if let Some(text) = text.value.as_ref() {
                                                        print!("{}", text);
                                                    }
                                                }
                                            }
                                            _ => continue,
                                        }
                                    }
                                });
                            }
                            _ => continue,
                        }
                    }
                },
                Err(_) => {
                    println!("Error: {:?}", event);
                    break;
                },
                _ => {continue}
            }
        }

        // if run.status == RunStatus::Completed {
        //     let messages = openai.beta.threads.messages.list(
        //         &run.thread_id,
        //         None,
        //         None,
        //     ).await?;
        //
        //     for message in messages.data.iter().rev() {
        //         match &message.content.first().unwrap() {
        //             messages::MessageContent::Text { text } => {
        //                 println!("{:?} > {:?}", message.role, text.value);
        //             }
        //             _ => {}
        //         }
        //     }
        // } else {
        //     println!("{:?}", run.status);
        //     panic!("Run not completed");
        // }


        Ok(())
    }

    #[tokio::test]
    async fn test_retrieve_run() -> Result<(), Box<dyn Error>> {
        let assistant_id = env::var("ASSISTANT_ID").ok().expect("ASSISTANT_ID is not set");

        let openai = OpenAI::new(ClientOptions::default())?;

        let thread = openai.beta.threads.create(ThreadCreateParams::default()).await?;

        println!("{:?}", thread);

        let message = openai.beta.threads.messages.create(
            &thread.id,
            MessageCreateParams {
                role: message_create_params::Role::User,
                // content: message_create_params::Content::Text("I need to solve the equation `3x + 11 = 14`. Can you help me?".to_string()),
                content: message_create_params::Content::Text("What vehicles I have?".to_string()),
                ..Default::default()
            },
            None,
        ).await?;

        let run = openai.beta.threads.runs.create(
            &thread.id,
            RunCreateParams {
                assistant_id: assistant_id.to_string(),
                additional_instructions: Some("Please address the user as Jane Doe. The user has a premium account.".to_string()),
                ..Default::default()
            },
            None
        ).await?;

        let run = openai.beta.threads.runs.retrieve(&thread.id, &run.id, None).await;

        Ok(())
    }

}