crab_ai 0.1.4

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
use std::cell::RefCell;
use std::collections::HashMap;
use std::error::Error;
use std::rc::Rc;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::resource::{APIResource};
use crate::core::{self, APIClient, FinalRequestOptions, Headers, RequestOptions};
use crate::resources::beta::assistants as assistants_api;
use crate::pagination::{CursorPage, CursorPageResponse, Page};
use crate::resources::chat::ChatCompletionContentPart;

#[derive(Debug, Clone)]
pub struct Messages {
    pub client: Option<APIResource>,
}

impl Messages {
    pub fn new() -> Self {
        Messages {
            client: None,
        }
    }

    /// Create a message.
    pub async fn create(
        &self,
        thread_id: &str,
        body: MessageCreateParams,
        options: Option<RequestOptions<MessageCreateParams>>,
    ) -> Result<Message, Box<dyn Error>> {
        let mut headers: Headers = HashMap::new();
        headers.insert("OpenAI-Beta".to_string(), Some("assistants=v2".to_string()));
        if let Some(opts) = &options {
            if let Some(hdrs) = &opts.headers {
                for (key, value) in hdrs {
                    headers.insert(key.to_owned(), value.to_owned());
                }
            }
        }

        self.client.as_ref().unwrap().borrow().post(
            &format!("/threads/{thread_id}/messages"),
            Some(RequestOptions {
                body: Some(body),
                headers: Some(headers),
                ..options.unwrap_or_default()
            }),
        ).await
    }

    /// Retrieve a message.
    pub async fn retrieve(
        &self,
        thread_id: &str,
        message_id: &str,
        _options: Option<core::RequestOptions<()>>,
    ) -> Result<Message, Box<dyn Error>> {
        self.client.as_ref().unwrap().borrow().post(
            &format!("/threads/{thread_id}/messages/{message_id}"),
            Some(core::RequestOptions::<()> {
                ..Default::default()
                // ..options
            }),
        ).await
    }

    // retrieve(threadId: string, messageId: string, options: Option<Core.RequestOptions): Core.APIPromise<Message> {>,
    // return this._client.get(`/threads/{threadId}/messages/{messageId}`, {
    // ...options,
    // headers: { 'OpenAI - Beta': 'assistants = v2', ...options ?.headers },
    // });
    // }

    /// Modifies a message.
    pub async fn update(
        &self,
        thread_id: &str,
        message_id: &str,
        body: MessageUpdateParams,
        _options: Option<core::RequestOptions<MessageUpdateParams>>,
    ) -> Result<Message, Box<dyn Error>> {
        self.client.as_ref().unwrap().borrow().post(
            &format!("/threads/{thread_id}/messages/{message_id}"),
            Some(core::RequestOptions {
                body: Some(body),
                ..Default::default()
            }),
        ).await
    }

    // update(
    //     threadId: string,
    //     messageId: string,
    //     body: MessageUpdateParams,
    //     options: Option<Core.RequestOptions>,
    // ): Core.APIPromise<Message> {
    //     return this._client.post(`/threads/{threadId}/messages/{messageId}`, {
    //         body,
    //         ...options,
    //         headers: { 'OpenAI - Beta': 'assistants = v2', ...options ?.headers },
    //     });
    // }

    /// Returns a list of messages for a given thread.
    pub async fn list(
        &self,
        thread_id: &str,
        query: Option<MessageListParams>,
        _options: Option<RequestOptions<MessageListParams>>,
    ) -> Result<CursorPage<MessageListParams, Message>, Box<dyn Error>> {
        let mut headers: Headers = HashMap::new();
        headers.insert("OpenAI-Beta".to_string(), Some("assistants=v2".to_string()));

        let page_constructor = |
            client: Rc<RefCell<APIClient>>,
            body: CursorPageResponse<Message>,
            options: FinalRequestOptions<MessageListParams>,
        | {
            CursorPage::new(client, body, options)
        };

        self.client.as_ref().unwrap().borrow().get_api_list(
            &format!("/threads/{thread_id}/messages"),
            page_constructor,
            Some(RequestOptions {
                query: query,
                headers: Some(headers),
                ..Default::default()
            }),
        ).await
    }

    // list(
    //     threadId: string,
    //     query: Option<MessageListParams>,
    //     options: Option<Core.RequestOptions>,
    //   ): Core.PagePromise<MessagesPage, Message>;
    //   list(threadId: string, options: Option<Core.RequestOptions): Core.PagePromise<MessagesPage, Message>>,
    //   list(
    //     threadId: string,
    //     query: MessageListParams | Core.RequestOptions = {},
    //     options: Option<Core.RequestOptions>,
    //   ): Core.PagePromise<MessagesPage, Message> {
    //     if (isRequestOptions(query)) {
    //       return this.list(threadId, {}, query);
    //     }
    //     return this._client.getAPIList(`/threads/{threadId}/messages`, MessagesPage, {
    //       query,
    //       ...options,
    //       headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
    //     });
    //   }

    /// Deletes a message.
    pub async fn del(
        &self,
        thread_id: &str,
        message_id: &str,
        options: Option<core::RequestOptions>,
    ) -> Result<MessageDeleted, Box<dyn Error>> {
        let mut headers: Headers = HashMap::new();
        // headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
        headers.insert("OpenAI-Beta".to_string(), Some("assistants=v2".to_string()));
        if let Some(opts) = options {
            if let Some(hdrs) = opts.headers {
                for (key, value) in hdrs {
                    headers.insert(key, value);
                }
            }
        }
        self.client.as_ref().unwrap().borrow().delete(
            &format!("/threads/{thread_id}/messages/{message_id}"),
            Some(core::RequestOptions::<()> {
                headers: Some(headers),
                ..Default::default()
            }),
        ).await
    }

    // del(threadId: string, messageId: string, options: Option<Core.RequestOptions): Core.APIPromise<MessageDeleted> {>,
    // return this._client.delete(` / threads/ {threadId}/ messages / {messageId}`, {
    // ...options,
    // headers: { 'OpenAI - Beta': 'assistants = v2', ...options ?.headers },
    // });
    // }
}
/// A citation within the message that points to a specific quote from a specific
/// File associated with the assistant or the message. Generated when the assistant
/// uses the "file_search" tool to search files.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged, rename_all = "snake_case")]
pub enum Annotation {
    FileCitationAnnotation(FileCitationAnnotation),
    FilePathAnnotation(FilePathAnnotation),
}

impl Default for Annotation {
    fn default() -> Self {
        Annotation::FilePathAnnotation(FilePathAnnotation::default())
    }
}

/// A citation within the message that points to a specific quote from a specific
/// File associated with the assistant or the message. Generated when the assistant
/// uses the "file_search" tool to search files.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged, rename_all = "snake_case")]
pub enum AnnotationDelta {
    FileCitationDeltaAnnotation(FileCitationDeltaAnnotation),
    FilePathDeltaAnnotation(FilePathDeltaAnnotation),
}

/// A citation within the message that points to a specific quote from a specific
/// File associated with the assistant or the message. Generated when the assistant
/// uses the "file_search" tool to search files.
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct FileCitationAnnotation {
    pub end_index: u32,
    pub file_citation: file_citation_annotation::FileCitation,
    pub start_index: u32,

    /// The text in the message content that needs to be replaced.
    pub text: String,

    /// Always `file_citation`.
    #[serde(rename = "type")]
    pub file_citation_annotation_type: file_citation_annotation::Type,
}

pub mod file_citation_annotation {
    use super::*;

    #[derive(Default, Debug, Clone, Serialize, Deserialize)]
    pub struct FileCitation {
        /// The ID of the specific File the citation is from.
        pub file_id: String,
    }

    #[derive(Default, Debug, Clone, Serialize, Deserialize)]
    #[serde(rename_all = "snake_case")]
    pub enum Type {
        #[default]
        FileCitation,
    }
}

/// A citation within the message that points to a specific quote from a specific
/// File associated with the assistant or the message. Generated when the assistant
/// uses the "file_search" tool to search files.
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct FileCitationDeltaAnnotation {
    /// The index of the annotation in the text content part.
    pub index: u32,

    /// Always `file_citation`.
    #[serde(rename = "type")]
    pub kind: file_citation_delta_annotation::Type,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_index: Option<u32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub file_citation: Option<file_citation_delta_annotation::FileCitation>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_index: Option<u32>,

    /// The text in the message content that needs to be replaced.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
}

pub mod file_citation_delta_annotation {
    use super::*;

    #[derive(Default, Debug, Clone, Serialize, Deserialize)]
    pub struct FileCitation {
        /// The ID of the specific File the citation is from.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub file_id: Option<String>,

        /// The specific quote in the file.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub quote: Option<String>,
    }

    #[derive(Default, Debug, Clone, Serialize, Deserialize)]
    #[serde(rename_all = "snake_case")]
    pub enum Type {
        #[default]
        FileCitation,
    }
}

/// A URL for the file that's generated when the assistant used the
/// `code_interpreter` tool to generate a file.
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct FilePathAnnotation {
    pub end_index: u32,
    pub file_path: file_path_annotation::FilePath,
    pub start_index: u32,

    /// The text in the message content that needs to be replaced.
    pub text: String,

    /// Always `file_path`.
    #[serde(rename = "type")]
    pub kind: file_path_annotation::Type,
}

pub mod file_path_annotation {
    use super::*;

    #[derive(Default, Debug, Clone, Serialize, Deserialize)]
    pub struct FilePath {
        /// The ID of the file that was generated.
        pub file_id: String,
    }

    #[derive(Default, Debug, Clone, Serialize, Deserialize)]
    #[serde(rename_all = "snake_case")]
    pub enum Type {
        #[default]
        FilePath,
    }
}

/// A URL for the file that's generated when the assistant used the
/// `code_interpreter` tool to generate a file.
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct FilePathDeltaAnnotation {
    /// The index of the annotation in the text content part.
    pub index: u32,

    /// Always `file_path`.
    #[serde(rename = "type")]
    pub kind: file_path_delta_annotation::Type,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_index: Option<u64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub file_path: Option<file_path_delta_annotation::FilePath>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_index: Option<u64>,

    /// The text in the message content that needs to be replaced.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
}

pub mod file_path_delta_annotation {
    use super::*;

    #[derive(Default, Debug, Clone, Serialize, Deserialize)]
    pub struct FilePath {
        /// The ID of the file that was generated.
        #[serde(skip_serializing_if = "Option::is_none")]
        file_id: Option<String>,
    }

    #[derive(Default, Debug, Clone, Serialize, Deserialize)]
    #[serde(rename_all = "snake_case")]
    pub enum Type {
        #[default]
        FilePath,
    }
}

#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct ImageFile {
    /// The [File](https://platform.openai.com/docs/api-reference/files) ID of the image
    /// in the message content. Set `purpose="vision"` when uploading the File if you
    /// need to later display the file content.
    pub file_id: String,

    /// Specifies the detail level of the image if specified by the user. `low` uses
    /// fewer tokens, you can opt in to high resolution using `high`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub detail: Option<Detail>,
}

#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct ImageFileDelta {
    /// Specifies the detail level of the image if specified by the user. `low` uses
    /// fewer tokens, you can opt in to high resolution using `high`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub detail: Option<Detail>,

    /// The [File](https://platform.openai.com/docs/api-reference/files) ID of the image
    /// in the message content. Set `purpose="vision"` when uploading the File if you
    /// need to later display the file content.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file_id: Option<String>,
}

/// References an image [File](https://platform.openai.com/docs/api-reference/files)
/// in the content of a message.
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct ImageFileDeltaBlock {
    /// The index of the content part in the message.
    pub index: u32,

    /// Always `image_file`.
    #[serde(rename = "type")]
    pub kind: image_file_delta_block::Type,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub image_file: Option<ImageFileDelta>,
}

pub mod image_file_delta_block {
    use super::*;

    #[derive(Default, Debug, Clone, Serialize, Deserialize)]
    #[serde(rename_all = "snake_case")]
    pub enum Type {
        #[default]
        ImageFile,
    }
}

#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct ImageURL {
    /// The external URL of the image, must be a supported image types: jpeg, jpg, png,
    /// gif, webp.
    pub url: String,

    /// Specifies the detail level of the image. `low` uses fewer tokens, you can opt in
    /// to high resolution using `high`. Default value is `auto`
    #[serde(skip_serializing_if = "Option::is_none")]
    pub detail: Option<Detail>,
}

#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct ImageURLDelta {
    /// Specifies the detail level of the image. `low` uses fewer tokens, you can opt in
    /// to high resolution using `high`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub detail: Option<Detail>,

    /// The URL of the image, must be a supported image types: jpeg, jpg, png, gif,
    /// webp.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
}

/// References an image URL in the content of a message.
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct ImageURLDeltaBlock {
    /// The index of the content part in the message.
    pub index: u32,

    /// Always `image_url`.
    #[serde(rename = "type")]
    pub kind: image_url_delta_block::Type,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub image_url: Option<ImageURLDelta>,
}

pub mod image_url_delta_block {
    use super::*;

    #[derive(Default, Debug, Clone, Serialize, Deserialize)]
    #[serde(rename_all = "snake_case")]
    pub enum Type {
        #[default]
        ImageUrl,
    }

}

/// Represents a message within a
/// [thread](https://platform.openai.com/docs/api-reference/threads).
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct Message {
    /// The identifier, which can be referenced in API endpoints.
    pub id: String,

    /// If applicable, the ID of the
    /// [assistant](https://platform.openai.com/docs/api-reference/assistants) that
    /// authored this message.
    pub assistant_id: Option<String>,

    /// A list of files attached to the message, and the tools they were added to.
    pub attachments: Option<Vec<message::Attachment>>,

    /// The Unix timestamp (in seconds) for when the message was completed.
    pub completed_at: Option<u64>,

    /// The content of the message in array of text and/or images.
    pub content: Vec<MessageContent>,

    /// The Unix timestamp (in seconds) for when the message was created.
    pub created_at: u64,

    /// The Unix timestamp (in seconds) for when the message was marked as incomplete.
    pub incomplete_at: Option<u64>,

    /// On an incomplete message, details about why the message is incomplete.
    pub incomplete_details: Option<message::IncompleteDetails>,

    /// Set of 16 key-value pairs that can be attached to an object. This can be useful
    /// for storing additional information about the object in a structured format. Keys
    /// can be a maximum of 64 characters long and values can be a maxium of 512
    /// characters long.
    pub metadata: Option<Value>,

    /// The object type, which is always `thread.message`.
    pub object: message::Object,

    /// The entity that produced the message. One of `user` or `assistant`.
    pub role: message::Role,

    /// The ID of the [run](https://platform.openai.com/docs/api-reference/runs)
    /// associated with the creation of this message. Value is `null` when messages are
    /// created manually using the create message or create thread endpoints.
    pub run_id: Option<String>,

    /// The status of the message, which can be either `in_progress`, `incomplete`, or
    /// `completed`.
    pub status: Option<message::Status>,

    /// The [thread](https://platform.openai.com/docs/api-reference/threads) ID that
    /// this message belongs to.
    pub thread_id: String,
}

pub mod message {
    use super::*;

    #[derive(Default, Debug, Clone, Serialize, Deserialize)]
    pub struct Attachment {
        /// The ID of the file to attach to the message.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub file_id: Option<String>,

        /// The tools to add this file to.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub tools: Option<Vec<attachment::Tool>>,
    }

    pub mod attachment {
        use super::*;

        #[derive(Default, Debug, Clone, Serialize, Deserialize)]
        pub struct AssistantToolsFileSearchTypeOnly {
            /// The type of tool being defined: `file_search`
            #[serde(rename = "type")]
            pub kind: assistant_tools_file_search_type_only::Type,
        }

        pub mod assistant_tools_file_search_type_only {
            use super::*;

            #[derive(Default, Debug, Clone, Serialize, Deserialize)]
            #[serde(rename_all = "snake_case")]
            pub enum Type {
                #[default]
                FileSearch,
            }
        }

        #[derive(Debug, Clone, Serialize, Deserialize)]
        #[serde(untagged, rename_all = "snake_case")]
        pub enum Tool {
            CodeInterpreterTool(assistants_api::CodeInterpreterTool),
            AssistantToolsFileSearchTypeOnly(AssistantToolsFileSearchTypeOnly),
        }
    }

    /// On an incomplete message, details about why the message is incomplete.
    #[derive(Default, Debug, Clone, Serialize, Deserialize)]
    pub struct IncompleteDetails {
        /// The reason the message is incomplete.
        pub reason: incomplete_details::Reason,
    }

    pub mod incomplete_details {
        use super::*;

        #[derive(Default, Debug, Clone, Serialize, Deserialize)]
        #[serde(rename_all = "snake_case")]
        pub enum Reason {
            #[default]
            ContentFilter,
            MaxTokens,
            RunCancelled,
            RunExpired,
            RunFailed,
        }
    }

    #[derive(Default, Debug, Clone, Serialize, Deserialize)]
    #[serde(rename_all = "snake_case")]
    pub enum Role {
        #[default]
        User,
        Assistant,
    }

    #[derive(Default, Debug, Clone, Serialize, Deserialize)]
    pub enum Object {
        #[default]
        #[serde(rename = "thread.message")]
        ThreadMessage,
    }

    #[derive(Default, Debug, Clone, Serialize, Deserialize)]
    #[serde(rename_all = "snake_case")]
    pub enum Status {
        #[default]
        InProgress,
        Incomplete,
        Complete,
    }
}

/// References an image [File](https://platform.openai.com/docs/api-reference/files)
/// in the content of a message.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum MessageContent {
    ImageFile(ImageFile),
    ImageURL(ImageURL),
    Text{ text: Text },
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ChatCompletionContent {
    Text(String),
    Multiple(Vec<ChatCompletionContentPart>),
}

impl Default for MessageContent {
    fn default() -> Self {
        MessageContent::Text{ text: Text::default() }
    }
}

/// References an image [File](https://platform.openai.com/docs/api-reference/files)
/// in the content of a message.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged, rename_all = "snake_case")]
pub enum MessageContentDelta {
    ImageFileDeltaBlock(ImageFileDeltaBlock),
    TextDeltaBlock(TextDeltaBlock),
    ImageURLDeltaBlock(ImageURLDeltaBlock),
}

#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct MessageDeleted {
    pub id: String,
    pub deleted: bool,
    pub object: message_deleted::Object,
}

pub mod message_deleted {
    use super::*;

    #[derive(Default, Debug, Clone, Serialize, Deserialize)]
    #[serde(untagged, rename_all = "snake_case")]
    pub enum Object {
        #[serde(rename = "thread.message.deleted")]
        #[default]
        ThreadMessageDeleted
    }
}

/// The delta containing the fields that have changed on the Message.
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct MessageDelta {
    /// The content of the message in array of text and/or images.
    #[serde(skip_serializing_if = "Option::is_none")]
    content: Option<Vec<MessageContentDelta>>,

    /// The entity that produced the message. One of `user` or `assistant`.
    #[serde(skip_serializing_if = "Option::is_none")]
    role: Option<message_deleted::Object>,
}

pub mod message_delta {
    use super::*;

    #[derive(Default, Debug, Clone, Serialize, Deserialize)]
    #[serde(untagged, rename_all = "snake_case")]
    pub enum Role {
        #[default]
        User,
        Assistant,
    }
}

/// Represents a message delta i.e. any changed fields on a message during
/// streaming.
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct MessageDeltaEvent {
    /// The identifier of the message, which can be referenced in API endpoints.
    pub id: String,

    /// The delta containing the fields that have changed on the Message.
    pub delta: MessageDelta,

    /// The object type, which is always `thread.message.delta`.
    pub object: message_delta_event::Object,
}

pub mod message_delta_event {
    use super::*;

    #[derive(Default, Debug, Clone, Serialize, Deserialize)]
    #[serde(untagged, rename_all = "snake_case")]
    pub enum Object {
        #[serde(rename = "thread.message.delta")]
        #[default]
        ThreadMessageDelta
    }
}

#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct Text {
    pub annotations: Vec<Annotation>,

    /// The data that makes up the text.
    pub value: String,
}

pub mod text_content_block {
    use super::*;

    #[derive(Default, Debug, Clone, Serialize, Deserialize)]
    #[serde(rename_all = "snake_case")]
    pub enum Type {
        #[default]
        Text,
    }
}

/// The text content that is part of a message.
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct TextContentBlockParam {
    /// Text content to be sent to the model
    pub text: String,

    /// Always `text`.
    #[serde(rename = "type")]
    pub kind: text_content_block_param::Type,
}

pub mod text_content_block_param {
    use super::*;

    #[derive(Default, Debug, Clone, Serialize, Deserialize)]
    #[serde(rename_all = "snake_case")]
    pub enum Type {
        #[default]
        Text,
    }
}

#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct TextDelta {
    #[serde(skip_serializing_if = "Option::is_none")]
    annotations: Option<Vec<AnnotationDelta>>,

    /// The data that makes up the text.
    #[serde(skip_serializing_if = "Option::is_none")]
    value: Option<String>,
}

/// The text content that is part of a message.
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct TextDeltaBlock {
    /// The index of the content part in the message.
    pub index: u32,

    /// Always `text`.
    #[serde(rename = "type")]
    pub kind: text_delta_block::Type,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<TextDelta>,
}

pub mod text_delta_block {
    use super::*;

    #[derive(Default, Debug, Clone, Serialize, Deserialize)]
    #[serde(rename_all = "snake_case")]
    pub enum Type {
        #[default]
        Text,
    }
}

#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct MessageCreateParams {
    /// The text contents of the message.
    pub content: message_create_params::Content,

    /// The role of the entity that is creating the message. Allowed values include:
    ///
    /// - `user`: Indicates the message is sent by an actual user and should be used in
    ///   most cases to represent user-generated messages.
    /// - `assistant`: Indicates the message is generated by the assistant. Use this
    ///   value to insert messages from the assistant into the conversation.
    pub role: message_create_params::Role,

    /// A list of files attached to the message, and the tools they should be added to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attachments: Option<Vec<message_create_params::Attachment>>,

    /// Set of 16 key-value pairs that can be attached to an object. This can be useful
    /// for storing additional information about the object in a structured format. Keys
    /// can be a maximum of 64 characters long and values can be a maxium of 512
    /// characters long.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
}

pub mod message_create_params {
    use super::*;

    #[derive(Debug, Clone, Serialize, Deserialize)]
    #[serde(untagged)]
    pub enum Content {
        Text(String),
        Multiple(Vec<MessageContent>),
    }

    impl Default for Content {
        fn default() -> Self {
            Content::Text(String::default())
        }
    }

    #[derive(Default, Debug, Clone, Serialize, Deserialize)]
    #[serde(rename_all = "snake_case")]
    pub enum Role {
        #[default]
        User,
        Assistant,
    }

    #[derive(Default, Debug, Clone, Serialize, Deserialize)]
    pub struct Attachment {
        /// The ID of the file to attach to the message.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub file_id: Option<String>,

        /// The tools to add this file to.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub tools: Option<Vec<attachment::Tool>>,
    }

    pub mod attachment {
        use super::*;

        #[derive(Default, Debug, Clone, Serialize, Deserialize)]
        pub struct FileSearch {
            /// The type of tool being defined: `file_search`
            #[serde(rename = "type")]
            pub kind: file_search::Type,
        }

        pub mod file_search {
            use super::*;

            #[derive(Default, Debug, Clone, Serialize, Deserialize)]
            #[serde(rename_all = "snake_case")]
            pub enum Type {
                #[default]
                FileSearch,
            }
        }

        #[derive(Debug, Clone, Serialize, Deserialize)]
        #[serde(untagged, rename_all = "snake_case")]
        pub enum Tool {
            CodeInterpreterTool(assistants_api::CodeInterpreterTool),
            FileSearch(FileSearch),
        }
    }
}

#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct MessageUpdateParams {
    /// Set of 16 key-value pairs that can be attached to an object. This can be useful
    /// for storing additional information about the object in a structured format. Keys
    /// can be a maximum of 64 characters long and values can be a maxium of 512
    /// characters long.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
}

#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct MessageListParams { // extends CursorPageParams
    /// A cursor for use in pagination. `before` is an object ID that defines your place
    /// in the list. For instance, if you make a list request and receive 100 objects,
    /// ending with obj_foo, your subsequent call can include before=obj_foo in order to
    /// fetch the previous page of the list.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub before: Option<String>,

    /// Sort order by the `created_at` timestamp of the objects. `asc` for ascending
    /// order and `desc` for descending order.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order: Option<message_list_params::Order>,

    /// Filter messages by the run ID that generated them.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub run_id: Option<String>,
}

pub mod message_list_params {
    use super::*;

    #[derive(Default, Debug, Clone, Serialize, Deserialize)]
    #[serde(untagged, rename_all = "snake_case")]
    pub enum Order {
        #[default]
        Asc,
        Desc,
    }

}

#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(untagged, rename_all = "snake_case")]
pub enum Detail {
    #[default]
    Auto,
    Low,
    High,
}