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
use crate::models::{LogitBias, Model, Role};
use log::debug;
use reqwest::{Client, StatusCode};
use serde::{Deserialize, Serialize};
use std::fmt;

/// Main ChatGPTClient struct.
pub struct ChatGPTClient {
    base_url: String,
    api_key: String,
    client: Client,
}

/// Represents the input for the chat API call.
#[derive(Debug, Serialize)]
pub struct ChatInput {
    pub model: Model,
    pub messages: Vec<Message>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_p: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub n: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stream: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_tokens: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub presence_penalty: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub frequency_penalty: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub logit_bias: Option<LogitBias>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user: Option<String>,
}

impl Default for ChatInput {
    fn default() -> Self {
        Self {
            model: Model::Gpt_4,  // Set the default model
            messages: Vec::new(), // Set an empty vector for messages
            temperature: None,
            top_p: None,
            n: None,
            stream: None,
            stop: None,
            max_tokens: None,
            presence_penalty: None,
            frequency_penalty: None,
            logit_bias: None,
            user: None,
        }
    }
}

/// Represents the response from the chat API call.
#[derive(Debug, Deserialize)]
pub struct ChatResponse {
    pub id: String,
    pub object: String,
    pub created: i64,
    pub model: String,
    pub usage: Usage,
    pub choices: Vec<Choice>,
}

/// Represents the usage information in the chat API response.
#[derive(Debug, Deserialize)]
pub struct Usage {
    pub prompt_tokens: i64,
    pub completion_tokens: i64,
    pub total_tokens: i64,
}

/// Represents a choice in the chat API response.
#[derive(Debug, Deserialize)]
pub struct Choice {
    pub message: Message,
    pub finish_reason: String,
}

/// Represents a message in the chat API call.
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Message {
    pub role: Role,
    pub content: String,
}

/// Enum representing possible errors in the ChatGPTClient.
#[derive(Debug)]
pub enum ChatGPTError {
    RequestFailed(String),
    Reqwest(reqwest::Error),
}

impl fmt::Display for ChatGPTError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ChatGPTError::RequestFailed(message) => write!(f, "{message}"),
            ChatGPTError::Reqwest(error) => write!(f, "Reqwest error: {error}"),
        }
    }
}

impl std::error::Error for ChatGPTError {}

impl From<reqwest::Error> for ChatGPTError {
    fn from(error: reqwest::Error) -> Self {
        ChatGPTError::Reqwest(error)
    }
}

impl ChatGPTClient {
    /// Creates a new ChatGPTClient with the given API key and base URL.
    ///
    /// # Arguments
    ///
    /// * `api_key` - The API key for the ChatGPT API.
    /// * `base_url` - The base URL for the ChatGPT API.
    pub fn new(api_key: &str, base_url: &str) -> Self {
        Self {
            base_url: base_url.to_string(),
            api_key: api_key.to_string(),
            client: Client::new(),
        }
    }

    /// Sends a request to the ChatGPT API with the given input and returns the response.
    ///
    /// # Arguments
    ///
    /// * `input` - A ChatInput struct representing the input for the chat API call.
    ///
    /// # Examples
    ///
    /// ```
    /// use chat_gpt_lib_rs::{ChatGPTClient, ChatInput, Message, Model, Role};
    ///
    /// async fn example() {
    ///     let chat_gpt = ChatGPTClient::new("your_api_key", "https://api.openai.com");
    ///     let input = ChatInput {
    ///         model: Model::Gpt_4,
    ///         messages: vec![
    ///             Message {
    ///                 role: Role::System,
    ///                 content: "You are a helpful assistant.".to_string(),
    ///             },
    ///             Message {
    ///                 role: Role::User,
    ///                 content: "Who is the best field hockey player in the world".to_string(),
    ///             },
    ///         ],
    ///         ..Default::default()
    ///     };
    ///
    ///     let response = chat_gpt.chat(input).await.unwrap();
    /// }
    /// ```
    /// # Errors
    ///
    /// Returns a ChatGPTError if the request fails.
    pub async fn chat(&self, input: ChatInput) -> Result<ChatResponse, ChatGPTError> {
        let url = format!("{}/v1/chat/completions", self.base_url);
        let response = self
            .client
            .post(&url)
            .header("Authorization", format!("Bearer {}", self.api_key))
            .json(&input)
            .send()
            .await?;

        debug!(
            "API call to url: {}\n with json payload: {:?}",
            &url, &input
        );

        // Check if the status code is 200
        if response.status() == StatusCode::OK {
            response
                .json::<ChatResponse>()
                .await
                .map_err(ChatGPTError::from)
        } else {
            let status_code = response.status();
            let headers = response.headers().clone();
            let body = response.text().await?;

            let error_message = format!(
                "Request failed with status code: {status_code}\nHeaders: {headers:?}\nBody: {body}"
            );
            Err(ChatGPTError::RequestFailed(error_message))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Helper function to create a ChatGPTClient instance with a dummy API key and base URL
    fn create_dummy_client() -> ChatGPTClient {
        ChatGPTClient::new("dummy_api_key", "https://dummy-api-url.com")
    }

    #[tokio::test]
    async fn test_chat_gpt_client_new() {
        let client = create_dummy_client();
        assert_eq!(client.api_key, "dummy_api_key");
        assert_eq!(client.base_url, "https://dummy-api-url.com");
    }

    #[tokio::test]
    async fn test_chat_gpt_client_chat() {
        // Please note that this test will not actually make an API call to OpenAI,
        // but it will test the error handling of the `chat` function.
        let client = create_dummy_client();

        let input = ChatInput {
            model: Model::Gpt_4,
            messages: vec![
                Message {
                    role: Role::System,
                    content: "You are a helpful assistant.".to_string(),
                },
                Message {
                    role: Role::User,
                    content: "Who is the best field hockey player in the world?".to_string(),
                },
            ],
            ..Default::default()
        };

        let result = client.chat(input).await;
        assert!(result.is_err());
    }

    #[test]
    fn test_usage_struct() {
        let usage = Usage {
            prompt_tokens: 10,
            completion_tokens: 20,
            total_tokens: 30,
        };

        assert_eq!(usage.prompt_tokens, 10);
        assert_eq!(usage.completion_tokens, 20);
        assert_eq!(usage.total_tokens, 30);
    }

    #[test]
    fn test_choice_struct() {
        let choice = Choice {
            message: Message {
                role: Role::Assistant,
                content: "Sample response".to_string(),
            },
            finish_reason: "stop".to_string(),
        };

        assert_eq!(choice.message.role, Role::Assistant);
        assert_eq!(choice.message.content, "Sample response");
        assert_eq!(choice.finish_reason, "stop");
    }
}