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
use serde::{Deserialize, Serialize};
pub mod request;
#[allow(unused_imports)]
pub use request::*;
pub mod response;
#[allow(unused_imports)]
pub use response::*;
pub mod stream_response;
#[allow(unused_imports)]
pub use stream_response::*;

#[derive(Debug, Deserialize, Clone, PartialEq, Serialize)]
pub struct Message {
    pub role: Role,
    pub content: MessageContent,
}

impl Message {
    //return true if text or all blocks are empty or only contain white spaces
    pub fn is_all_empty(&self) -> bool {
        self.content.is_all_empty()
    }
}

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

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

impl MessageContent {
    pub fn is_all_empty(&self) -> bool {
        match self {
            MessageContent::Text(s) => s.trim().is_empty(),
            MessageContent::Blocks(blocks) => {
                if blocks.is_empty() {
                    return true;
                }
                for block in blocks {
                    if !block.is_empty() {
                        return false;
                    }
                }
                true
            }
        }
    }
}

#[derive(Debug, Deserialize, Clone, PartialEq, Serialize)]
#[serde(tag = "type")]
pub enum ContentBlock {
    #[serde(rename = "text")]
    Text { text: String },
    #[serde(rename = "image")]
    Image { source: ImageSource },
    #[serde(rename = "text_delta")]
    TextDelta { text: String },
}

impl ContentBlock {
    pub fn is_empty(&self) -> bool {
        match self {
            ContentBlock::Text { text } => text.trim().is_empty(),
            ContentBlock::Image { source } => match source {
                ImageSource::Base64 { media_type, data } => {
                    media_type.trim().is_empty() || data.trim().is_empty()
                }
            },
            ContentBlock::TextDelta { text } => text.trim().is_empty(),
        }
    }
}

#[derive(Debug, Deserialize, Clone, PartialEq, Serialize)]
#[serde(tag = "type")]
pub enum ImageSource {
    #[serde(rename = "base64")]
    Base64 { media_type: String, data: String },
}

#[derive(Debug, Deserialize, Clone, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum StopReason {
    EndTurn,
    MaxTokens,
    StopSequence,
}

#[derive(Debug, Deserialize, Default, Clone, PartialEq, Serialize)]
pub struct Usage {
    pub input_tokens: Option<usize>,
    pub output_tokens: usize,
}