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
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
//! Default transformation engine and concrete Transform implementations

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;

use super::types::*;
use crate::core::providers::ProviderType;
use crate::core::providers::unified_provider::ProviderError;

/// Default transformation engine implementation
pub struct DefaultTransformEngine {
    pipelines: HashMap<ProviderType, TransformPipeline>,
    model_mappings: HashMap<String, ModelMapping>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelMapping {
    pub provider_model: String,
    pub openai_equivalent: String,
    pub capabilities: Vec<String>,
    pub parameter_mappings: HashMap<String, String>,
}

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

impl DefaultTransformEngine {
    pub fn new() -> Self {
        let mut engine = Self {
            pipelines: HashMap::new(),
            model_mappings: HashMap::new(),
        };

        engine.init_default_mappings();
        engine.init_default_pipelines();
        engine
    }

    fn init_default_mappings(&mut self) {
        // Anthropic model mappings
        self.model_mappings.insert(
            "claude-3-sonnet".to_string(),
            ModelMapping {
                provider_model: "claude-3-sonnet-20240229".to_string(),
                openai_equivalent: "gpt-4".to_string(),
                capabilities: vec!["chat".to_string(), "vision".to_string()],
                parameter_mappings: HashMap::from([
                    ("max_tokens".to_string(), "max_tokens".to_string()),
                    ("temperature".to_string(), "temperature".to_string()),
                ]),
            },
        );

        // Google model mappings
        self.model_mappings.insert(
            "gemini-pro".to_string(),
            ModelMapping {
                provider_model: "gemini-1.0-pro".to_string(),
                openai_equivalent: "gpt-3.5-turbo".to_string(),
                capabilities: vec!["chat".to_string()],
                parameter_mappings: HashMap::from([
                    ("max_tokens".to_string(), "maxOutputTokens".to_string()),
                    ("temperature".to_string(), "temperature".to_string()),
                ]),
            },
        );
    }

    fn init_default_pipelines(&mut self) {
        // Initialize transformation pipelines for each provider
        // This would include provider-specific transformations

        // Anthropic pipeline
        let anthropic_pipeline = TransformPipeline {
            transforms: vec![
                Box::new(AnthropicMessageTransform::new()),
                Box::new(AnthropicParameterTransform::new()),
            ],
        };
        self.pipelines
            .insert(ProviderType::Anthropic, anthropic_pipeline);

        // VertexAI/Gemini pipeline
        let vertexai_pipeline = TransformPipeline {
            transforms: vec![
                Box::new(GoogleMessageTransform::new()),
                Box::new(GoogleParameterTransform::new()),
            ],
        };
        self.pipelines
            .insert(ProviderType::VertexAI, vertexai_pipeline);
    }

    pub(crate) fn map_model_name(&self, model: &str, provider_type: &ProviderType) -> String {
        // Model name mapping logic
        match provider_type {
            ProviderType::Anthropic => {
                if model.starts_with("claude") {
                    model.to_string()
                } else {
                    "claude-3-sonnet-20240229".to_string() // default
                }
            }
            ProviderType::VertexAI => {
                if model.starts_with("gemini") {
                    model.to_string()
                } else {
                    "gemini-1.0-pro".to_string() // default
                }
            }
            _ => model.to_string(),
        }
    }
}

#[async_trait]
impl TransformEngine for DefaultTransformEngine {
    async fn transform_chat_request(
        &self,
        request: &TransformChatRequest,
        provider_type: &ProviderType,
        provider_config: &HashMap<String, Value>,
    ) -> ProviderResult<TransformResult<ProviderRequest>> {
        let context = TransformContext {
            provider_type: provider_type.clone(),
            original_model: request.model.clone(),
            target_model: self.map_model_name(&request.model, provider_type),
            config: provider_config.clone(),
            metadata: HashMap::new(),
        };

        let mut transformations = Vec::new();
        let warnings = Vec::new();

        // Convert request to JSON for pipeline processing
        let mut request_json =
            serde_json::to_value(request).map_err(|e| ProviderError::Serialization {
                provider: "transform",
                message: format!("Serialization error: {}", e),
            })?;

        // Apply transformation pipeline if available
        if let Some(pipeline) = self.pipelines.get(provider_type) {
            for transform in &pipeline.transforms {
                transformations.push(transform.name().to_string());
                request_json = transform.transform_request(request_json, &context).await?;
            }
        }

        // Build provider request
        let provider_request = match provider_type {
            ProviderType::Anthropic => self.build_anthropic_request(request_json, &context).await?,
            ProviderType::VertexAI => self.build_vertexai_request(request_json, &context).await?,
            _ => {
                self.build_openai_compatible_request(request_json, &context)
                    .await?
            }
        };

        Ok(TransformResult {
            data: provider_request,
            metadata: TransformMetadata {
                provider_type: provider_type.clone(),
                original_model: request.model.clone(),
                transformed_model: context.target_model,
                transformations_applied: transformations,
                warnings,
                cost_estimate: None,
            },
        })
    }

    async fn transform_chat_response(
        &self,
        response: &ProviderResponse,
        provider_type: &ProviderType,
        original_request: &TransformChatRequest,
    ) -> ProviderResult<TransformResult<ChatResponse>> {
        let context = TransformContext {
            provider_type: provider_type.clone(),
            original_model: original_request.model.clone(),
            target_model: self.map_model_name(&original_request.model, provider_type),
            config: HashMap::new(),
            metadata: HashMap::new(),
        };

        let mut transformations = Vec::new();
        let mut response_json = response.body.clone();

        // Apply reverse transformation pipeline
        if let Some(pipeline) = self.pipelines.get(provider_type) {
            for transform in pipeline.transforms.iter().rev() {
                transformations.push(format!("reverse_{}", transform.name()));
                response_json = transform
                    .transform_response(response_json, &context)
                    .await?;
            }
        }

        // Convert back to ChatResponse
        let chat_response: ChatResponse =
            serde_json::from_value(response_json).map_err(|e| ProviderError::Serialization {
                provider: "transform",
                message: format!("Deserialization error: {}", e),
            })?;

        Ok(TransformResult {
            data: chat_response,
            metadata: TransformMetadata {
                provider_type: provider_type.clone(),
                original_model: original_request.model.clone(),
                transformed_model: context.target_model,
                transformations_applied: transformations,
                warnings: Vec::new(),
                cost_estimate: None,
            },
        })
    }

    async fn transform_embedding_request(
        &self,
        request: &EmbeddingRequest,
        provider_type: &ProviderType,
        provider_config: &HashMap<String, Value>,
    ) -> ProviderResult<TransformResult<ProviderRequest>> {
        // Similar implementation for embedding requests
        let context = TransformContext {
            provider_type: provider_type.clone(),
            original_model: request.model.clone(),
            target_model: self.map_model_name(&request.model, provider_type),
            config: provider_config.clone(),
            metadata: HashMap::new(),
        };

        let request_json =
            serde_json::to_value(request).map_err(|e| ProviderError::Serialization {
                provider: "transform",
                message: format!("Serialization error: {}", e),
            })?;

        let provider_request = self
            .build_openai_compatible_request(request_json, &context)
            .await?;

        Ok(TransformResult {
            data: provider_request,
            metadata: TransformMetadata {
                provider_type: provider_type.clone(),
                original_model: request.model.clone(),
                transformed_model: context.target_model,
                transformations_applied: vec!["embedding_transform".to_string()],
                warnings: Vec::new(),
                cost_estimate: None,
            },
        })
    }

    async fn transform_embedding_response(
        &self,
        response: &ProviderResponse,
        provider_type: &ProviderType,
        original_request: &EmbeddingRequest,
    ) -> ProviderResult<TransformResult<EmbeddingResponse>> {
        let embedding_response: EmbeddingResponse = serde_json::from_value(response.body.clone())
            .map_err(|e| ProviderError::Serialization {
            provider: "transform",
            message: format!("Deserialization error: {}", e),
        })?;

        Ok(TransformResult {
            data: embedding_response,
            metadata: TransformMetadata {
                provider_type: provider_type.clone(),
                original_model: original_request.model.clone(),
                transformed_model: self.map_model_name(&original_request.model, provider_type),
                transformations_applied: vec!["embedding_response_transform".to_string()],
                warnings: Vec::new(),
                cost_estimate: None,
            },
        })
    }

    fn get_supported_transformations(&self, provider_type: &ProviderType) -> Vec<String> {
        self.pipelines
            .get(provider_type)
            .map(|pipeline| {
                pipeline
                    .transforms
                    .iter()
                    .map(|t| t.name().to_string())
                    .collect()
            })
            .unwrap_or_default()
    }

    async fn validate_request_compatibility(
        &self,
        request: &TransformChatRequest,
        provider_type: &ProviderType,
    ) -> ProviderResult<Vec<String>> {
        let mut issues = Vec::new();

        // Check for unsupported features
        match provider_type {
            ProviderType::Anthropic => {
                if request.functions.is_some() {
                    issues.push(
                        "Functions are not supported by Anthropic, use tools instead".to_string(),
                    );
                }
                if request.logit_bias.is_some() {
                    issues.push("Logit bias is not supported by Anthropic".to_string());
                }
            }
            ProviderType::VertexAI => {
                if request.functions.is_some() || request.tools.is_some() {
                    issues.push("Function calling support limited in Vertex AI models".to_string());
                }
            }
            _ => {}
        }

        Ok(issues)
    }
}

impl DefaultTransformEngine {
    async fn build_anthropic_request(
        &self,
        _request: Value,
        _context: &TransformContext,
    ) -> ProviderResult<ProviderRequest> {
        // Build Anthropic-specific request format
        Ok(ProviderRequest {
            endpoint: "/v1/messages".to_string(),
            method: "POST".to_string(),
            headers: HashMap::from([
                ("Content-Type".to_string(), "application/json".to_string()),
                ("anthropic-version".to_string(), "2023-06-01".to_string()),
            ]),
            body: serde_json::json!({}), // Would contain transformed request
            query_params: HashMap::new(),
        })
    }

    async fn build_vertexai_request(
        &self,
        _request: Value,
        context: &TransformContext,
    ) -> ProviderResult<ProviderRequest> {
        // Build VertexAI/Gemini-specific request format
        Ok(ProviderRequest {
            endpoint: format!("/v1/models/{}:generateContent", context.target_model),
            method: "POST".to_string(),
            headers: HashMap::from([("Content-Type".to_string(), "application/json".to_string())]),
            body: serde_json::json!({}), // Would contain transformed request
            query_params: HashMap::new(),
        })
    }

    async fn build_openai_compatible_request(
        &self,
        request: Value,
        _context: &TransformContext,
    ) -> ProviderResult<ProviderRequest> {
        // Build OpenAI-compatible request format
        Ok(ProviderRequest {
            endpoint: "/v1/chat/completions".to_string(),
            method: "POST".to_string(),
            headers: HashMap::from([("Content-Type".to_string(), "application/json".to_string())]),
            body: request,
            query_params: HashMap::new(),
        })
    }
}

// Example transformation implementations
#[derive(Default)]
pub struct AnthropicMessageTransform;
#[derive(Default)]
pub struct AnthropicParameterTransform;
#[derive(Default)]
pub struct GoogleMessageTransform;
#[derive(Default)]
pub struct GoogleParameterTransform;

impl AnthropicMessageTransform {
    pub fn new() -> Self {
        Self
    }
}

impl AnthropicParameterTransform {
    pub fn new() -> Self {
        Self
    }
}

impl GoogleMessageTransform {
    pub fn new() -> Self {
        Self
    }
}

impl GoogleParameterTransform {
    pub fn new() -> Self {
        Self
    }
}

#[async_trait]
impl Transform for AnthropicMessageTransform {
    async fn transform_request(
        &self,
        request: Value,
        _context: &TransformContext,
    ) -> ProviderResult<Value> {
        // Transform OpenAI messages to Anthropic format
        // Implementation would handle message role mapping, content structure, etc.
        Ok(request)
    }

    async fn transform_response(
        &self,
        response: Value,
        _context: &TransformContext,
    ) -> ProviderResult<Value> {
        // Transform Anthropic response back to OpenAI format
        Ok(response)
    }

    fn name(&self) -> &str {
        "anthropic_message_transform"
    }
}

#[async_trait]
impl Transform for AnthropicParameterTransform {
    async fn transform_request(
        &self,
        request: Value,
        _context: &TransformContext,
    ) -> ProviderResult<Value> {
        // Transform OpenAI parameters to Anthropic equivalents
        Ok(request)
    }

    async fn transform_response(
        &self,
        response: Value,
        _context: &TransformContext,
    ) -> ProviderResult<Value> {
        Ok(response)
    }

    fn name(&self) -> &str {
        "anthropic_parameter_transform"
    }
}

#[async_trait]
impl Transform for GoogleMessageTransform {
    async fn transform_request(
        &self,
        request: Value,
        _context: &TransformContext,
    ) -> ProviderResult<Value> {
        // Transform OpenAI messages to Google format
        Ok(request)
    }

    async fn transform_response(
        &self,
        response: Value,
        _context: &TransformContext,
    ) -> ProviderResult<Value> {
        // Transform Google response back to OpenAI format
        Ok(response)
    }

    fn name(&self) -> &str {
        "google_message_transform"
    }
}

#[async_trait]
impl Transform for GoogleParameterTransform {
    async fn transform_request(
        &self,
        request: Value,
        _context: &TransformContext,
    ) -> ProviderResult<Value> {
        // Transform OpenAI parameters to Google equivalents
        Ok(request)
    }

    async fn transform_response(
        &self,
        response: Value,
        _context: &TransformContext,
    ) -> ProviderResult<Value> {
        Ok(response)
    }

    fn name(&self) -> &str {
        "google_parameter_transform"
    }
}