aipim 0.1.1

AIPIM is a Rust library designed to provide a unified interface for interacting with various AI providers. It abstracts the complexities of different AI APIs, allowing developers to easily switch between providers without changing their codebase.
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
#![allow(unused)]
use async_trait::async_trait;
use log::{debug, trace};
use reqwest::Client;
use serde::{Deserialize, Serialize};

use crate::client;

use super::AIProvider;

const MAX_TOKENS: u32 = 4096;
const BASE_URL: &str = "https://api.openai.com/v1/";
const MODELS: &[&str] = &["gpt-4o", "gpt-4-turbo", "gpt-4", "gpt-3.5-turbo"];

/// Represents an OpenAI client for interacting with the OpenAI API.
pub struct OpenAI {
    client: Client,
    api_key: String,
    model: String,
}

impl OpenAI {
    /// Creates a new `OpenAI` instance.
    ///
    /// # Arguments
    ///
    /// * `api_key` - A string slice that holds the API key.
    /// * `model` - A string slice that holds the name of the model.
    ///
    pub fn new(api_key: impl Into<String>, model: impl Into<String>) -> Self {
        Self {
            client: Client::new(),
            api_key: api_key.into(),
            model: model.into(),
        }
    }

    /// Sets the model for the `OpenAI` instance.
    ///
    /// # Arguments
    ///
    /// * `model` - A string slice that holds the name of the model.
    ///
    pub fn with_model(self, model: impl Into<String>) -> Self {
        Self {
            model: model.into(),
            ..self
        }
    }
}

impl Default for OpenAI {
    fn default() -> Self {
        Self::new(
            std::env::var("OPENAI_API_KEY").expect("OPENAI_API_KEY is not set"),
            MODELS[0],
        )
    }
}

#[async_trait]
impl AIProvider for OpenAI {
    /// Sends a message to the OpenAI API.
    ///
    /// # Arguments
    ///
    /// * `message` - A `client::Message` instance containing the message to be sent.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or the response contains an error.
    ///
    async fn send_message(&self, message: client::Message) -> anyhow::Result<client::Response> {
        let mut content = Content::Complex(vec![ComplexContent::Text(Text {
            typ: "text".to_string(),
            text: message.text,
        })]);

        for image in message.images.unwrap_or_default() {
            content.push(ComplexContent::Image(Image {
                typ: "image_url".to_string(),
                image_url: ImageUrl {
                    url: format!("data:image/jpeg;base64,{}", image.data),
                },
            }));
        }

        let chat_message = ChatMessage {
            role: "user".to_string(),
            content,
        };

        let request = Request {
            model: self.model.clone(),
            messages: vec![chat_message],
            max_tokens: MAX_TOKENS as usize,
        };

        trace!(
            "JSON Request: {}",
            serde_json::to_string_pretty(&request).unwrap()
        );

        let response = self
            .client
            .post(&format!("{}chat/completions", BASE_URL))
            .header("Authorization", &format!("Bearer {}", self.api_key))
            .json(&request)
            .send()
            .await?;

        let response: serde_json::Value = response.json().await?;
        trace!(
            "JSON Response: {}",
            serde_json::to_string_pretty(&response).unwrap()
        );

        let response = serde_json::from_value::<Response>(response)?;
        debug!("OpenAI Response: {:#?}", response);

        match response {
            Response::Message(message) => {
                let content = &message.choices[0].message.content;
                let text = content.as_text().ok_or_else(|| {
                    anyhow::anyhow!("unsupported response content type: {:?}", content)
                })?;

                Ok(client::Response::new(text))
            }
            Response::Error { error } => {
                let code = if let Some(code) = error.code {
                    format!("{}: ", code)
                } else {
                    "".to_string()
                };
                Err(anyhow::anyhow!(
                    "{}{} ({})",
                    code,
                    error.message,
                    error.param
                ))
            }
        }
    }
}

unsafe impl Send for OpenAI {}
unsafe impl Sync for OpenAI {}

#[derive(Serialize, Debug)]
/// Represents a request to the OpenAI API.
struct Request {
    model: String,
    messages: Vec<ChatMessage>,
    max_tokens: usize,
}

#[derive(Serialize, Deserialize, Debug)]
/// Represents a chat message to be sent to the OpenAI API.
struct ChatMessage {
    role: String,
    content: Content,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
/// Represents the content of a chat message.
enum Content {
    Simple(String),
    Complex(Vec<ComplexContent>),
}

impl Content {
    pub fn as_text(&self) -> Option<&str> {
        match self {
            Content::Simple(text) => Some(text),
            _ => None,
        }
    }

    pub fn push(&mut self, content: ComplexContent) {
        if let Content::Complex(vec) = self {
            vec.push(content);
        }
    }
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(tag = "type")]
/// Represents complex content types for a chat message.
enum ComplexContent {
    Text(Text),
    Image(Image),
}

#[derive(Serialize, Deserialize, Debug)]
/// Represents text content for a chat message.
struct Text {
    text: String,
    #[serde(rename = "type")]
    typ: String,
}

#[derive(Serialize, Deserialize, Debug)]
/// Represents image content for a chat message.
struct Image {
    image_url: ImageUrl,
    #[serde(rename = "type")]
    typ: String,
}

#[derive(Serialize, Deserialize, Debug)]
/// Represents the URL of an image.
struct ImageUrl {
    url: String,
}

#[derive(Deserialize, Debug)]
#[serde(untagged)]
/// Represents a response from the OpenAI API.
enum Response {
    Message(Message),
    Error { error: Error },
}

#[derive(Deserialize, Debug)]
/// Represents a message in the response from the OpenAI API.
struct Message {
    id: String,
    object: String,
    created: i64,
    model: String,
    system_fingerprint: String,
    choices: Vec<Choice>,
    usage: Usage,
}

#[derive(Deserialize, Debug)]
/// Represents an error in the response from the OpenAI API.
struct Error {
    code: Option<String>,
    message: String,
    param: String,
    #[serde(rename = "type")]
    typ: String,
}

#[derive(Deserialize, Debug)]
/// Represents a choice in the response from the OpenAI API.
struct Choice {
    index: usize,
    message: ChatMessage,
    logprobs: Option<bool>,
    finish_reason: String,
}

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

#[cfg(test)]
/// Unit tests for the OpenAI module.
mod tests {
    use super::*;

    #[test]
    /// Tests parsing a successful response from the OpenAI API.
    fn test_parse() {
        let res = r#"
        {
          "choices": [
            {
              "finish_reason": "length",
              "index": 0,
              "logprobs": null,
              "message": {
                "content": "response",
                "role": "assistant"
              }
            }
          ],
          "created": 1719328775,
          "id": "chatcmpl-9e2FDY8pjRfZqufnqa4XSu5f26aUy",
          "model": "gpt-4o-2024-05-13",
          "object": "chat.completion",
          "system_fingerprint": "fp_8c6b918852",
          "usage": {
            "completion_tokens": 1024,
            "prompt_tokens": 1563,
            "total_tokens": 2587
          }
        }
        "#;
        let response = serde_json::from_str::<Response>(res).unwrap();
        println!("{:#?}", response);
    }

    #[test]
    /// Tests parsing an error response from the OpenAI API.
    fn test_parse_error() {
        let error = r#"
            {
              "error": {
                "code": null,
                "message": "Invalid content type. image_url is only supported by certain models.",
                "param": "messages.[0].content.[1].type",
                "type": "invalid_request_error"
              }
            }
        "#;
        let response = serde_json::from_str::<Response>(error).unwrap();
        let Response::Error { error } = response else {
            panic!("expected error response, got: {:?}", response);
        };
        assert!(error.code.is_none());
    }

    #[test]
    /// Tests the `as_text` method of the `Content` enum.
    fn test_as_text() {
        let simple = Content::Simple("text".to_string());
        assert_eq!(simple.as_text(), Some("text"));

        let complex = Content::Complex(vec![ComplexContent::Text(Text {
            typ: "text".to_string(),
            text: "text".to_string(),
        })]);
        assert_eq!(complex.as_text(), None);
    }

    #[test]
    /// Tests creating a new `OpenAI` instance.
    fn test_openai_new() {
        let api_key = "test_api_key";
        let model = "gpt-3.5-turbo";
        let openai = OpenAI::new(api_key, model);
        assert_eq!(openai.api_key, api_key);
        assert_eq!(openai.model, model);
    }

    #[test]
    /// Tests setting the model for an `OpenAI` instance.
    fn test_openai_with_model() {
        let api_key = "test_api_key";
        let model = "gpt-3.5-turbo";
        let new_model = "gpt-4";
        let openai = OpenAI::new(api_key, model).with_model(new_model);
        assert_eq!(openai.model, new_model);
    }

    #[test]
    /// Tests pushing content to a `Content` instance.
    fn test_content_push() {
        let mut content = Content::Complex(vec![ComplexContent::Text(Text {
            typ: "text".to_string(),
            text: "initial text".to_string(),
        })]);
        content.push(ComplexContent::Image(Image {
            typ: "image_url".to_string(),
            image_url: ImageUrl {
                url: "http://example.com/image.jpg".to_string(),
            },
        }));
        if let Content::Complex(vec) = content {
            assert_eq!(vec.len(), 2);
        } else {
            panic!("Content is not complex");
        }
    }

    #[test]
    /// Tests parsing a message response from the OpenAI API.
    fn test_response_message() {
        let res = r#"
        {
          "choices": [
            {
              "finish_reason": "length",
              "index": 0,
              "logprobs": null,
              "message": {
                "content": "response",
                "role": "assistant"
              }
            }
          ],
          "created": 1719328775,
          "id": "chatcmpl-9e2FDY8pjRfZqufnqa4XSu5f26aUy",
          "model": "gpt-4o-2024-05-13",
          "object": "chat.completion",
          "system_fingerprint": "fp_8c6b918852",
          "usage": {
            "completion_tokens": 1024,
            "prompt_tokens": 1563,
            "total_tokens": 2587
          }
        }
        "#;
        let response = serde_json::from_str::<Response>(res).unwrap();
        if let Response::Message(message) = response {
            assert_eq!(
                message.choices[0].message.content.as_text(),
                Some("response")
            );
        } else {
            panic!("Response is not a message");
        }
    }

    #[test]
    /// Tests parsing an error response with a code from the OpenAI API.
    fn test_response_error_with_code() {
        let error = r#"
            {
              "error": {
                "code": "invalid_request_error",
                "message": "Invalid content type. image_url is only supported by certain models.",
                "param": "messages.[0].content.[1].type",
                "type": "invalid_request_error"
              }
            }
        "#;
        let response = serde_json::from_str::<Response>(error).unwrap();
        let Response::Error { error } = response else {
            panic!("expected error response, got: {:?}", response);
        };
        assert_eq!(error.code, Some("invalid_request_error".to_string()));
    }
}