litellm-rs 0.4.16

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
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
//! Replicate Prediction Types
//!
//! Types for handling Replicate prediction lifecycle

use serde::{Deserialize, Serialize};

/// Prediction status
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PredictionStatus {
    /// Prediction is queued and waiting to be processed
    Starting,
    /// Prediction is currently being processed
    Processing,
    /// Prediction completed successfully
    Succeeded,
    /// Prediction failed
    Failed,
    /// Prediction was canceled
    Canceled,
}

impl PredictionStatus {
    /// Check if the prediction has completed (either succeeded or failed)
    pub fn is_terminal(&self) -> bool {
        matches!(
            self,
            PredictionStatus::Succeeded | PredictionStatus::Failed | PredictionStatus::Canceled
        )
    }

    /// Check if the prediction is still in progress
    pub fn is_in_progress(&self) -> bool {
        matches!(
            self,
            PredictionStatus::Starting | PredictionStatus::Processing
        )
    }

    /// Check if the prediction succeeded
    pub fn is_success(&self) -> bool {
        matches!(self, PredictionStatus::Succeeded)
    }
}

/// URLs returned in prediction response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PredictionUrls {
    /// URL to cancel the prediction
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cancel: Option<String>,

    /// URL to get the prediction status
    #[serde(skip_serializing_if = "Option::is_none")]
    pub get: Option<String>,

    /// URL for streaming output (if available)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stream: Option<String>,
}

/// Prediction metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PredictionMetrics {
    /// Time to generate prediction in seconds
    #[serde(skip_serializing_if = "Option::is_none")]
    pub predict_time: Option<f64>,

    /// Total time including queue time
    #[serde(skip_serializing_if = "Option::is_none")]
    pub total_time: Option<f64>,
}

/// Replicate prediction response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PredictionResponse {
    /// Unique prediction ID
    pub id: String,

    /// Model version used for the prediction
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,

    /// Prediction status
    pub status: PredictionStatus,

    /// Prediction input
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input: Option<serde_json::Value>,

    /// Prediction output (format depends on the model)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output: Option<serde_json::Value>,

    /// Error message if prediction failed
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,

    /// Logs from the prediction
    #[serde(skip_serializing_if = "Option::is_none")]
    pub logs: Option<String>,

    /// Prediction metrics
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metrics: Option<PredictionMetrics>,

    /// URLs for prediction operations
    #[serde(skip_serializing_if = "Option::is_none")]
    pub urls: Option<PredictionUrls>,

    /// Creation timestamp
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at: Option<String>,

    /// Start timestamp
    #[serde(skip_serializing_if = "Option::is_none")]
    pub started_at: Option<String>,

    /// Completion timestamp
    #[serde(skip_serializing_if = "Option::is_none")]
    pub completed_at: Option<String>,

    /// Model used for the prediction
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,

    /// Data URL for the prediction
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data_removed: Option<bool>,
}

impl PredictionResponse {
    /// Get the prediction URL for polling
    pub fn get_prediction_url(&self) -> Option<&str> {
        self.urls.as_ref()?.get.as_deref()
    }

    /// Get the stream URL if available
    pub fn get_stream_url(&self) -> Option<&str> {
        self.urls.as_ref()?.stream.as_deref()
    }

    /// Get the cancel URL
    pub fn get_cancel_url(&self) -> Option<&str> {
        self.urls.as_ref()?.cancel.as_deref()
    }

    /// Check if the prediction is still in progress
    pub fn is_in_progress(&self) -> bool {
        self.status.is_in_progress()
    }

    /// Check if the prediction has completed
    pub fn is_terminal(&self) -> bool {
        self.status.is_terminal()
    }

    /// Check if the prediction succeeded
    pub fn is_success(&self) -> bool {
        self.status.is_success()
    }

    /// Get the output as a string (for text models)
    pub fn get_text_output(&self) -> Option<String> {
        let output = self.output.as_ref()?;

        // Output can be a string or an array of strings
        if let Some(s) = output.as_str() {
            return Some(s.to_string());
        }

        if let Some(arr) = output.as_array() {
            let texts: Vec<&str> = arr.iter().filter_map(|v| v.as_str()).collect();
            if !texts.is_empty() {
                return Some(texts.join(""));
            }
        }

        None
    }

    /// Get the output as URLs (for image models)
    pub fn get_image_urls(&self) -> Option<Vec<String>> {
        let output = self.output.as_ref()?;

        // Output is typically an array of URLs for image models
        if let Some(arr) = output.as_array() {
            let urls: Vec<String> = arr
                .iter()
                .filter_map(|v| v.as_str())
                .map(|s| s.to_string())
                .collect();
            if !urls.is_empty() {
                return Some(urls);
            }
        }

        // Single URL output
        if let Some(s) = output.as_str() {
            return Some(vec![s.to_string()]);
        }

        None
    }
}

/// Request to create a new prediction
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreatePredictionRequest {
    /// Input parameters for the model
    pub input: serde_json::Value,

    /// Model version to use (optional, for versioned predictions)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,

    /// Whether to stream output
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stream: Option<bool>,

    /// Webhook URL to receive prediction updates
    #[serde(skip_serializing_if = "Option::is_none")]
    pub webhook: Option<String>,

    /// Events to trigger webhook
    #[serde(skip_serializing_if = "Option::is_none")]
    pub webhook_events_filter: Option<Vec<String>>,
}

impl CreatePredictionRequest {
    /// Create a new prediction request with input
    pub fn new(input: serde_json::Value) -> Self {
        Self {
            input,
            version: None,
            stream: None,
            webhook: None,
            webhook_events_filter: None,
        }
    }

    /// Set the model version
    pub fn with_version(mut self, version: impl Into<String>) -> Self {
        self.version = Some(version.into());
        self
    }

    /// Enable streaming
    pub fn with_stream(mut self, stream: bool) -> Self {
        self.stream = Some(stream);
        self
    }
}

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

    #[test]
    fn test_prediction_status_is_terminal() {
        assert!(PredictionStatus::Succeeded.is_terminal());
        assert!(PredictionStatus::Failed.is_terminal());
        assert!(PredictionStatus::Canceled.is_terminal());
        assert!(!PredictionStatus::Starting.is_terminal());
        assert!(!PredictionStatus::Processing.is_terminal());
    }

    #[test]
    fn test_prediction_status_is_in_progress() {
        assert!(PredictionStatus::Starting.is_in_progress());
        assert!(PredictionStatus::Processing.is_in_progress());
        assert!(!PredictionStatus::Succeeded.is_in_progress());
        assert!(!PredictionStatus::Failed.is_in_progress());
        assert!(!PredictionStatus::Canceled.is_in_progress());
    }

    #[test]
    fn test_prediction_status_is_success() {
        assert!(PredictionStatus::Succeeded.is_success());
        assert!(!PredictionStatus::Failed.is_success());
        assert!(!PredictionStatus::Processing.is_success());
    }

    #[test]
    fn test_prediction_response_get_text_output_string() {
        let response = PredictionResponse {
            id: "test".to_string(),
            version: None,
            status: PredictionStatus::Succeeded,
            input: None,
            output: Some(serde_json::json!("Hello, world!")),
            error: None,
            logs: None,
            metrics: None,
            urls: None,
            created_at: None,
            started_at: None,
            completed_at: None,
            model: None,
            data_removed: None,
        };
        assert_eq!(
            response.get_text_output(),
            Some("Hello, world!".to_string())
        );
    }

    #[test]
    fn test_prediction_response_get_text_output_array() {
        let response = PredictionResponse {
            id: "test".to_string(),
            version: None,
            status: PredictionStatus::Succeeded,
            input: None,
            output: Some(serde_json::json!(["Hello", ", ", "world", "!"])),
            error: None,
            logs: None,
            metrics: None,
            urls: None,
            created_at: None,
            started_at: None,
            completed_at: None,
            model: None,
            data_removed: None,
        };
        assert_eq!(
            response.get_text_output(),
            Some("Hello, world!".to_string())
        );
    }

    #[test]
    fn test_prediction_response_get_image_urls() {
        let response = PredictionResponse {
            id: "test".to_string(),
            version: None,
            status: PredictionStatus::Succeeded,
            input: None,
            output: Some(serde_json::json!([
                "https://example.com/image1.png",
                "https://example.com/image2.png"
            ])),
            error: None,
            logs: None,
            metrics: None,
            urls: None,
            created_at: None,
            started_at: None,
            completed_at: None,
            model: None,
            data_removed: None,
        };
        let urls = response.get_image_urls().unwrap();
        assert_eq!(urls.len(), 2);
        assert_eq!(urls[0], "https://example.com/image1.png");
    }

    #[test]
    fn test_prediction_response_get_prediction_url() {
        let response = PredictionResponse {
            id: "test".to_string(),
            version: None,
            status: PredictionStatus::Processing,
            input: None,
            output: None,
            error: None,
            logs: None,
            metrics: None,
            urls: Some(PredictionUrls {
                cancel: Some("https://api.replicate.com/v1/predictions/test/cancel".to_string()),
                get: Some("https://api.replicate.com/v1/predictions/test".to_string()),
                stream: None,
            }),
            created_at: None,
            started_at: None,
            completed_at: None,
            model: None,
            data_removed: None,
        };
        assert_eq!(
            response.get_prediction_url(),
            Some("https://api.replicate.com/v1/predictions/test")
        );
    }

    #[test]
    fn test_create_prediction_request() {
        let request = CreatePredictionRequest::new(serde_json::json!({
            "prompt": "Hello"
        }))
        .with_version("abc123")
        .with_stream(true);

        assert_eq!(request.version, Some("abc123".to_string()));
        assert_eq!(request.stream, Some(true));
    }

    #[test]
    fn test_prediction_status_serialization() {
        assert_eq!(
            serde_json::to_string(&PredictionStatus::Succeeded).unwrap(),
            "\"succeeded\""
        );
        assert_eq!(
            serde_json::to_string(&PredictionStatus::Processing).unwrap(),
            "\"processing\""
        );
    }

    #[test]
    fn test_prediction_status_deserialization() {
        assert_eq!(
            serde_json::from_str::<PredictionStatus>("\"succeeded\"").unwrap(),
            PredictionStatus::Succeeded
        );
        assert_eq!(
            serde_json::from_str::<PredictionStatus>("\"failed\"").unwrap(),
            PredictionStatus::Failed
        );
    }

    #[test]
    fn test_prediction_response_is_in_progress() {
        let response = PredictionResponse {
            id: "test".to_string(),
            version: None,
            status: PredictionStatus::Processing,
            input: None,
            output: None,
            error: None,
            logs: None,
            metrics: None,
            urls: None,
            created_at: None,
            started_at: None,
            completed_at: None,
            model: None,
            data_removed: None,
        };
        assert!(response.is_in_progress());
        assert!(!response.is_terminal());
    }

    #[test]
    fn test_prediction_urls_serialization() {
        let urls = PredictionUrls {
            cancel: Some("https://example.com/cancel".to_string()),
            get: Some("https://example.com/get".to_string()),
            stream: None,
        };
        let json = serde_json::to_value(&urls).unwrap();
        assert!(json.get("cancel").is_some());
        assert!(json.get("stream").is_none());
    }

    #[test]
    fn test_prediction_metrics() {
        let metrics = PredictionMetrics {
            predict_time: Some(1.5),
            total_time: Some(2.0),
        };
        assert_eq!(metrics.predict_time, Some(1.5));
        assert_eq!(metrics.total_time, Some(2.0));
    }
}