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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//! Replicate Model Registry
//!
//! Model registry for Replicate with support for LLM and image generation models

use std::collections::HashMap;
use std::sync::OnceLock;

use crate::core::types::{model::ModelInfo, model::ProviderCapability};

/// Model type for Replicate
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ReplicateModelType {
    /// Text generation / Chat completion (LLM)
    TextGeneration,
    /// Image generation (Stable Diffusion, SDXL, Flux, etc.)
    ImageGeneration,
    /// Audio generation
    AudioGeneration,
    /// Video generation
    VideoGeneration,
    /// Other model types
    Other,
}

/// Model specification for Replicate
#[derive(Debug, Clone)]
pub struct ReplicateModelSpec {
    /// Model info
    pub model_info: ModelInfo,
    /// Model type
    pub model_type: ReplicateModelType,
    /// Default input parameters
    pub default_params: HashMap<String, serde_json::Value>,
}

/// Replicate model registry
pub struct ReplicateModelRegistry {
    models: HashMap<String, ReplicateModelSpec>,
}

impl Default for ReplicateModelRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl ReplicateModelRegistry {
    /// Create a new model registry
    pub fn new() -> Self {
        let mut registry = Self {
            models: HashMap::new(),
        };
        registry.load_models();
        registry
    }

    /// Load default models
    fn load_models(&mut self) {
        // LLM Models
        self.add_llm_models();

        // Image Generation Models
        self.add_image_models();
    }

    /// Add LLM models to the registry
    fn add_llm_models(&mut self) {
        let llm_models = vec![
            // Meta Llama 2 models
            (
                "meta/llama-2-70b-chat",
                "Llama 2 70B Chat",
                4096,
                Some(2048),
                0.00065, // ~$0.65/1M tokens
                0.00275, // ~$2.75/1M tokens
            ),
            (
                "meta/llama-2-13b-chat",
                "Llama 2 13B Chat",
                4096,
                Some(2048),
                0.0001,
                0.0005,
            ),
            (
                "meta/llama-2-7b-chat",
                "Llama 2 7B Chat",
                4096,
                Some(2048),
                0.00005,
                0.00025,
            ),
            // Meta Llama 3 models
            (
                "meta/meta-llama-3-70b-instruct",
                "Llama 3 70B Instruct",
                8192,
                Some(4096),
                0.00065,
                0.00275,
            ),
            (
                "meta/meta-llama-3-8b-instruct",
                "Llama 3 8B Instruct",
                8192,
                Some(4096),
                0.00005,
                0.00025,
            ),
            // Meta Llama 3.1 models
            (
                "meta/meta-llama-3.1-405b-instruct",
                "Llama 3.1 405B Instruct",
                128_000,
                Some(4096),
                0.0095, // Higher cost for largest model
                0.0095,
            ),
            // Mistral models
            (
                "mistralai/mistral-7b-instruct-v0.2",
                "Mistral 7B Instruct v0.2",
                32_768,
                Some(4096),
                0.00005,
                0.00025,
            ),
            (
                "mistralai/mixtral-8x7b-instruct-v0.1",
                "Mixtral 8x7B Instruct",
                32_768,
                Some(4096),
                0.00027,
                0.00027,
            ),
        ];

        for (id, name, context_len, output_len, input_cost, output_cost) in llm_models {
            let model_info = ModelInfo {
                id: id.to_string(),
                name: name.to_string(),
                provider: "replicate".to_string(),
                max_context_length: context_len,
                max_output_length: output_len,
                supports_streaming: true,
                supports_tools: false, // Replicate LLMs generally don't support tool calling
                supports_multimodal: false,
                input_cost_per_1k_tokens: Some(input_cost),
                output_cost_per_1k_tokens: Some(output_cost),
                currency: "USD".to_string(),
                capabilities: vec![ProviderCapability::ChatCompletion],
                created_at: None,
                updated_at: None,
                metadata: HashMap::new(),
            };

            self.models.insert(
                id.to_string(),
                ReplicateModelSpec {
                    model_info,
                    model_type: ReplicateModelType::TextGeneration,
                    default_params: HashMap::new(),
                },
            );
        }
    }

    /// Add image generation models to the registry
    fn add_image_models(&mut self) {
        let image_models = vec![
            // Stable Diffusion XL
            (
                "stability-ai/sdxl",
                "Stable Diffusion XL",
                "1024x1024",
                0.003, // ~$0.003 per image
            ),
            (
                "stability-ai/stable-diffusion",
                "Stable Diffusion 2.1",
                "768x768",
                0.002,
            ),
            // FLUX models
            (
                "black-forest-labs/flux-schnell",
                "FLUX Schnell",
                "1024x1024",
                0.003,
            ),
            ("black-forest-labs/flux-dev", "FLUX Dev", "1024x1024", 0.025),
            ("black-forest-labs/flux-pro", "FLUX Pro", "1024x1024", 0.05),
            // Other popular models
            (
                "bytedance/sdxl-lightning-4step",
                "SDXL Lightning 4-Step",
                "1024x1024",
                0.002,
            ),
            (
                "lucataco/playground-v2.5-1024px-aesthetic",
                "Playground v2.5",
                "1024x1024",
                0.004,
            ),
        ];

        for (id, name, default_size, cost_per_image) in image_models {
            let mut metadata = HashMap::new();
            metadata.insert(
                "default_size".to_string(),
                serde_json::Value::String(default_size.to_string()),
            );
            metadata.insert(
                "cost_per_image".to_string(),
                serde_json::json!(cost_per_image),
            );

            let model_info = ModelInfo {
                id: id.to_string(),
                name: name.to_string(),
                provider: "replicate".to_string(),
                max_context_length: 0, // Not applicable for image models
                max_output_length: None,
                supports_streaming: false,
                supports_tools: false,
                supports_multimodal: false,
                input_cost_per_1k_tokens: None, // Image models don't use token pricing
                output_cost_per_1k_tokens: None,
                currency: "USD".to_string(),
                capabilities: vec![ProviderCapability::ImageGeneration],
                created_at: None,
                updated_at: None,
                metadata,
            };

            let mut default_params = HashMap::new();
            // Parse default size into width and height
            if let Some((w, h)) = default_size.split_once('x')
                && let (Ok(width), Ok(height)) = (w.parse::<i64>(), h.parse::<i64>())
            {
                default_params.insert("width".to_string(), serde_json::json!(width));
                default_params.insert("height".to_string(), serde_json::json!(height));
            }

            self.models.insert(
                id.to_string(),
                ReplicateModelSpec {
                    model_info,
                    model_type: ReplicateModelType::ImageGeneration,
                    default_params,
                },
            );
        }
    }

    /// Get all models
    pub fn get_all_models(&self) -> Vec<ModelInfo> {
        self.models
            .values()
            .map(|spec| spec.model_info.clone())
            .collect()
    }

    /// Get models by type
    pub fn get_models_by_type(&self, model_type: &ReplicateModelType) -> Vec<ModelInfo> {
        self.models
            .values()
            .filter(|spec| &spec.model_type == model_type)
            .map(|spec| spec.model_info.clone())
            .collect()
    }

    /// Get model specification
    pub fn get_model_spec(&self, model_id: &str) -> Option<&ReplicateModelSpec> {
        self.models.get(model_id)
    }

    /// Check if model exists
    pub fn has_model(&self, model_id: &str) -> bool {
        self.models.contains_key(model_id)
    }

    /// Get model type
    pub fn get_model_type(&self, model_id: &str) -> Option<ReplicateModelType> {
        self.models
            .get(model_id)
            .map(|spec| spec.model_type.clone())
    }

    /// Get default parameters for a model
    pub fn get_default_params(
        &self,
        model_id: &str,
    ) -> Option<&HashMap<String, serde_json::Value>> {
        self.models.get(model_id).map(|spec| &spec.default_params)
    }

    /// Get LLM models (for chat completion)
    pub fn get_llm_models(&self) -> Vec<ModelInfo> {
        self.get_models_by_type(&ReplicateModelType::TextGeneration)
    }

    /// Get image generation models
    pub fn get_image_models(&self) -> Vec<ModelInfo> {
        self.get_models_by_type(&ReplicateModelType::ImageGeneration)
    }
}

/// Global model registry
static REPLICATE_REGISTRY: OnceLock<ReplicateModelRegistry> = OnceLock::new();

/// Get the global Replicate model registry
pub fn get_replicate_registry() -> &'static ReplicateModelRegistry {
    REPLICATE_REGISTRY.get_or_init(ReplicateModelRegistry::new)
}

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

    #[test]
    fn test_registry_creation() {
        let registry = ReplicateModelRegistry::new();
        assert!(!registry.get_all_models().is_empty());
    }

    #[test]
    fn test_registry_has_llm_models() {
        let registry = get_replicate_registry();
        let llm_models = registry.get_llm_models();
        assert!(!llm_models.is_empty());

        // Check for specific Llama model
        let has_llama = llm_models.iter().any(|m| m.id.contains("llama"));
        assert!(has_llama);
    }

    #[test]
    fn test_registry_has_image_models() {
        let registry = get_replicate_registry();
        let image_models = registry.get_image_models();
        assert!(!image_models.is_empty());

        // Check for SDXL
        let has_sdxl = image_models.iter().any(|m| m.id.contains("sdxl"));
        assert!(has_sdxl);
    }

    #[test]
    fn test_get_model_spec() {
        let registry = get_replicate_registry();
        let spec = registry.get_model_spec("meta/llama-2-70b-chat");
        assert!(spec.is_some());

        let spec = spec.unwrap();
        assert_eq!(spec.model_type, ReplicateModelType::TextGeneration);
    }

    #[test]
    fn test_get_model_type() {
        let registry = get_replicate_registry();

        assert_eq!(
            registry.get_model_type("meta/llama-2-70b-chat"),
            Some(ReplicateModelType::TextGeneration)
        );
        assert_eq!(
            registry.get_model_type("stability-ai/sdxl"),
            Some(ReplicateModelType::ImageGeneration)
        );
        assert_eq!(registry.get_model_type("nonexistent"), None);
    }

    #[test]
    fn test_has_model() {
        let registry = get_replicate_registry();
        assert!(registry.has_model("meta/llama-2-70b-chat"));
        assert!(registry.has_model("stability-ai/sdxl"));
        assert!(!registry.has_model("nonexistent"));
    }

    #[test]
    fn test_model_info_properties() {
        let registry = get_replicate_registry();
        let models = registry.get_all_models();

        for model in models {
            assert!(!model.id.is_empty());
            assert!(!model.name.is_empty());
            assert_eq!(model.provider, "replicate");
            assert_eq!(model.currency, "USD");
        }
    }

    #[test]
    fn test_llm_model_capabilities() {
        let registry = get_replicate_registry();
        let llm_models = registry.get_llm_models();

        for model in llm_models {
            assert!(
                model
                    .capabilities
                    .contains(&ProviderCapability::ChatCompletion)
            );
            assert!(model.max_context_length > 0);
        }
    }

    #[test]
    fn test_image_model_capabilities() {
        let registry = get_replicate_registry();
        let image_models = registry.get_image_models();

        for model in image_models {
            assert!(
                model
                    .capabilities
                    .contains(&ProviderCapability::ImageGeneration)
            );
        }
    }

    #[test]
    fn test_image_model_default_params() {
        let registry = get_replicate_registry();
        let params = registry.get_default_params("stability-ai/sdxl");
        assert!(params.is_some());

        let params = params.unwrap();
        assert!(params.contains_key("width"));
        assert!(params.contains_key("height"));
    }

    #[test]
    fn test_model_type_equality() {
        assert_eq!(
            ReplicateModelType::TextGeneration,
            ReplicateModelType::TextGeneration
        );
        assert_ne!(
            ReplicateModelType::TextGeneration,
            ReplicateModelType::ImageGeneration
        );
    }

    #[test]
    fn test_default_impl() {
        let registry = ReplicateModelRegistry::default();
        assert!(!registry.get_all_models().is_empty());
    }

    #[test]
    fn test_global_registry() {
        let registry1 = get_replicate_registry();
        let registry2 = get_replicate_registry();

        // Should be the same instance
        assert_eq!(
            registry1.get_all_models().len(),
            registry2.get_all_models().len()
        );
    }

    #[test]
    fn test_flux_models() {
        let registry = get_replicate_registry();

        assert!(registry.has_model("black-forest-labs/flux-schnell"));
        assert!(registry.has_model("black-forest-labs/flux-dev"));
        assert!(registry.has_model("black-forest-labs/flux-pro"));
    }

    #[test]
    fn test_llama_3_models() {
        let registry = get_replicate_registry();

        assert!(registry.has_model("meta/meta-llama-3-70b-instruct"));
        assert!(registry.has_model("meta/meta-llama-3-8b-instruct"));
    }
}