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
//! Replicate provider implementation
//!
//! This module provides Replicate API integration for various AI models.

use super::{BaseProvider, ModelPricing, Provider, ProviderError, ProviderType};
use crate::config::ProviderConfig;
use crate::core::models::{RequestContext, openai::*};
use crate::utils::error::{GatewayError, Result};
use async_trait::async_trait;
use serde_json::json;
use std::collections::HashMap;
use tracing::{debug, info};

/// Replicate provider implementation
#[derive(Debug, Clone)]
pub struct ReplicateProvider {
    /// Base provider functionality
    base: BaseProvider,
    /// Model pricing cache
    pricing_cache: HashMap<String, ModelPricing>,
}

impl ReplicateProvider {
    /// Create a new Replicate provider
    pub async fn new(config: &ProviderConfig) -> Result<Self> {
        let base = BaseProvider::new(config)?;

        let base_url = config
            .base_url
            .clone()
            .unwrap_or_else(|| "https://api.replicate.com".to_string());

        let provider = Self {
            base: BaseProvider { base_url, ..base },
            pricing_cache: Self::initialize_pricing_cache(),
        };

        info!(
            "Replicate provider '{}' initialized successfully",
            config.name
        );
        Ok(provider)
    }

    /// Initialize pricing cache with Replicate model prices
    fn initialize_pricing_cache() -> HashMap<String, ModelPricing> {
        let mut cache = HashMap::new();

        // Llama models
        cache.insert(
            "meta/llama-2-70b-chat".to_string(),
            ModelPricing {
                model: "meta/llama-2-70b-chat".to_string(),
                input_cost_per_1k: 0.00065,
                output_cost_per_1k: 0.00275,
                currency: "USD".to_string(),
                updated_at: chrono::Utc::now(),
            },
        );

        cache.insert(
            "meta/llama-2-13b-chat".to_string(),
            ModelPricing {
                model: "meta/llama-2-13b-chat".to_string(),
                input_cost_per_1k: 0.0001,
                output_cost_per_1k: 0.0005,
                currency: "USD".to_string(),
                updated_at: chrono::Utc::now(),
            },
        );

        // Mistral models
        cache.insert(
            "mistralai/mixtral-8x7b-instruct-v0.1".to_string(),
            ModelPricing {
                model: "mistralai/mixtral-8x7b-instruct-v0.1".to_string(),
                input_cost_per_1k: 0.0003,
                output_cost_per_1k: 0.001,
                currency: "USD".to_string(),
                updated_at: chrono::Utc::now(),
            },
        );

        // Image generation models
        cache.insert(
            "stability-ai/stable-diffusion".to_string(),
            ModelPricing {
                model: "stability-ai/stable-diffusion".to_string(),
                input_cost_per_1k: 0.0,
                output_cost_per_1k: 0.0018, // Per image
                currency: "USD".to_string(),
                updated_at: chrono::Utc::now(),
            },
        );

        cache.insert(
            "stability-ai/sdxl".to_string(),
            ModelPricing {
                model: "stability-ai/sdxl".to_string(),
                input_cost_per_1k: 0.0,
                output_cost_per_1k: 0.004, // Per image
                currency: "USD".to_string(),
                updated_at: chrono::Utc::now(),
            },
        );

        cache
    }

    /// Convert OpenAI messages to Replicate format
    fn convert_messages_to_replicate(&self, messages: &[ChatMessage]) -> String {
        // Replicate typically expects a single prompt string
        messages
            .iter()
            .map(|msg| {
                let role = match msg.role {
                    MessageRole::System => "System",
                    MessageRole::User => "User",
                    MessageRole::Assistant => "Assistant",
                    MessageRole::Tool => "Tool",
                    MessageRole::Function => "function",
                };

                let content = match &msg.content {
                    Some(MessageContent::Text(text)) => text.clone(),
                    Some(MessageContent::Parts(parts)) => parts
                        .iter()
                        .filter_map(|part| match part {
                            ContentPart::Text { text } => Some(text.clone()),
                            _ => None,
                        })
                        .collect::<Vec<String>>()
                        .join(" "),
                    None => String::new(),
                };

                format!("{}: {}", role, content)
            })
            .collect::<Vec<String>>()
            .join("\n\n")
    }

    /// Create a prediction on Replicate
    async fn create_prediction(
        &self,
        model: &str,
        input: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let body = json!({
            "version": model,
            "input": input
        });

        let url = format!("{}/v1/predictions", self.base.base_url);

        let response = self
            .base
            .client
            .post(&url)
            .header("Authorization", format!("Token {}", self.base.api_key))
            .header("Content-Type", "application/json")
            .json(&body)
            .send()
            .await
            .map_err(|e| ProviderError::Network(e.to_string()))?;

        if !response.status().is_success() {
            let status = response.status();
            let error_text = response.text().await.unwrap_or_default();

            return Err(match status.as_u16() {
                401 => ProviderError::Authentication(error_text),
                429 => ProviderError::RateLimit(error_text),
                404 => ProviderError::ModelNotFound(error_text),
                400 => ProviderError::InvalidRequest(error_text),
                _ => ProviderError::Unknown(format!("HTTP {}: {}", status, error_text)),
            }
            .into());
        }

        let prediction: serde_json::Value = self.base.parse_json_response(response).await?;
        Ok(prediction)
    }

    /// Wait for prediction to complete
    async fn wait_for_prediction(&self, prediction_id: &str) -> Result<serde_json::Value> {
        let url = format!("{}/v1/predictions/{}", self.base.base_url, prediction_id);

        // Poll for completion (simplified - in production, use webhooks)
        for _ in 0..30 {
            // Max 30 attempts
            let response = self
                .base
                .client
                .get(&url)
                .header("Authorization", format!("Token {}", self.base.api_key))
                .send()
                .await
                .map_err(|e| ProviderError::Network(e.to_string()))?;

            let prediction: serde_json::Value = self.base.parse_json_response(response).await?;

            let status = prediction
                .get("status")
                .and_then(|s| s.as_str())
                .unwrap_or("unknown");

            match status {
                "succeeded" => return Ok(prediction),
                "failed" | "canceled" => {
                    let error = prediction
                        .get("error")
                        .and_then(|e| e.as_str())
                        .unwrap_or("Prediction failed");
                    return Err(ProviderError::Unknown(error.to_string()).into());
                }
                "starting" | "processing" => {
                    // Continue polling
                    tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
                }
                _ => {
                    return Err(
                        ProviderError::Unknown(format!("Unknown status: {}", status)).into(),
                    );
                }
            }
        }

        Err(ProviderError::Unknown("Prediction timed out".to_string()).into())
    }
}

#[async_trait]
impl Provider for ReplicateProvider {
    fn name(&self) -> &str {
        &self.base.name
    }

    fn provider_type(&self) -> ProviderType {
        ProviderType::Custom("replicate".to_string())
    }

    async fn supports_model(&self, model: &str) -> bool {
        self.base.is_model_supported(model) || model.contains("/") // Replicate models are in format "owner/model"
    }

    async fn supports_images(&self) -> bool {
        true // Replicate has many image generation models
    }

    async fn supports_embeddings(&self) -> bool {
        false // Replicate doesn't typically have embedding models
    }

    async fn supports_streaming(&self) -> bool {
        false // Replicate doesn't support streaming
    }

    async fn list_models(&self) -> Result<Vec<Model>> {
        // Replicate has thousands of models, return some popular ones
        let known_models = vec![
            "meta/llama-2-70b-chat",
            "meta/llama-2-13b-chat",
            "meta/llama-2-7b-chat",
            "mistralai/mixtral-8x7b-instruct-v0.1",
            "stability-ai/stable-diffusion",
            "stability-ai/sdxl",
            "openai/whisper",
            "salesforce/blip",
        ];

        let models = known_models
            .into_iter()
            .map(|model| Model {
                id: model.to_string(),
                object: "model".to_string(),
                created: chrono::Utc::now().timestamp() as u64,
                owned_by: "replicate".to_string(),
            })
            .collect();

        Ok(models)
    }

    async fn health_check(&self) -> Result<()> {
        debug!("Performing Replicate health check");

        // Try to access the account endpoint
        let url = format!("{}/v1/account", self.base.base_url);

        let response = self
            .base
            .client
            .get(&url)
            .header("Authorization", format!("Token {}", self.base.api_key))
            .send()
            .await
            .map_err(|e| ProviderError::Network(e.to_string()))?;

        if response.status().is_success() {
            Ok(())
        } else {
            Err(
                ProviderError::Unknown(format!("Health check failed: {}", response.status()))
                    .into(),
            )
        }
    }

    async fn chat_completion(
        &self,
        request: ChatCompletionRequest,
        _context: RequestContext,
    ) -> Result<ChatCompletionResponse> {
        debug!("Replicate chat completion for model: {}", request.model);

        let prompt = self.convert_messages_to_replicate(&request.messages);

        let mut input = json!({
            "prompt": prompt
        });

        // Add optional parameters
        if let Some(max_tokens) = request.max_tokens {
            input["max_new_tokens"] = json!(max_tokens);
        }
        if let Some(temperature) = request.temperature {
            input["temperature"] = json!(temperature);
        }
        if let Some(top_p) = request.top_p {
            input["top_p"] = json!(top_p);
        }

        // Create prediction
        let prediction = self.create_prediction(&request.model, input).await?;

        let prediction_id = prediction
            .get("id")
            .and_then(|id| id.as_str())
            .ok_or_else(|| ProviderError::Parsing("No prediction ID in response".to_string()))?;

        // Wait for completion
        let completed_prediction = self.wait_for_prediction(prediction_id).await?;

        let output = completed_prediction
            .get("output")
            .ok_or_else(|| ProviderError::Parsing("No output in prediction".to_string()))?;

        let content = match output {
            serde_json::Value::String(s) => s.clone(),
            serde_json::Value::Array(arr) => arr
                .iter()
                .filter_map(|v| v.as_str())
                .collect::<Vec<&str>>()
                .join(""),
            _ => output.to_string(),
        };

        Ok(ChatCompletionResponse {
            id: format!("chatcmpl-replicate-{}", prediction_id),
            object: "chat.completion".to_string(),
            created: chrono::Utc::now().timestamp() as u64,
            model: request.model,
            choices: vec![ChatChoice {
                index: 0,
                message: ChatMessage {
                    role: MessageRole::Assistant,
                    content: Some(MessageContent::Text(content)),
                    name: None,
                    function_call: None,
                    tool_calls: None,
                    tool_call_id: None,
                    audio: None,
                },
                finish_reason: Some("stop".to_string()),
                logprobs: None,
            }],
            usage: Some(Usage::default()), // Replicate doesn't provide token counts
            system_fingerprint: None,
        })
    }

    async fn completion(
        &self,
        request: CompletionRequest,
        _context: RequestContext,
    ) -> Result<CompletionResponse> {
        debug!("Replicate completion for model: {}", request.model);

        let mut input = json!({
            "prompt": request.prompt
        });

        // Add optional parameters
        if let Some(max_tokens) = request.max_tokens {
            input["max_new_tokens"] = json!(max_tokens);
        }
        if let Some(temperature) = request.temperature {
            input["temperature"] = json!(temperature);
        }
        if let Some(top_p) = request.top_p {
            input["top_p"] = json!(top_p);
        }

        // Create prediction
        let prediction = self.create_prediction(&request.model, input).await?;

        let prediction_id = prediction
            .get("id")
            .and_then(|id| id.as_str())
            .ok_or_else(|| ProviderError::Parsing("No prediction ID in response".to_string()))?;

        // Wait for completion
        let completed_prediction = self.wait_for_prediction(prediction_id).await?;

        let output = completed_prediction
            .get("output")
            .ok_or_else(|| ProviderError::Parsing("No output in prediction".to_string()))?;

        let text = match output {
            serde_json::Value::String(s) => s.clone(),
            serde_json::Value::Array(arr) => arr
                .iter()
                .filter_map(|v| v.as_str())
                .collect::<Vec<&str>>()
                .join(""),
            _ => output.to_string(),
        };

        Ok(CompletionResponse {
            id: format!("cmpl-replicate-{}", prediction_id),
            object: "text_completion".to_string(),
            created: chrono::Utc::now().timestamp() as u64,
            model: request.model,
            choices: vec![CompletionChoice {
                text,
                index: 0,
                logprobs: None,
                finish_reason: Some("stop".to_string()),
            }],
            usage: Some(Usage::default()),
        })
    }

    async fn embedding(
        &self,
        _request: EmbeddingRequest,
        _context: RequestContext,
    ) -> Result<EmbeddingResponse> {
        Err(
            ProviderError::InvalidRequest("Embeddings not supported by Replicate".to_string())
                .into(),
        )
    }

    async fn image_generation(
        &self,
        request: ImageGenerationRequest,
        _context: RequestContext,
    ) -> Result<ImageGenerationResponse> {
        debug!("Replicate image generation for model: {:?}", request.model);

        let mut input = json!({
            "prompt": request.prompt
        });

        // Add optional parameters
        if let Some(n) = request.n {
            input["num_outputs"] = json!(n);
        }
        if let Some(size) = &request.size {
            // Parse size like "1024x1024"
            if let Some((width, height)) = size.split_once('x') {
                if let (Ok(w), Ok(h)) = (width.parse::<u32>(), height.parse::<u32>()) {
                    input["width"] = json!(w);
                    input["height"] = json!(h);
                }
            }
        }

        // Create prediction
        let model_str = request.model.as_ref().ok_or_else(|| {
            GatewayError::InvalidRequest("Model is required for image generation".to_string())
        })?;
        let prediction = self.create_prediction(model_str, input).await?;

        let prediction_id = prediction
            .get("id")
            .and_then(|id| id.as_str())
            .ok_or_else(|| ProviderError::Parsing("No prediction ID in response".to_string()))?;

        // Wait for completion
        let completed_prediction = self.wait_for_prediction(prediction_id).await?;

        let output = completed_prediction
            .get("output")
            .ok_or_else(|| ProviderError::Parsing("No output in prediction".to_string()))?;

        let urls = match output {
            serde_json::Value::String(url) => vec![url.clone()],
            serde_json::Value::Array(arr) => arr
                .iter()
                .filter_map(|v| v.as_str())
                .map(|s| s.to_string())
                .collect(),
            _ => return Err(ProviderError::Parsing("Invalid output format".to_string()).into()),
        };

        let data = urls
            .into_iter()
            .map(|url| ImageObject {
                url: Some(url),
                b64_json: None,
            })
            .collect();

        Ok(ImageGenerationResponse {
            created: chrono::Utc::now().timestamp() as u64,
            data,
        })
    }

    async fn get_model_pricing(&self, model: &str) -> Result<ModelPricing> {
        if let Some(pricing) = self.pricing_cache.get(model) {
            Ok(pricing.clone())
        } else {
            // Return default pricing for unknown models
            Ok(ModelPricing {
                model: model.to_string(),
                input_cost_per_1k: 0.001,
                output_cost_per_1k: 0.002,
                currency: "USD".to_string(),
                updated_at: chrono::Utc::now(),
            })
        }
    }

    async fn calculate_cost(
        &self,
        model: &str,
        input_tokens: u32,
        output_tokens: u32,
    ) -> Result<f64> {
        let pricing = self.get_model_pricing(model).await?;

        let input_cost = (input_tokens as f64 / 1000.0) * pricing.input_cost_per_1k;
        let output_cost = (output_tokens as f64 / 1000.0) * pricing.output_cost_per_1k;

        Ok(input_cost + output_cost)
    }
}