litellm-rs 0.1.1

A high-performance AI Gateway written in Rust, providing OpenAI-compatible APIs with intelligent routing, load balancing, and enterprise features
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
//! Validation utilities for the Gateway
//!
//! This module provides comprehensive validation functions for various data types and formats.

#![allow(dead_code)]

use crate::core::models::openai::MessageContent;
use crate::utils::error::{GatewayError, Result};
use regex::Regex;
use std::collections::HashSet;
use uuid::Uuid;

/// Request validation utilities
pub struct RequestValidator;

impl RequestValidator {
    /// Validate chat completion request
    pub fn validate_chat_completion_request(
        model: &str,
        messages: &[crate::core::models::openai::ChatMessage],
        max_tokens: Option<u32>,
        temperature: Option<f32>,
    ) -> Result<()> {
        // Validate model
        Self::validate_model_name(model)?;

        // Validate messages
        if messages.is_empty() {
            return Err(GatewayError::Validation(
                "Messages cannot be empty".to_string(),
            ));
        }

        for (i, message) in messages.iter().enumerate() {
            Self::validate_chat_message(message, i)?;
        }

        // Validate max_tokens
        if let Some(max_tokens) = max_tokens {
            if max_tokens == 0 {
                return Err(GatewayError::Validation(
                    "max_tokens must be greater than 0".to_string(),
                ));
            }
            if max_tokens > 100000 {
                return Err(GatewayError::Validation(
                    "max_tokens cannot exceed 100000".to_string(),
                ));
            }
        }

        // Validate temperature
        if let Some(temperature) = temperature {
            if !(0.0..=2.0).contains(&temperature) {
                return Err(GatewayError::Validation(
                    "temperature must be between 0.0 and 2.0".to_string(),
                ));
            }
        }

        Ok(())
    }

    /// Validate chat message
    fn validate_chat_message(
        message: &crate::core::models::openai::ChatMessage,
        index: usize,
    ) -> Result<()> {
        use crate::core::models::openai::MessageRole;

        // Validate role
        match message.role {
            MessageRole::System | MessageRole::User | MessageRole::Assistant => {
                // These roles should have content
                if message.content.is_none() {
                    return Err(GatewayError::Validation(format!(
                        "Message at index {} with role {:?} must have content",
                        index, message.role
                    )));
                }
            }
            MessageRole::Function => {
                // Function messages should have name and content
                if message.name.is_none() {
                    return Err(GatewayError::Validation(format!(
                        "Function message at index {} must have a name",
                        index
                    )));
                }
                if message.content.is_none() {
                    return Err(GatewayError::Validation(format!(
                        "Function message at index {} must have content",
                        index
                    )));
                }
            }
            MessageRole::Tool => {
                // Tool messages should have tool_call_id and content
                if message.tool_call_id.is_none() {
                    return Err(GatewayError::Validation(format!(
                        "Tool message at index {} must have tool_call_id",
                        index
                    )));
                }
                if message.content.is_none() {
                    return Err(GatewayError::Validation(format!(
                        "Tool message at index {} must have content",
                        index
                    )));
                }
            }
        }

        // Validate content if present
        if let Some(content) = &message.content {
            Self::validate_message_content(content, index)?;
        }

        // Validate name if present
        if let Some(name) = &message.name {
            Self::validate_function_name(name)?;
        }

        Ok(())
    }

    /// Validate message content
    fn validate_message_content(
        content: &crate::core::models::openai::MessageContent,
        index: usize,
    ) -> Result<()> {
        match content {
            MessageContent::Text(text) => {
                if text.trim().is_empty() {
                    return Err(GatewayError::Validation(format!(
                        "Text content at message index {} cannot be empty",
                        index
                    )));
                }
                if text.len() > 1_000_000 {
                    return Err(GatewayError::Validation(format!(
                        "Text content at message index {} is too long (max 1M characters)",
                        index
                    )));
                }
            }
            MessageContent::Parts(parts) => {
                if parts.is_empty() {
                    return Err(GatewayError::Validation(format!(
                        "Content parts at message index {} cannot be empty",
                        index
                    )));
                }
                for (part_index, part) in parts.iter().enumerate() {
                    Self::validate_content_part(part, index, part_index)?;
                }
            }
        }

        Ok(())
    }

    /// Validate content part
    fn validate_content_part(
        part: &crate::core::models::openai::ContentPart,
        message_index: usize,
        part_index: usize,
    ) -> Result<()> {
        use crate::core::models::openai::ContentPart;

        match part {
            ContentPart::Text { text } => {
                if text.trim().is_empty() {
                    return Err(GatewayError::Validation(format!(
                        "Text part at message {} part {} cannot be empty",
                        message_index, part_index
                    )));
                }
            }
            ContentPart::ImageUrl { image_url } => {
                Self::validate_image_url(&image_url.url)?;
                if let Some(detail) = &image_url.detail {
                    if !["low", "high", "auto"].contains(&detail.as_str()) {
                        return Err(GatewayError::Validation(
                            "Image detail must be 'low', 'high', or 'auto'".to_string(),
                        ));
                    }
                }
            }
            ContentPart::Audio { audio } => {
                Self::validate_audio_data(&audio.data)?;
                Self::validate_audio_format(&audio.format)?;
            }
        }

        Ok(())
    }

    /// Validate model name
    fn validate_model_name(model: &str) -> Result<()> {
        if model.trim().is_empty() {
            return Err(GatewayError::Validation(
                "Model name cannot be empty".to_string(),
            ));
        }

        // Check for valid characters
        let model_regex = Regex::new(r"^[a-zA-Z0-9._/-]+$")
            .map_err(|e| GatewayError::Internal(format!("Regex error: {}", e)))?;

        if !model_regex.is_match(model) {
            return Err(GatewayError::Validation(
                "Model name contains invalid characters".to_string(),
            ));
        }

        Ok(())
    }

    /// Validate function name
    fn validate_function_name(name: &str) -> Result<()> {
        if name.trim().is_empty() {
            return Err(GatewayError::Validation(
                "Function name cannot be empty".to_string(),
            ));
        }

        // Function names should follow identifier rules
        let name_regex = Regex::new(r"^[a-zA-Z_][a-zA-Z0-9_]*$")
            .map_err(|e| GatewayError::Internal(format!("Regex error: {}", e)))?;

        if !name_regex.is_match(name) {
            return Err(GatewayError::Validation(
                "Function name must be a valid identifier".to_string(),
            ));
        }

        Ok(())
    }

    /// Validate image URL
    fn validate_image_url(url: &str) -> Result<()> {
        if url.starts_with("data:image/") {
            // Base64 encoded image
            Self::validate_base64_image(url)?;
        } else {
            // Regular URL
            url::Url::parse(url)
                .map_err(|e| GatewayError::Validation(format!("Invalid image URL: {}", e)))?;
        }
        Ok(())
    }

    /// Validate base64 image data
    fn validate_base64_image(data_url: &str) -> Result<()> {
        if !data_url.starts_with("data:image/") {
            return Err(GatewayError::Validation(
                "Invalid image data URL format".to_string(),
            ));
        }

        let parts: Vec<&str> = data_url.splitn(2, ',').collect();
        if parts.len() != 2 {
            return Err(GatewayError::Validation(
                "Invalid image data URL format".to_string(),
            ));
        }

        // Validate base64 data
        base64::Engine::decode(&base64::engine::general_purpose::STANDARD, parts[1])
            .map_err(|e| GatewayError::Validation(format!("Invalid base64 image data: {}", e)))?;

        Ok(())
    }

    /// Validate audio data
    fn validate_audio_data(data: &str) -> Result<()> {
        // Validate base64 encoded audio data
        base64::Engine::decode(&base64::engine::general_purpose::STANDARD, data)
            .map_err(|e| GatewayError::Validation(format!("Invalid base64 audio data: {}", e)))?;
        Ok(())
    }

    /// Validate audio format
    fn validate_audio_format(format: &str) -> Result<()> {
        let valid_formats = ["mp3", "wav", "flac", "m4a", "ogg", "webm"];
        if !valid_formats.contains(&format) {
            return Err(GatewayError::Validation(format!(
                "Invalid audio format: {}. Supported formats: {:?}",
                format, valid_formats
            )));
        }
        Ok(())
    }
}

/// API validation utilities
pub struct ApiValidator;

impl ApiValidator {
    /// Validate API key format
    pub fn validate_api_key(api_key: &str) -> Result<()> {
        if api_key.trim().is_empty() {
            return Err(GatewayError::Validation(
                "API key cannot be empty".to_string(),
            ));
        }

        if api_key.len() < 10 {
            return Err(GatewayError::Validation("API key is too short".to_string()));
        }

        if api_key.len() > 200 {
            return Err(GatewayError::Validation("API key is too long".to_string()));
        }

        Ok(())
    }

    /// Validate UUID format
    pub fn validate_uuid(uuid_str: &str) -> Result<Uuid> {
        Uuid::parse_str(uuid_str)
            .map_err(|e| GatewayError::Validation(format!("Invalid UUID format: {}", e)))
    }

    /// Validate pagination parameters
    pub fn validate_pagination(page: Option<u32>, limit: Option<u32>) -> Result<(u32, u32)> {
        let page = page.unwrap_or(1);
        let limit = limit.unwrap_or(20);

        if page == 0 {
            return Err(GatewayError::Validation(
                "Page must be greater than 0".to_string(),
            ));
        }

        if limit == 0 {
            return Err(GatewayError::Validation(
                "Limit must be greater than 0".to_string(),
            ));
        }

        if limit > 1000 {
            return Err(GatewayError::Validation(
                "Limit cannot exceed 1000".to_string(),
            ));
        }

        Ok((page, limit))
    }

    /// Validate date range
    pub fn validate_date_range(
        start_date: Option<chrono::DateTime<chrono::Utc>>,
        end_date: Option<chrono::DateTime<chrono::Utc>>,
    ) -> Result<()> {
        if let (Some(start), Some(end)) = (start_date, end_date) {
            if start >= end {
                return Err(GatewayError::Validation(
                    "Start date must be before end date".to_string(),
                ));
            }

            let max_range = chrono::Duration::days(365);
            if end - start > max_range {
                return Err(GatewayError::Validation(
                    "Date range cannot exceed 365 days".to_string(),
                ));
            }
        }

        Ok(())
    }

    /// Validate sort parameters
    pub fn validate_sort_params(
        sort_by: &str,
        sort_order: &str,
        valid_fields: &[&str],
    ) -> Result<()> {
        if !valid_fields.contains(&sort_by) {
            return Err(GatewayError::Validation(format!(
                "Invalid sort field: {}. Valid fields: {:?}",
                sort_by, valid_fields
            )));
        }

        if !["asc", "desc"].contains(&sort_order) {
            return Err(GatewayError::Validation(
                "Sort order must be 'asc' or 'desc'".to_string(),
            ));
        }

        Ok(())
    }

    /// Validate filter parameters
    pub fn validate_filters(
        filters: &std::collections::HashMap<String, String>,
        valid_filters: &[&str],
    ) -> Result<()> {
        for key in filters.keys() {
            if !valid_filters.contains(&key.as_str()) {
                return Err(GatewayError::Validation(format!(
                    "Invalid filter: {}. Valid filters: {:?}",
                    key, valid_filters
                )));
            }
        }

        Ok(())
    }
}

/// Data validation utilities
pub struct DataValidator;

impl DataValidator {
    /// Validate username
    pub fn validate_username(username: &str) -> Result<()> {
        if username.trim().is_empty() {
            return Err(GatewayError::Validation(
                "Username cannot be empty".to_string(),
            ));
        }

        if username.len() < 3 {
            return Err(GatewayError::Validation(
                "Username must be at least 3 characters".to_string(),
            ));
        }

        if username.len() > 50 {
            return Err(GatewayError::Validation(
                "Username cannot exceed 50 characters".to_string(),
            ));
        }

        let username_regex = Regex::new(r"^[a-zA-Z0-9_-]+$")
            .map_err(|e| GatewayError::Internal(format!("Regex error: {}", e)))?;

        if !username_regex.is_match(username) {
            return Err(GatewayError::Validation(
                "Username can only contain letters, numbers, underscores, and hyphens".to_string(),
            ));
        }

        Ok(())
    }

    /// Validate password strength
    pub fn validate_password(password: &str) -> Result<()> {
        if password.len() < 8 {
            return Err(GatewayError::Validation(
                "Password must be at least 8 characters".to_string(),
            ));
        }

        if password.len() > 128 {
            return Err(GatewayError::Validation(
                "Password cannot exceed 128 characters".to_string(),
            ));
        }

        let has_lowercase = password.chars().any(|c| c.is_lowercase());
        let has_uppercase = password.chars().any(|c| c.is_uppercase());
        let has_digit = password.chars().any(|c| c.is_ascii_digit());
        let has_special = password
            .chars()
            .any(|c| "!@#$%^&*()_+-=[]{}|;:,.<>?".contains(c));

        let strength_count = [has_lowercase, has_uppercase, has_digit, has_special]
            .iter()
            .filter(|&&x| x)
            .count();

        if strength_count < 3 {
            return Err(GatewayError::Validation(
                "Password must contain at least 3 of: lowercase, uppercase, digit, special character".to_string()
            ));
        }

        Ok(())
    }

    /// Validate team name
    pub fn validate_team_name(name: &str) -> Result<()> {
        if name.trim().is_empty() {
            return Err(GatewayError::Validation(
                "Team name cannot be empty".to_string(),
            ));
        }

        if name.len() < 2 {
            return Err(GatewayError::Validation(
                "Team name must be at least 2 characters".to_string(),
            ));
        }

        if name.len() > 100 {
            return Err(GatewayError::Validation(
                "Team name cannot exceed 100 characters".to_string(),
            ));
        }

        Ok(())
    }

    /// Validate tags
    pub fn validate_tags(tags: &[String]) -> Result<()> {
        if tags.len() > 20 {
            return Err(GatewayError::Validation(
                "Cannot have more than 20 tags".to_string(),
            ));
        }

        let mut unique_tags = HashSet::new();
        for tag in tags {
            if tag.trim().is_empty() {
                return Err(GatewayError::Validation("Tag cannot be empty".to_string()));
            }

            if tag.len() > 50 {
                return Err(GatewayError::Validation(
                    "Tag cannot exceed 50 characters".to_string(),
                ));
            }

            if !unique_tags.insert(tag.to_lowercase()) {
                return Err(GatewayError::Validation(format!("Duplicate tag: {}", tag)));
            }
        }

        Ok(())
    }
}

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

    #[test]
    fn test_model_name_validation() {
        assert!(RequestValidator::validate_model_name("gpt-4").is_ok());
        assert!(RequestValidator::validate_model_name("claude-3.5-sonnet").is_ok());
        assert!(RequestValidator::validate_model_name("").is_err());
        assert!(RequestValidator::validate_model_name("invalid@model").is_err());
    }

    #[test]
    fn test_api_key_validation() {
        assert!(ApiValidator::validate_api_key("valid_api_key_123").is_ok());
        assert!(ApiValidator::validate_api_key("").is_err());
        assert!(ApiValidator::validate_api_key("short").is_err());
    }

    #[test]
    fn test_uuid_validation() {
        let valid_uuid = "550e8400-e29b-41d4-a716-446655440000";
        assert!(ApiValidator::validate_uuid(valid_uuid).is_ok());
        assert!(ApiValidator::validate_uuid("invalid-uuid").is_err());
    }

    #[test]
    fn test_pagination_validation() {
        assert!(ApiValidator::validate_pagination(Some(1), Some(20)).is_ok());
        assert!(ApiValidator::validate_pagination(Some(0), Some(20)).is_err());
        assert!(ApiValidator::validate_pagination(Some(1), Some(0)).is_err());
        assert!(ApiValidator::validate_pagination(Some(1), Some(2000)).is_err());
    }

    #[test]
    fn test_username_validation() {
        assert!(DataValidator::validate_username("valid_user").is_ok());
        assert!(DataValidator::validate_username("user123").is_ok());
        assert!(DataValidator::validate_username("").is_err());
        assert!(DataValidator::validate_username("ab").is_err());
        assert!(DataValidator::validate_username("invalid@user").is_err());
    }

    #[test]
    fn test_password_validation() {
        assert!(DataValidator::validate_password("StrongPass123!").is_ok());
        assert!(DataValidator::validate_password("NoSpecialChars123").is_ok()); // Has 3 types: upper, lower, digit
        assert!(DataValidator::validate_password("weak").is_err()); // Too short
        assert!(DataValidator::validate_password("onlylowercase").is_err()); // Only 1 type
        assert!(DataValidator::validate_password("ONLYUPPERCASE").is_err()); // Only 1 type
        assert!(DataValidator::validate_password("OnlyTwoTypes").is_err()); // Only 2 types: upper, lower
    }

    #[test]
    fn test_tags_validation() {
        assert!(DataValidator::validate_tags(&["tag1".to_string(), "tag2".to_string()]).is_ok());
        assert!(DataValidator::validate_tags(&["".to_string()]).is_err());
        assert!(DataValidator::validate_tags(&["tag1".to_string(), "tag1".to_string()]).is_err());
    }
}