paladin-ai-core 0.5.1

Pure domain types for the Paladin framework — zero infrastructure dependencies
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
//! Vision content types for multi-modal AI agent processing.
//!
//! This module provides data structures for handling image inputs in Paladin agents,
//! supporting multiple image formats and quality levels for vision-capable LLM providers.

use serde::{Deserialize, Serialize};
use std::path::PathBuf;

/// Quality/detail level for image processing.
///
/// Controls the level of detail the vision model should use when analyzing an image.
/// Different providers may interpret these levels differently.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum ImageDetail {
    /// Let the model automatically decide the appropriate detail level.
    #[default]
    Auto,
    /// Lower detail, faster processing, lower cost.
    Low,
    /// Higher detail, slower processing, higher cost but more accurate analysis.
    High,
}

/// Vision content variants for different image input methods.
///
/// Supports three ways to provide images to vision-capable models:
/// - URL reference to a publicly accessible image
/// - Base64-encoded image data
/// - Local file path to an image file
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum VisionContent {
    /// Reference to a publicly accessible image URL.
    ImageUrl {
        /// The URL of the image.
        url: String,
        /// Detail level for processing.
        #[serde(default)]
        detail: ImageDetail,
    },
    /// Base64-encoded image data.
    ImageBase64 {
        /// Base64-encoded image data.
        data: String,
        /// MIME type of the image (e.g., "image/png", "image/jpeg").
        media_type: String,
        /// Detail level for processing.
        #[serde(default)]
        detail: ImageDetail,
    },
    /// Path to a local image file.
    ImageFile {
        /// Path to the image file.
        path: PathBuf,
        /// Detail level for processing.
        #[serde(default)]
        detail: ImageDetail,
    },
}

impl VisionContent {
    /// Validates that the image format is supported.
    ///
    /// Supported formats: PNG, JPEG, GIF, WebP
    ///
    /// # Errors
    ///
    /// Returns `VisionError::UnsupportedFormat` if the format is not supported.
    pub fn validate_format(&self) -> Result<(), VisionError> {
        match self {
            VisionContent::ImageUrl { url, .. } => {
                let url_lower = url.to_lowercase();
                if url_lower.ends_with(".png")
                    || url_lower.ends_with(".jpg")
                    || url_lower.ends_with(".jpeg")
                    || url_lower.ends_with(".gif")
                    || url_lower.ends_with(".webp")
                {
                    Ok(())
                } else {
                    Err(VisionError::UnsupportedFormat(
                        "URL must end with .png, .jpg, .jpeg, .gif, or .webp".to_string(),
                    ))
                }
            }
            VisionContent::ImageBase64 { media_type, .. } => {
                if media_type == "image/png"
                    || media_type == "image/jpeg"
                    || media_type == "image/gif"
                    || media_type == "image/webp"
                {
                    Ok(())
                } else {
                    Err(VisionError::UnsupportedFormat(format!(
                        "Unsupported media type: {}. Supported: image/png, image/jpeg, image/gif, image/webp",
                        media_type
                    )))
                }
            }
            VisionContent::ImageFile { path, .. } => {
                if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
                    let ext_lower = ext.to_lowercase();
                    if ext_lower == "png"
                        || ext_lower == "jpg"
                        || ext_lower == "jpeg"
                        || ext_lower == "gif"
                        || ext_lower == "webp"
                    {
                        Ok(())
                    } else {
                        Err(VisionError::UnsupportedFormat(format!(
                            "Unsupported file extension: {}. Supported: png, jpg, jpeg, gif, webp",
                            ext
                        )))
                    }
                } else {
                    Err(VisionError::UnsupportedFormat(
                        "File has no extension".to_string(),
                    ))
                }
            }
        }
    }
}

/// A vision request combining text and images.
///
/// This is the primary structure for multi-modal requests to vision-capable LLMs.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct VisionRequest {
    /// The text prompt or question about the images.
    pub text: String,
    /// Vector of images to analyze.
    pub images: Vec<VisionContent>,
}

impl VisionRequest {
    /// Creates a new vision request with validation.
    ///
    /// # Errors
    ///
    /// Returns `VisionError` if any image format is invalid or if the request is empty.
    pub fn new(text: String, images: Vec<VisionContent>) -> Result<Self, VisionError> {
        if text.is_empty() {
            return Err(VisionError::InvalidRequest(
                "Text prompt cannot be empty".to_string(),
            ));
        }

        if images.is_empty() {
            return Err(VisionError::InvalidRequest(
                "At least one image is required".to_string(),
            ));
        }

        // Validate all image formats
        for image in &images {
            image.validate_format()?;
        }

        Ok(Self { text, images })
    }

    /// Validates the vision request.
    pub fn validate(&self) -> Result<(), VisionError> {
        if self.text.is_empty() {
            return Err(VisionError::InvalidRequest(
                "Text prompt cannot be empty".to_string(),
            ));
        }

        if self.images.is_empty() {
            return Err(VisionError::InvalidRequest(
                "At least one image is required".to_string(),
            ));
        }

        for image in &self.images {
            image.validate_format()?;
        }

        Ok(())
    }
}

/// Vision-specific errors.
#[derive(Debug, thiserror::Error)]
pub enum VisionError {
    /// Unsupported image format.
    #[error("Unsupported image format: {0}")]
    UnsupportedFormat(String),

    /// Image file is too large.
    #[error("Image file too large: {size} bytes (max: {max})")]
    FileTooLarge { size: usize, max: usize },

    /// Invalid image data.
    #[error("Invalid image data: {0}")]
    InvalidImage(String),

    /// Model does not support vision.
    #[error("Model does not support vision: {0}")]
    ModelNotSupported(String),

    /// Network error.
    #[error("Network error: {0}")]
    NetworkError(String),

    /// Encryption error.
    #[error("Encryption error: {0}")]
    EncryptionError(String),

    /// Invalid request.
    #[error("Invalid vision request: {0}")]
    InvalidRequest(String),

    /// Authentication error (401, invalid API key).
    #[error("Authentication error: {0}")]
    AuthenticationError(String),

    /// Rate limit exceeded (429, too many requests).
    #[error("Rate limit exceeded: {0}")]
    RateLimitExceeded(String),

    /// Provider-specific error (5xx server errors).
    #[error("Provider error: {0}")]
    ProviderError(String),

    /// Request timeout.
    #[error("Request timeout after {0} seconds")]
    Timeout(u64),

    /// Unsupported vision provider.
    #[error("Unsupported vision provider: {0}")]
    UnsupportedProvider(String),

    /// Maximum retry attempts exceeded.
    #[error("Maximum retry attempts exceeded: {0} attempts")]
    MaxRetriesExceeded(u32),

    /// IO error.
    #[error("IO error: {0}")]
    IoError(#[from] std::io::Error),
}

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

    #[test]
    fn test_image_detail_enum() {
        // Test all variants
        let auto = ImageDetail::Auto;
        let low = ImageDetail::Low;
        let high = ImageDetail::High;

        assert_eq!(auto, ImageDetail::Auto);
        assert_eq!(low, ImageDetail::Low);
        assert_eq!(high, ImageDetail::High);

        // Test default
        assert_eq!(ImageDetail::default(), ImageDetail::Auto);

        // Test serialization/deserialization
        let json = serde_json::to_string(&auto).unwrap();
        assert_eq!(json, "\"auto\"");
        let deserialized: ImageDetail = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized, auto);
    }

    #[test]
    fn test_vision_content_validation() {
        // Valid PNG URL
        let valid_png = VisionContent::ImageUrl {
            url: "https://example.com/image.png".to_string(),
            detail: ImageDetail::Auto,
        };
        assert!(valid_png.validate_format().is_ok());

        // Valid JPEG URL
        let valid_jpg = VisionContent::ImageUrl {
            url: "https://example.com/photo.jpg".to_string(),
            detail: ImageDetail::Low,
        };
        assert!(valid_jpg.validate_format().is_ok());

        // Valid GIF URL
        let valid_gif = VisionContent::ImageUrl {
            url: "https://example.com/animation.gif".to_string(),
            detail: ImageDetail::High,
        };
        assert!(valid_gif.validate_format().is_ok());

        // Valid WebP URL
        let valid_webp = VisionContent::ImageUrl {
            url: "https://example.com/image.webp".to_string(),
            detail: ImageDetail::Auto,
        };
        assert!(valid_webp.validate_format().is_ok());

        // Invalid format URL
        let invalid_url = VisionContent::ImageUrl {
            url: "https://example.com/document.pdf".to_string(),
            detail: ImageDetail::Auto,
        };
        assert!(invalid_url.validate_format().is_err());
    }

    #[test]
    fn test_vision_content_base64_validation() {
        // Valid base64 PNG
        let valid_base64 = VisionContent::ImageBase64 {
            data: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==".to_string(),
            media_type: "image/png".to_string(),
            detail: ImageDetail::Auto,
        };
        assert!(valid_base64.validate_format().is_ok());

        // Invalid media type
        let invalid_media = VisionContent::ImageBase64 {
            data: "base64data".to_string(),
            media_type: "image/bmp".to_string(),
            detail: ImageDetail::Auto,
        };
        assert!(invalid_media.validate_format().is_err());
    }

    #[test]
    fn test_vision_content_file_validation() {
        // Valid file paths
        let valid_png = VisionContent::ImageFile {
            path: PathBuf::from("/path/to/image.png"),
            detail: ImageDetail::Auto,
        };
        assert!(valid_png.validate_format().is_ok());

        let valid_jpg = VisionContent::ImageFile {
            path: PathBuf::from("/path/to/photo.jpeg"),
            detail: ImageDetail::Auto,
        };
        assert!(valid_jpg.validate_format().is_ok());

        // Invalid file extension
        let invalid_file = VisionContent::ImageFile {
            path: PathBuf::from("/path/to/document.txt"),
            detail: ImageDetail::Auto,
        };
        assert!(invalid_file.validate_format().is_err());

        // No extension
        let no_ext = VisionContent::ImageFile {
            path: PathBuf::from("/path/to/file"),
            detail: ImageDetail::Auto,
        };
        assert!(no_ext.validate_format().is_err());
    }

    #[test]
    fn test_vision_request_creation() {
        let images = vec![VisionContent::ImageUrl {
            url: "https://example.com/image.png".to_string(),
            detail: ImageDetail::Auto,
        }];

        let request = VisionRequest::new("Describe this image".to_string(), images);
        assert!(request.is_ok());

        let request = request.unwrap();
        assert_eq!(request.text, "Describe this image");
        assert_eq!(request.images.len(), 1);
    }

    #[test]
    fn test_vision_request_empty_text() {
        let images = vec![VisionContent::ImageUrl {
            url: "https://example.com/image.png".to_string(),
            detail: ImageDetail::Auto,
        }];

        let request = VisionRequest::new("".to_string(), images);
        assert!(request.is_err());
        match request {
            Err(VisionError::InvalidRequest(msg)) => {
                assert!(msg.contains("Text prompt cannot be empty"));
            }
            _ => panic!("Expected InvalidRequest error"),
        }
    }

    #[test]
    fn test_vision_request_no_images() {
        let request = VisionRequest::new("Describe this".to_string(), vec![]);
        assert!(request.is_err());
        match request {
            Err(VisionError::InvalidRequest(msg)) => {
                assert!(msg.contains("At least one image is required"));
            }
            _ => panic!("Expected InvalidRequest error"),
        }
    }

    #[test]
    fn test_vision_request_multiple_images() {
        let images = vec![
            VisionContent::ImageUrl {
                url: "https://example.com/image1.png".to_string(),
                detail: ImageDetail::Auto,
            },
            VisionContent::ImageUrl {
                url: "https://example.com/image2.jpg".to_string(),
                detail: ImageDetail::Low,
            },
            VisionContent::ImageFile {
                path: PathBuf::from("/local/image.gif"),
                detail: ImageDetail::High,
            },
        ];

        let request = VisionRequest::new("Compare these images".to_string(), images);
        assert!(request.is_ok());

        let request = request.unwrap();
        assert_eq!(request.images.len(), 3);
    }

    #[test]
    fn test_vision_request_invalid_format() {
        let images = vec![VisionContent::ImageUrl {
            url: "https://example.com/document.pdf".to_string(),
            detail: ImageDetail::Auto,
        }];

        let request = VisionRequest::new("Describe this".to_string(), images);
        assert!(request.is_err());
        match request {
            Err(VisionError::UnsupportedFormat(_)) => {
                // Expected
            }
            _ => panic!("Expected UnsupportedFormat error"),
        }
    }

    #[test]
    fn test_vision_error_variants() {
        // Test AuthenticationError
        let auth_err = VisionError::AuthenticationError("Invalid API key".to_string());
        assert!(auth_err.to_string().contains("Authentication error"));
        assert!(auth_err.to_string().contains("Invalid API key"));

        // Test RateLimitExceeded
        let rate_err = VisionError::RateLimitExceeded("Too many requests".to_string());
        assert!(rate_err.to_string().contains("Rate limit exceeded"));
        assert!(rate_err.to_string().contains("Too many requests"));

        // Test ProviderError
        let provider_err = VisionError::ProviderError("Internal server error".to_string());
        assert!(provider_err.to_string().contains("Provider error"));
        assert!(provider_err.to_string().contains("Internal server error"));

        // Test Timeout
        let timeout_err = VisionError::Timeout(30);
        assert!(timeout_err.to_string().contains("timeout"));
        assert!(timeout_err.to_string().contains("30"));

        // Test UnsupportedProvider
        let unsupported_err = VisionError::UnsupportedProvider("unknown-provider".to_string());
        assert!(
            unsupported_err
                .to_string()
                .contains("Unsupported vision provider")
        );
        assert!(unsupported_err.to_string().contains("unknown-provider"));

        // Test MaxRetriesExceeded
        let max_retries_err = VisionError::MaxRetriesExceeded(3);
        assert!(
            max_retries_err
                .to_string()
                .contains("Maximum retry attempts exceeded")
        );
        assert!(max_retries_err.to_string().contains("3"));
    }

    #[test]
    fn test_vision_error_existing_variants() {
        // Test InvalidImage
        let invalid_img = VisionError::InvalidImage("Corrupted data".to_string());
        assert!(invalid_img.to_string().contains("Invalid image data"));

        // Test UnsupportedFormat
        let unsupported_fmt = VisionError::UnsupportedFormat("BMP not supported".to_string());
        assert!(
            unsupported_fmt
                .to_string()
                .contains("Unsupported image format")
        );

        // Test NetworkError
        let network_err = VisionError::NetworkError("Connection failed".to_string());
        assert!(network_err.to_string().contains("Network error"));

        // Test FileTooLarge
        let large_file = VisionError::FileTooLarge {
            size: 10_000_000,
            max: 5_000_000,
        };
        assert!(large_file.to_string().contains("too large"));
        assert!(large_file.to_string().contains("10000000"));
        assert!(large_file.to_string().contains("5000000"));
    }
}