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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
//! Error handling for the Gateway
//!
//! This module defines all error types used throughout the gateway.

#![allow(missing_docs)]

use actix_web::{HttpResponse, ResponseError};

use thiserror::Error;

/// Result type alias for the Gateway
pub type Result<T> = std::result::Result<T, GatewayError>;

/// Main error type for the Gateway
#[derive(Error, Debug)]
#[allow(dead_code)]
pub enum GatewayError {
    /// Configuration errors
    #[error("Configuration error: {0}")]
    Config(String),

    /// Database errors
    #[error("Database error: {0}")]
    Database(#[from] sea_orm::DbErr),

    /// Redis errors
    #[error("Redis error: {0}")]
    Redis(#[from] redis::RedisError),

    /// HTTP client errors
    #[error("HTTP client error: {0}")]
    HttpClient(#[from] reqwest::Error),

    /// Serialization errors
    #[error("Serialization error: {0}")]
    Serialization(#[from] serde_json::Error),

    /// YAML parsing errors
    #[error("YAML error: {0}")]
    Yaml(#[from] serde_yaml::Error),

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

    /// Authentication errors
    #[error("Authentication error: {0}")]
    Auth(String),

    /// Authorization errors
    #[error("Authorization error: {0}")]
    Authorization(String),

    /// Provider errors
    #[error("Provider error: {0}")]
    Provider(#[from] ProviderError),

    /// Rate limiting errors
    #[error("Rate limit exceeded: {0}")]
    RateLimit(String),

    /// Validation errors
    #[error("Validation error: {0}")]
    Validation(String),

    /// Cache errors
    #[error("Cache error: {0}")]
    Cache(String),

    /// Circuit breaker errors
    #[error("Circuit breaker error: {0}")]
    CircuitBreaker(String),

    /// Timeout errors
    #[error("Timeout error: {0}")]
    Timeout(String),

    /// Not found errors
    #[error("Not found: {0}")]
    NotFound(String),

    /// Conflict errors
    #[error("Conflict: {0}")]
    Conflict(String),

    /// Bad request errors
    #[error("Bad request: {0}")]
    BadRequest(String),

    /// Internal server errors
    #[error("Internal server error: {0}")]
    Internal(String),

    /// Service unavailable errors
    #[error("Service unavailable: {0}")]
    ServiceUnavailable(String),

    /// JWT errors
    #[error("JWT error: {0}")]
    Jwt(#[from] jsonwebtoken::errors::Error),

    /// Crypto errors
    #[error("Crypto error: {0}")]
    Crypto(String),

    /// File storage errors
    #[error("File storage error: {0}")]
    FileStorage(String),

    /// Vector database errors
    #[error("Vector database error: {0}")]
    VectorDb(String),

    /// Monitoring errors
    #[error("Monitoring error: {0}")]
    Monitoring(String),

    /// Integration errors
    #[error("Integration error: {0}")]
    Integration(String),

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

    /// Parsing errors
    #[error("Parsing error: {0}")]
    Parsing(String),

    /// Alert errors
    #[error("Alert error: {0}")]
    Alert(String),

    /// Not implemented errors
    #[error("Not implemented: {0}")]
    NotImplemented(String),

    /// Unauthorized errors
    #[error("Unauthorized: {0}")]
    Unauthorized(String),

    /// Forbidden errors
    #[error("Forbidden: {0}")]
    Forbidden(String),

    /// External service errors
    #[error("External service error: {0}")]
    External(String),

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

    /// No providers available
    #[error("No providers available: {0}")]
    NoProvidersAvailable(String),

    /// Provider not found
    #[error("Provider not found: {0}")]
    ProviderNotFound(String),

    /// No providers for model
    #[error("No providers for model: {0}")]
    NoProvidersForModel(String),

    /// No healthy providers
    #[error("No healthy providers: {0}")]
    NoHealthyProviders(String),
}

/// Provider-specific errors
#[derive(Error, Debug)]
#[allow(dead_code)]
pub enum ProviderError {
    /// API errors from providers
    #[error("API error: {message} (status: {status_code})")]
    ApiError {
        status_code: u16,
        message: String,
        provider: String,
    },

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

    /// Authentication errors with provider
    #[error("Provider authentication error: {0}")]
    Authentication(String),

    /// Rate limiting from provider
    #[error("Provider rate limit: {0}")]
    RateLimit(String),

    /// Quota exceeded
    #[error("Provider quota exceeded: {0}")]
    QuotaExceeded(String),

    /// Model not found
    #[error("Model not found: {0}")]
    ModelNotFound(String),

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

    /// Provider timeout
    #[error("Provider timeout: {0}")]
    Timeout(String),

    /// Provider unavailable
    #[error("Provider unavailable: {0}")]
    Unavailable(String),

    /// Configuration error
    #[error("Provider configuration error: {0}")]
    Configuration(String),

    /// Unknown provider error
    #[error("Unknown provider error: {0}")]
    Unknown(String),
}

impl ResponseError for GatewayError {
    fn error_response(&self) -> HttpResponse {
        let (status_code, error_code, message) = match self {
            GatewayError::Config(_) => (
                actix_web::http::StatusCode::INTERNAL_SERVER_ERROR,
                "CONFIG_ERROR",
                self.to_string(),
            ),
            GatewayError::Database(_) => (
                actix_web::http::StatusCode::INTERNAL_SERVER_ERROR,
                "DATABASE_ERROR",
                "Database operation failed".to_string(),
            ),
            GatewayError::Redis(_) => (
                actix_web::http::StatusCode::INTERNAL_SERVER_ERROR,
                "CACHE_ERROR",
                "Cache operation failed".to_string(),
            ),
            GatewayError::Auth(_) => (
                actix_web::http::StatusCode::UNAUTHORIZED,
                "AUTH_ERROR",
                self.to_string(),
            ),
            GatewayError::Authorization(_) => (
                actix_web::http::StatusCode::FORBIDDEN,
                "AUTHORIZATION_ERROR",
                self.to_string(),
            ),
            GatewayError::Provider(provider_error) => match provider_error {
                ProviderError::ApiError { status_code, .. } => (
                    actix_web::http::StatusCode::from_u16(*status_code)
                        .unwrap_or(actix_web::http::StatusCode::BAD_GATEWAY),
                    "PROVIDER_API_ERROR",
                    provider_error.to_string(),
                ),
                ProviderError::RateLimit(_) => (
                    actix_web::http::StatusCode::TOO_MANY_REQUESTS,
                    "PROVIDER_RATE_LIMIT",
                    provider_error.to_string(),
                ),
                ProviderError::QuotaExceeded(_) => (
                    actix_web::http::StatusCode::PAYMENT_REQUIRED,
                    "PROVIDER_QUOTA_EXCEEDED",
                    provider_error.to_string(),
                ),
                ProviderError::ModelNotFound(_) => (
                    actix_web::http::StatusCode::NOT_FOUND,
                    "MODEL_NOT_FOUND",
                    provider_error.to_string(),
                ),
                ProviderError::InvalidRequest(_) => (
                    actix_web::http::StatusCode::BAD_REQUEST,
                    "INVALID_REQUEST",
                    provider_error.to_string(),
                ),
                ProviderError::Timeout(_) => (
                    actix_web::http::StatusCode::GATEWAY_TIMEOUT,
                    "PROVIDER_TIMEOUT",
                    provider_error.to_string(),
                ),
                ProviderError::Unavailable(_) => (
                    actix_web::http::StatusCode::SERVICE_UNAVAILABLE,
                    "PROVIDER_UNAVAILABLE",
                    provider_error.to_string(),
                ),
                _ => (
                    actix_web::http::StatusCode::BAD_GATEWAY,
                    "PROVIDER_ERROR",
                    provider_error.to_string(),
                ),
            },
            GatewayError::RateLimit(_) => (
                actix_web::http::StatusCode::TOO_MANY_REQUESTS,
                "RATE_LIMIT_EXCEEDED",
                self.to_string(),
            ),
            GatewayError::Validation(_) => (
                actix_web::http::StatusCode::BAD_REQUEST,
                "VALIDATION_ERROR",
                self.to_string(),
            ),
            GatewayError::NotFound(_) => (
                actix_web::http::StatusCode::NOT_FOUND,
                "NOT_FOUND",
                self.to_string(),
            ),
            GatewayError::Conflict(_) => (
                actix_web::http::StatusCode::CONFLICT,
                "CONFLICT",
                self.to_string(),
            ),
            GatewayError::BadRequest(_) => (
                actix_web::http::StatusCode::BAD_REQUEST,
                "BAD_REQUEST",
                self.to_string(),
            ),
            GatewayError::Timeout(_) => (
                actix_web::http::StatusCode::REQUEST_TIMEOUT,
                "TIMEOUT",
                self.to_string(),
            ),
            GatewayError::ServiceUnavailable(_) => (
                actix_web::http::StatusCode::SERVICE_UNAVAILABLE,
                "SERVICE_UNAVAILABLE",
                self.to_string(),
            ),
            GatewayError::CircuitBreaker(_) => (
                actix_web::http::StatusCode::SERVICE_UNAVAILABLE,
                "CIRCUIT_BREAKER_OPEN",
                self.to_string(),
            ),
            GatewayError::Network(_) => (
                actix_web::http::StatusCode::BAD_GATEWAY,
                "NETWORK_ERROR",
                self.to_string(),
            ),
            GatewayError::Parsing(_) => (
                actix_web::http::StatusCode::BAD_REQUEST,
                "PARSING_ERROR",
                self.to_string(),
            ),
            GatewayError::Alert(_) => (
                actix_web::http::StatusCode::INTERNAL_SERVER_ERROR,
                "ALERT_ERROR",
                self.to_string(),
            ),
            GatewayError::NotImplemented(_) => (
                actix_web::http::StatusCode::NOT_IMPLEMENTED,
                "NOT_IMPLEMENTED",
                self.to_string(),
            ),
            GatewayError::Unauthorized(_) => (
                actix_web::http::StatusCode::UNAUTHORIZED,
                "UNAUTHORIZED",
                self.to_string(),
            ),
            GatewayError::Forbidden(_) => (
                actix_web::http::StatusCode::FORBIDDEN,
                "FORBIDDEN",
                self.to_string(),
            ),
            GatewayError::External(_) => (
                actix_web::http::StatusCode::BAD_GATEWAY,
                "EXTERNAL_ERROR",
                self.to_string(),
            ),
            GatewayError::InvalidRequest(_) => (
                actix_web::http::StatusCode::BAD_REQUEST,
                "INVALID_REQUEST",
                self.to_string(),
            ),
            GatewayError::NoProvidersAvailable(_) => (
                actix_web::http::StatusCode::SERVICE_UNAVAILABLE,
                "NO_PROVIDERS_AVAILABLE",
                self.to_string(),
            ),
            GatewayError::ProviderNotFound(_) => (
                actix_web::http::StatusCode::NOT_FOUND,
                "PROVIDER_NOT_FOUND",
                self.to_string(),
            ),
            GatewayError::NoProvidersForModel(_) => (
                actix_web::http::StatusCode::BAD_REQUEST,
                "NO_PROVIDERS_FOR_MODEL",
                self.to_string(),
            ),
            GatewayError::NoHealthyProviders(_) => (
                actix_web::http::StatusCode::SERVICE_UNAVAILABLE,
                "NO_HEALTHY_PROVIDERS",
                self.to_string(),
            ),
            _ => (
                actix_web::http::StatusCode::INTERNAL_SERVER_ERROR,
                "INTERNAL_ERROR",
                "An internal error occurred".to_string(),
            ),
        };

        let error_response = ErrorResponse {
            error: ErrorDetail {
                code: error_code.to_string(),
                message,
                timestamp: chrono::Utc::now().timestamp(),
                request_id: None, // This should be set by middleware
            },
        };

        HttpResponse::build(status_code).json(error_response)
    }
}

/// Standard error response format
#[derive(serde::Serialize)]
pub struct ErrorResponse {
    pub error: ErrorDetail,
}

/// Error detail structure
#[derive(serde::Serialize)]
pub struct ErrorDetail {
    pub code: String,
    pub message: String,
    pub timestamp: i64,
    pub request_id: Option<String>,
}

/// Helper functions for creating specific errors
#[allow(dead_code)]
impl GatewayError {
    pub fn auth<S: Into<String>>(message: S) -> Self {
        Self::Auth(message.into())
    }

    pub fn authorization<S: Into<String>>(message: S) -> Self {
        Self::Authorization(message.into())
    }

    pub fn bad_request<S: Into<String>>(message: S) -> Self {
        Self::BadRequest(message.into())
    }

    pub fn not_found<S: Into<String>>(message: S) -> Self {
        Self::NotFound(message.into())
    }

    pub fn conflict<S: Into<String>>(message: S) -> Self {
        Self::Conflict(message.into())
    }

    pub fn internal<S: Into<String>>(message: S) -> Self {
        Self::Internal(message.into())
    }

    pub fn validation<S: Into<String>>(message: S) -> Self {
        Self::Validation(message.into())
    }

    pub fn rate_limit<S: Into<String>>(message: S) -> Self {
        Self::RateLimit(message.into())
    }

    pub fn timeout<S: Into<String>>(message: S) -> Self {
        Self::Timeout(message.into())
    }

    pub fn service_unavailable<S: Into<String>>(message: S) -> Self {
        Self::ServiceUnavailable(message.into())
    }

    pub fn server<S: Into<String>>(message: S) -> Self {
        Self::Internal(message.into())
    }

    pub fn network<S: Into<String>>(message: S) -> Self {
        Self::Network(message.into())
    }

    pub fn external_service<S: Into<String>>(message: S) -> Self {
        Self::Internal(message.into())
    }

    pub fn invalid_request<S: Into<String>>(message: S) -> Self {
        Self::BadRequest(message.into())
    }

    pub fn parsing<S: Into<String>>(message: S) -> Self {
        Self::Parsing(message.into())
    }

    pub fn alert<S: Into<String>>(message: S) -> Self {
        Self::Alert(message.into())
    }

    pub fn not_implemented<S: Into<String>>(message: S) -> Self {
        Self::NotImplemented(message.into())
    }

    pub fn unauthorized<S: Into<String>>(message: S) -> Self {
        Self::Unauthorized(message.into())
    }

    pub fn forbidden<S: Into<String>>(message: S) -> Self {
        Self::Forbidden(message.into())
    }

    pub fn external<S: Into<String>>(message: S) -> Self {
        Self::External(message.into())
    }

    pub fn invalid_request_error<S: Into<String>>(message: S) -> Self {
        Self::InvalidRequest(message.into())
    }

    pub fn no_providers_available<S: Into<String>>(message: S) -> Self {
        Self::NoProvidersAvailable(message.into())
    }

    pub fn provider_not_found<S: Into<String>>(message: S) -> Self {
        Self::ProviderNotFound(message.into())
    }

    pub fn no_providers_for_model<S: Into<String>>(message: S) -> Self {
        Self::NoProvidersForModel(message.into())
    }

    pub fn no_healthy_providers<S: Into<String>>(message: S) -> Self {
        Self::NoHealthyProviders(message.into())
    }
}

#[allow(dead_code)]
impl ProviderError {
    pub fn api_error<S: Into<String>>(status_code: u16, message: S, provider: S) -> Self {
        Self::ApiError {
            status_code,
            message: message.into(),
            provider: provider.into(),
        }
    }

    pub fn rate_limit<S: Into<String>>(message: S) -> Self {
        Self::RateLimit(message.into())
    }

    pub fn quota_exceeded<S: Into<String>>(message: S) -> Self {
        Self::QuotaExceeded(message.into())
    }

    pub fn model_not_found<S: Into<String>>(message: S) -> Self {
        Self::ModelNotFound(message.into())
    }

    pub fn invalid_request<S: Into<String>>(message: S) -> Self {
        Self::InvalidRequest(message.into())
    }

    pub fn timeout<S: Into<String>>(message: S) -> Self {
        Self::Timeout(message.into())
    }

    pub fn unavailable<S: Into<String>>(message: S) -> Self {
        Self::Unavailable(message.into())
    }
}

// 添加从 core::providers::ProviderError 的转换
impl From<crate::core::providers::ProviderError> for GatewayError {
    fn from(err: crate::core::providers::ProviderError) -> Self {
        match err {
            crate::core::providers::ProviderError::Network(msg) => GatewayError::network(msg),
            crate::core::providers::ProviderError::Authentication(msg) => GatewayError::Auth(msg),
            crate::core::providers::ProviderError::RateLimit(msg) => GatewayError::RateLimit(msg),
            crate::core::providers::ProviderError::RateLimited(msg) => GatewayError::RateLimit(msg),
            crate::core::providers::ProviderError::InvalidRequest(msg) => {
                GatewayError::BadRequest(msg)
            }
            crate::core::providers::ProviderError::ModelNotFound(msg) => {
                GatewayError::NotFound(msg)
            }
            crate::core::providers::ProviderError::Parsing(msg) => GatewayError::parsing(msg),
            crate::core::providers::ProviderError::Timeout(msg) => GatewayError::Timeout(msg),
            crate::core::providers::ProviderError::Unavailable(msg) => {
                GatewayError::ServiceUnavailable(msg)
            }
            crate::core::providers::ProviderError::Unknown(msg) => GatewayError::Internal(msg),
            crate::core::providers::ProviderError::Other(msg) => GatewayError::Internal(msg),
        }
    }
}

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

    #[test]
    fn test_error_creation() {
        let error = GatewayError::auth("Invalid token");
        assert!(matches!(error, GatewayError::Auth(_)));

        let error = GatewayError::bad_request("Missing parameter");
        assert!(matches!(error, GatewayError::BadRequest(_)));
    }

    #[test]
    fn test_provider_error_creation() {
        let error = ProviderError::api_error(400, "Bad request", "openai");
        assert!(matches!(error, ProviderError::ApiError { .. }));

        let error = ProviderError::rate_limit("Too many requests");
        assert!(matches!(error, ProviderError::RateLimit(_)));
    }
}