litellm-rs 0.8.2

A high-performance AI Gateway written in Rust, providing OpenAI-compatible APIs with intelligent routing, load balancing, and enterprise features
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
//! HTTP route modules
//!
//! This module contains all HTTP route handlers organized by functionality.

pub mod admin;
pub mod admin_dashboard;
mod admin_openapi;
mod admin_providers;
mod admin_request_ledger;
mod admin_routing;
mod admin_routing_policy;
pub mod ai;
pub mod auth;
pub mod budget;
pub mod health;
pub mod keys;
#[cfg(feature = "mcp")]
pub mod mcp;
pub mod pricing;
pub mod teams;

use actix_web::HttpResponse;

/// Standard API response structure
#[derive(Debug, Clone, serde::Serialize)]
pub struct ApiResponse<T> {
    /// Whether the request was successful
    pub success: bool,
    /// Response data (if successful)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<T>,
    /// Error message (if failed)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    /// Additional metadata
    #[serde(skip_serializing_if = "Option::is_none")]
    pub meta: Option<serde_json::Value>,
}

impl<T> ApiResponse<T>
where
    T: serde::Serialize,
{
    /// Create a successful response
    pub fn success(data: T) -> Self {
        Self {
            success: true,
            data: Some(data),
            error: None,
            meta: None,
        }
    }

    /// Create an error response
    pub fn error(message: String) -> ApiResponse<()> {
        ApiResponse {
            success: false,
            data: None,
            error: Some(message),
            meta: None,
        }
    }
}

impl<T> ApiResponse<T> {
    /// Create an error response for any type
    pub fn error_for_type(message: String) -> ApiResponse<T> {
        ApiResponse {
            success: false,
            data: None,
            error: Some(message),
            meta: None,
        }
    }
}

impl<T> ApiResponse<T>
where
    T: serde::Serialize,
{
    /// Convert the API response to an HTTP response.
    #[deprecated(note = "Use explicit route status helpers instead")]
    pub fn to_http_response(&self) -> HttpResponse {
        if self.success {
            HttpResponse::Ok().json(self)
        } else {
            HttpResponse::BadRequest().json(self)
        }
    }
}

/// Pagination metadata
#[derive(Debug, Clone, serde::Serialize)]
pub struct PaginationMeta {
    /// Current page number
    pub page: u32,
    /// Number of items per page
    pub limit: u32,
    /// Total number of items
    pub total: u64,
    /// Total number of pages
    pub pages: u32,
    /// Whether there is a next page
    pub has_next: bool,
    /// Whether there is a previous page
    pub has_prev: bool,
}

impl PaginationMeta {
    /// Create pagination metadata
    pub fn new(page: u32, limit: u32, total: u64) -> Self {
        let pages = ((total as f64) / (limit as f64)).ceil() as u32;

        Self {
            page,
            limit,
            total,
            pages,
            has_next: page < pages,
            has_prev: page > 1,
        }
    }
}

/// Paginated response
#[derive(Debug, Clone, serde::Serialize)]
pub struct PaginatedResponse<T> {
    /// Response items
    pub items: Vec<T>,
    /// Pagination metadata
    pub pagination: PaginationMeta,
}

impl<T> PaginatedResponse<T>
where
    T: serde::Serialize,
{
    /// Create a paginated response
    pub fn new(items: Vec<T>, page: u32, limit: u32, total: u64) -> Self {
        Self {
            items,
            pagination: PaginationMeta::new(page, limit, total),
        }
    }
}

/// Query parameters for pagination
#[derive(Debug, Clone, serde::Deserialize)]
pub struct PaginationQuery {
    /// Page number (1-based)
    #[serde(default = "default_page")]
    pub page: u32,
    /// Number of items per page
    #[serde(default = "default_limit")]
    pub limit: u32,
}

fn default_page() -> u32 {
    1
}

fn default_limit() -> u32 {
    20
}

impl PaginationQuery {
    /// Validate pagination parameters
    pub fn validate(&self) -> Result<(), String> {
        if self.page == 0 {
            return Err("Page must be greater than 0".to_string());
        }
        if self.limit == 0 {
            return Err("Limit must be greater than 0".to_string());
        }
        if self.limit > 1000 {
            return Err("Limit cannot exceed 1000".to_string());
        }
        Ok(())
    }

    /// Get offset for database queries
    pub fn offset(&self) -> u32 {
        (self.page - 1) * self.limit
    }
}

/// Query parameters for sorting
#[derive(Debug, Clone, serde::Deserialize)]
pub struct SortQuery {
    /// Field to sort by
    #[serde(default = "default_sort_by")]
    pub sort_by: String,
    /// Sort order (asc or desc)
    #[serde(default = "default_sort_order")]
    pub sort_order: String,
}

fn default_sort_by() -> String {
    "created_at".to_string()
}

fn default_sort_order() -> String {
    "desc".to_string()
}

impl SortQuery {
    /// Validate sort parameters
    pub fn validate(&self, valid_fields: &[&str]) -> Result<(), String> {
        if !valid_fields.contains(&self.sort_by.as_str()) {
            return Err(format!("Invalid sort field: {}", self.sort_by));
        }
        if !["asc", "desc"].contains(&self.sort_order.as_str()) {
            return Err("Sort order must be 'asc' or 'desc'".to_string());
        }
        Ok(())
    }
}

/// Combined query parameters for listing endpoints
#[derive(Debug, Clone, serde::Deserialize)]
pub struct ListQuery {
    /// Pagination parameters (page, limit)
    #[serde(flatten)]
    pub pagination: PaginationQuery,
    /// Sorting parameters (sort_by, sort_order)
    #[serde(flatten)]
    pub sort: SortQuery,
}

impl ListQuery {
    /// Validate all query parameters
    pub fn validate(&self, valid_sort_fields: &[&str]) -> Result<(), String> {
        self.pagination.validate()?;
        self.sort.validate(valid_sort_fields)?;
        Ok(())
    }
}

/// Error response helpers
pub mod errors {
    use super::*;
    use crate::utils::error::gateway_error::GatewayError;
    use actix_web::ResponseError;

    /// Convert GatewayError to HTTP response.
    ///
    /// Kept as a compatibility shim while routes migrate to `ResponseError` directly.
    pub fn gateway_error_to_response(error: GatewayError) -> HttpResponse {
        error.error_response()
    }

    /// Create a validation error response
    pub fn validation_error(message: &str) -> HttpResponse {
        HttpResponse::BadRequest().json(ApiResponse::<()>::error(message.to_string()))
    }

    /// Create an unauthorized error response
    pub fn unauthorized_error(message: &str) -> HttpResponse {
        HttpResponse::Unauthorized().json(ApiResponse::<()>::error(message.to_string()))
    }

    /// Create a forbidden error response
    pub fn forbidden_error(message: &str) -> HttpResponse {
        HttpResponse::Forbidden().json(ApiResponse::<()>::error(message.to_string()))
    }

    /// Create a not found error response
    pub fn not_found_error(message: &str) -> HttpResponse {
        HttpResponse::NotFound().json(ApiResponse::<()>::error(message.to_string()))
    }

    /// Create an internal server error response
    pub fn internal_error(message: &str) -> HttpResponse {
        HttpResponse::InternalServerError().json(ApiResponse::<()>::error(message.to_string()))
    }
}

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

    #[test]
    fn test_api_response_success() {
        let response = ApiResponse::success("test data");
        assert!(response.success);
        assert_eq!(response.data, Some("test data"));
        assert!(response.error.is_none());
    }

    #[test]
    fn test_api_response_error() {
        let response = ApiResponse::<()>::error("test error".to_string());
        assert!(!response.success);
        assert!(response.data.is_none());
        assert_eq!(response.error, Some("test error".to_string()));
    }

    #[test]
    #[allow(deprecated)]
    fn test_api_response_to_http_response_remains_compatibility_shim() {
        let success = ApiResponse::success("test data").to_http_response();
        assert_eq!(success.status(), actix_web::http::StatusCode::OK);

        let error = ApiResponse::<()>::error("test error".to_string()).to_http_response();
        assert_eq!(error.status(), actix_web::http::StatusCode::BAD_REQUEST);
    }

    #[actix_web::test]
    async fn test_gateway_error_helpers_keep_api_response_envelope() {
        let response = errors::validation_error("test validation error");

        assert_eq!(response.status(), actix_web::http::StatusCode::BAD_REQUEST);
        let body = actix_web::body::to_bytes(response.into_body())
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();

        assert_eq!(json["success"], false);
        assert_eq!(json["error"], "test validation error");
        assert!(json["data"].is_null());
    }

    #[test]
    fn test_error_helpers_preserve_specific_http_statuses() {
        assert_eq!(
            errors::unauthorized_error("unauthorized").status(),
            actix_web::http::StatusCode::UNAUTHORIZED
        );
        assert_eq!(
            errors::forbidden_error("forbidden").status(),
            actix_web::http::StatusCode::FORBIDDEN
        );
        assert_eq!(
            errors::not_found_error("missing").status(),
            actix_web::http::StatusCode::NOT_FOUND
        );
        assert_eq!(
            errors::internal_error("internal").status(),
            actix_web::http::StatusCode::INTERNAL_SERVER_ERROR
        );
    }

    #[test]
    fn test_pagination_meta() {
        let meta = PaginationMeta::new(2, 10, 25);
        assert_eq!(meta.page, 2);
        assert_eq!(meta.limit, 10);
        assert_eq!(meta.total, 25);
        assert_eq!(meta.pages, 3);
        assert!(meta.has_next);
        assert!(meta.has_prev);
    }

    #[test]
    fn test_pagination_query_validation() {
        let valid_query = PaginationQuery { page: 1, limit: 20 };
        assert!(valid_query.validate().is_ok());

        let invalid_page = PaginationQuery { page: 0, limit: 20 };
        assert!(invalid_page.validate().is_err());

        let invalid_limit = PaginationQuery { page: 1, limit: 0 };
        assert!(invalid_limit.validate().is_err());

        let too_large_limit = PaginationQuery {
            page: 1,
            limit: 2000,
        };
        assert!(too_large_limit.validate().is_err());
    }

    #[test]
    fn test_pagination_query_offset() {
        let query = PaginationQuery { page: 3, limit: 10 };
        assert_eq!(query.offset(), 20);
    }

    #[test]
    fn test_sort_query_validation() {
        let valid_fields = &["name", "created_at", "updated_at"];

        let valid_query = SortQuery {
            sort_by: "name".to_string(),
            sort_order: "asc".to_string(),
        };
        assert!(valid_query.validate(valid_fields).is_ok());

        let invalid_field = SortQuery {
            sort_by: "invalid".to_string(),
            sort_order: "asc".to_string(),
        };
        assert!(invalid_field.validate(valid_fields).is_err());

        let invalid_order = SortQuery {
            sort_by: "name".to_string(),
            sort_order: "invalid".to_string(),
        };
        assert!(invalid_order.validate(valid_fields).is_err());
    }
}

#[cfg(feature = "a2a")]
pub mod a2a;