serdes-ai-core 0.2.0

Core types, messages, and error handling for serdes-ai
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
//! Multi-modal content types for user prompts.
//!
//! This module defines the content types that can be included in user messages,
//! supporting text, images, audio, video, documents, and generic files.

use serde::{Deserialize, Serialize};

use super::media::{AudioMediaType, DocumentMediaType, ImageMediaType, VideoMediaType};

/// User message content.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum UserContent {
    /// Plain text content.
    Text(String),
    /// Multi-part content.
    Parts(Vec<UserContentPart>),
}

impl UserContent {
    /// Create text content.
    #[must_use]
    pub fn text(s: impl Into<String>) -> Self {
        Self::Text(s.into())
    }

    /// Create multi-part content.
    #[must_use]
    pub fn parts(parts: Vec<UserContentPart>) -> Self {
        Self::Parts(parts)
    }

    /// Check if this is text content.
    #[must_use]
    pub fn is_text(&self) -> bool {
        matches!(self, Self::Text(_))
    }

    /// Get as text if this is text content.
    #[must_use]
    pub fn as_text(&self) -> Option<&str> {
        match self {
            Self::Text(s) => Some(s),
            _ => None,
        }
    }

    /// Get all parts (wraps text in a single-element vec if needed).
    #[must_use]
    pub fn to_parts(&self) -> Vec<UserContentPart> {
        match self {
            Self::Text(s) => vec![UserContentPart::Text { text: s.clone() }],
            Self::Parts(parts) => parts.clone(),
        }
    }
}

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

impl From<String> for UserContent {
    fn from(s: String) -> Self {
        Self::Text(s)
    }
}

impl From<&str> for UserContent {
    fn from(s: &str) -> Self {
        Self::Text(s.to_string())
    }
}

impl From<Vec<UserContentPart>> for UserContent {
    fn from(parts: Vec<UserContentPart>) -> Self {
        Self::Parts(parts)
    }
}

/// Individual content part in a multi-part message.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum UserContentPart {
    /// Text content.
    Text {
        /// The text.
        text: String,
    },
    /// Image content.
    Image {
        /// The image.
        #[serde(flatten)]
        image: ImageContent,
    },
    /// Audio content.
    Audio {
        /// The audio.
        #[serde(flatten)]
        audio: AudioContent,
    },
    /// Video content.
    Video {
        /// The video.
        #[serde(flatten)]
        video: VideoContent,
    },
    /// Document content.
    Document {
        /// The document.
        #[serde(flatten)]
        document: DocumentContent,
    },
    /// Generic file content.
    File {
        /// The file.
        #[serde(flatten)]
        file: FileContent,
    },
}

impl UserContentPart {
    /// Create text content.
    #[must_use]
    pub fn text(s: impl Into<String>) -> Self {
        Self::Text { text: s.into() }
    }

    /// Create image content from URL.
    #[must_use]
    pub fn image_url(url: impl Into<String>) -> Self {
        Self::Image {
            image: ImageContent::url(url),
        }
    }

    /// Create image content from binary data.
    #[must_use]
    pub fn image_binary(data: Vec<u8>, media_type: ImageMediaType) -> Self {
        Self::Image {
            image: ImageContent::binary(data, media_type),
        }
    }
}

/// Image content.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ImageContent {
    /// Image from URL.
    Url(ImageUrl),
    /// Binary image data.
    Binary(BinaryImage),
}

impl ImageContent {
    /// Create from URL.
    #[must_use]
    pub fn url(url: impl Into<String>) -> Self {
        Self::Url(ImageUrl::new(url))
    }

    /// Create from binary data.
    #[must_use]
    pub fn binary(data: Vec<u8>, media_type: ImageMediaType) -> Self {
        Self::Binary(BinaryImage::new(data, media_type))
    }

    /// Get the media type if known.
    #[must_use]
    pub fn media_type(&self) -> Option<ImageMediaType> {
        match self {
            Self::Url(u) => u.media_type,
            Self::Binary(b) => Some(b.media_type),
        }
    }
}

/// Image from URL.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ImageUrl {
    /// The image URL.
    pub url: String,
    /// Media type hint.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub media_type: Option<ImageMediaType>,
    /// Force download instead of using URL directly.
    #[serde(default)]
    pub force_download: bool,
    /// Vendor-specific metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub vendor_metadata: Option<serde_json::Value>,
}

impl ImageUrl {
    /// Create a new image URL.
    #[must_use]
    pub fn new(url: impl Into<String>) -> Self {
        Self {
            url: url.into(),
            media_type: None,
            force_download: false,
            vendor_metadata: None,
        }
    }

    /// Set the media type.
    #[must_use]
    pub fn with_media_type(mut self, media_type: ImageMediaType) -> Self {
        self.media_type = Some(media_type);
        self
    }

    /// Set force download.
    #[must_use]
    pub fn with_force_download(mut self, force: bool) -> Self {
        self.force_download = force;
        self
    }

    /// Set vendor metadata.
    #[must_use]
    pub fn with_vendor_metadata(mut self, metadata: serde_json::Value) -> Self {
        self.vendor_metadata = Some(metadata);
        self
    }
}

/// Binary image data.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BinaryImage {
    /// The raw image data.
    #[serde(with = "base64_serde")]
    pub data: Vec<u8>,
    /// The media type.
    pub media_type: ImageMediaType,
}

impl BinaryImage {
    /// Create new binary image.
    #[must_use]
    pub fn new(data: Vec<u8>, media_type: ImageMediaType) -> Self {
        Self { data, media_type }
    }

    /// Get data as base64 string.
    #[must_use]
    pub fn to_base64(&self) -> String {
        base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &self.data)
    }

    /// Get as data URL.
    #[must_use]
    pub fn to_data_url(&self) -> String {
        format!(
            "data:{};base64,{}",
            self.media_type.mime_type(),
            self.to_base64()
        )
    }
}

/// Audio content.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum AudioContent {
    /// Audio from URL.
    Url(AudioUrl),
    /// Binary audio data.
    Binary(BinaryAudio),
}

impl AudioContent {
    /// Create from URL.
    #[must_use]
    pub fn url(url: impl Into<String>) -> Self {
        Self::Url(AudioUrl::new(url))
    }

    /// Create from binary data.
    #[must_use]
    pub fn binary(data: Vec<u8>, media_type: AudioMediaType) -> Self {
        Self::Binary(BinaryAudio::new(data, media_type))
    }
}

/// Audio from URL.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AudioUrl {
    /// The audio URL.
    pub url: String,
    /// Media type hint.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub media_type: Option<AudioMediaType>,
    /// Force download instead of using URL directly.
    #[serde(default)]
    pub force_download: bool,
    /// Vendor-specific metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub vendor_metadata: Option<serde_json::Value>,
}

impl AudioUrl {
    /// Create a new audio URL.
    #[must_use]
    pub fn new(url: impl Into<String>) -> Self {
        Self {
            url: url.into(),
            media_type: None,
            force_download: false,
            vendor_metadata: None,
        }
    }

    /// Set the media type.
    #[must_use]
    pub fn with_media_type(mut self, media_type: AudioMediaType) -> Self {
        self.media_type = Some(media_type);
        self
    }
}

/// Binary audio data.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BinaryAudio {
    /// The raw audio data.
    #[serde(with = "base64_serde")]
    pub data: Vec<u8>,
    /// The media type.
    pub media_type: AudioMediaType,
}

impl BinaryAudio {
    /// Create new binary audio.
    #[must_use]
    pub fn new(data: Vec<u8>, media_type: AudioMediaType) -> Self {
        Self { data, media_type }
    }
}

/// Video content.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum VideoContent {
    /// Video from URL.
    Url(VideoUrl),
    /// Binary video data.
    Binary(BinaryVideo),
}

impl VideoContent {
    /// Create from URL.
    #[must_use]
    pub fn url(url: impl Into<String>) -> Self {
        Self::Url(VideoUrl::new(url))
    }

    /// Create from binary data.
    #[must_use]
    pub fn binary(data: Vec<u8>, media_type: VideoMediaType) -> Self {
        Self::Binary(BinaryVideo::new(data, media_type))
    }
}

/// Video from URL.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct VideoUrl {
    /// The video URL.
    pub url: String,
    /// Media type hint.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub media_type: Option<VideoMediaType>,
    /// Force download instead of using URL directly.
    #[serde(default)]
    pub force_download: bool,
    /// Vendor-specific metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub vendor_metadata: Option<serde_json::Value>,
}

impl VideoUrl {
    /// Create a new video URL.
    #[must_use]
    pub fn new(url: impl Into<String>) -> Self {
        Self {
            url: url.into(),
            media_type: None,
            force_download: false,
            vendor_metadata: None,
        }
    }

    /// Set the media type.
    #[must_use]
    pub fn with_media_type(mut self, media_type: VideoMediaType) -> Self {
        self.media_type = Some(media_type);
        self
    }
}

/// Binary video data.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BinaryVideo {
    /// The raw video data.
    #[serde(with = "base64_serde")]
    pub data: Vec<u8>,
    /// The media type.
    pub media_type: VideoMediaType,
}

impl BinaryVideo {
    /// Create new binary video.
    #[must_use]
    pub fn new(data: Vec<u8>, media_type: VideoMediaType) -> Self {
        Self { data, media_type }
    }
}

/// Document content.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum DocumentContent {
    /// Document from URL.
    Url(DocumentUrl),
    /// Binary document data.
    Binary(BinaryDocument),
}

impl DocumentContent {
    /// Create from URL.
    #[must_use]
    pub fn url(url: impl Into<String>) -> Self {
        Self::Url(DocumentUrl::new(url))
    }

    /// Create from binary data.
    #[must_use]
    pub fn binary(data: Vec<u8>, media_type: DocumentMediaType) -> Self {
        Self::Binary(BinaryDocument::new(data, media_type))
    }
}

/// Document from URL.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DocumentUrl {
    /// The document URL.
    pub url: String,
    /// Media type hint.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub media_type: Option<DocumentMediaType>,
    /// Force download instead of using URL directly.
    #[serde(default)]
    pub force_download: bool,
    /// Vendor-specific metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub vendor_metadata: Option<serde_json::Value>,
}

impl DocumentUrl {
    /// Create a new document URL.
    #[must_use]
    pub fn new(url: impl Into<String>) -> Self {
        Self {
            url: url.into(),
            media_type: None,
            force_download: false,
            vendor_metadata: None,
        }
    }

    /// Set the media type.
    #[must_use]
    pub fn with_media_type(mut self, media_type: DocumentMediaType) -> Self {
        self.media_type = Some(media_type);
        self
    }
}

/// Binary document data.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BinaryDocument {
    /// The raw document data.
    #[serde(with = "base64_serde")]
    pub data: Vec<u8>,
    /// The media type.
    pub media_type: DocumentMediaType,
    /// Optional filename.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filename: Option<String>,
}

impl BinaryDocument {
    /// Create new binary document.
    #[must_use]
    pub fn new(data: Vec<u8>, media_type: DocumentMediaType) -> Self {
        Self {
            data,
            media_type,
            filename: None,
        }
    }

    /// Set the filename.
    #[must_use]
    pub fn with_filename(mut self, filename: impl Into<String>) -> Self {
        self.filename = Some(filename.into());
        self
    }
}

/// Generic file content.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum FileContent {
    /// File from URL.
    Url(FileUrl),
    /// Binary file data.
    Binary(BinaryFile),
}

impl FileContent {
    /// Create from URL.
    #[must_use]
    pub fn url(url: impl Into<String>) -> Self {
        Self::Url(FileUrl::new(url))
    }

    /// Create from binary data.
    #[must_use]
    pub fn binary(data: Vec<u8>, mime_type: impl Into<String>) -> Self {
        Self::Binary(BinaryFile::new(data, mime_type))
    }
}

/// File from URL.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FileUrl {
    /// The file URL.
    pub url: String,
    /// MIME type hint.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mime_type: Option<String>,
    /// Force download instead of using URL directly.
    #[serde(default)]
    pub force_download: bool,
    /// Vendor-specific metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub vendor_metadata: Option<serde_json::Value>,
}

impl FileUrl {
    /// Create a new file URL.
    #[must_use]
    pub fn new(url: impl Into<String>) -> Self {
        Self {
            url: url.into(),
            mime_type: None,
            force_download: false,
            vendor_metadata: None,
        }
    }

    /// Set the MIME type.
    #[must_use]
    pub fn with_mime_type(mut self, mime_type: impl Into<String>) -> Self {
        self.mime_type = Some(mime_type.into());
        self
    }
}

/// Binary file data.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BinaryFile {
    /// The raw file data.
    #[serde(with = "base64_serde")]
    pub data: Vec<u8>,
    /// The MIME type.
    pub mime_type: String,
    /// Optional filename.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filename: Option<String>,
}

impl BinaryFile {
    /// Create new binary file.
    #[must_use]
    pub fn new(data: Vec<u8>, mime_type: impl Into<String>) -> Self {
        Self {
            data,
            mime_type: mime_type.into(),
            filename: None,
        }
    }

    /// Set the filename.
    #[must_use]
    pub fn with_filename(mut self, filename: impl Into<String>) -> Self {
        self.filename = Some(filename.into());
        self
    }
}

/// Serde helper for base64 encoding.
mod base64_serde {
    use base64::{engine::general_purpose::STANDARD, Engine};
    use serde::{Deserialize, Deserializer, Serializer};

    pub fn serialize<S>(data: &[u8], serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&STANDARD.encode(data))
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        STANDARD.decode(s).map_err(serde::de::Error::custom)
    }
}

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

    #[test]
    fn test_user_content_text() {
        let content = UserContent::text("Hello, world!");
        assert!(content.is_text());
        assert_eq!(content.as_text(), Some("Hello, world!"));
    }

    #[test]
    fn test_user_content_from_string() {
        let content: UserContent = "Hello".into();
        assert!(content.is_text());
    }

    #[test]
    fn test_image_url() {
        let img =
            ImageUrl::new("https://example.com/image.png").with_media_type(ImageMediaType::Png);
        assert_eq!(img.url, "https://example.com/image.png");
        assert_eq!(img.media_type, Some(ImageMediaType::Png));
    }

    #[test]
    fn test_binary_image_to_data_url() {
        let img = BinaryImage::new(vec![1, 2, 3, 4], ImageMediaType::Png);
        let data_url = img.to_data_url();
        assert!(data_url.starts_with("data:image/png;base64,"));
    }

    #[test]
    fn test_serde_roundtrip() {
        let content = UserContent::parts(vec![
            UserContentPart::text("Hello"),
            UserContentPart::image_url("https://example.com/img.jpg"),
        ]);
        let json = serde_json::to_string(&content).unwrap();
        let parsed: UserContent = serde_json::from_str(&json).unwrap();
        assert_eq!(content, parsed);
    }
}