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
//! OpenAI Fine-tuning Module
//!
//! Fine-tuning job management following the unified architecture

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

use crate::core::providers::unified_provider::ProviderError;

/// OpenAI Fine-tuning Job creation request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OpenAIFineTuningRequest {
    /// The ID of an uploaded file that contains training data
    pub training_file: String,

    /// The ID of an uploaded file that contains validation data
    #[serde(skip_serializing_if = "Option::is_none")]
    pub validation_file: Option<String>,

    /// The name of the model to fine-tune
    pub model: String,

    /// The hyperparameters used for the fine-tuning job
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hyperparameters: Option<FineTuningHyperparameters>,

    /// A string of up to 18 characters for the suffix
    #[serde(skip_serializing_if = "Option::is_none")]
    pub suffix: Option<String>,

    /// Set of key-value pairs for metadata
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<HashMap<String, String>>,

    /// List of integrations to enable for this fine-tuning job
    #[serde(skip_serializing_if = "Option::is_none")]
    pub integrations: Option<Vec<Integration>>,

    /// Seed for deterministic training
    #[serde(skip_serializing_if = "Option::is_none")]
    pub seed: Option<i32>,
}

/// Hyperparameters for fine-tuning
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FineTuningHyperparameters {
    /// The number of epochs to train the model for
    #[serde(skip_serializing_if = "Option::is_none")]
    pub n_epochs: Option<u32>,

    /// Batch size to use for training
    #[serde(skip_serializing_if = "Option::is_none")]
    pub batch_size: Option<u32>,

    /// Learning rate multiplier to use for training
    #[serde(skip_serializing_if = "Option::is_none")]
    pub learning_rate_multiplier: Option<f64>,
}

/// Integration configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Integration {
    /// The type of integration
    #[serde(rename = "type")]
    pub integration_type: String,

    /// Configuration for Weights & Biases integration
    #[serde(skip_serializing_if = "Option::is_none")]
    pub wandb: Option<WandBConfig>,
}

/// Weights & Biases configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WandBConfig {
    /// The name of the project
    #[serde(skip_serializing_if = "Option::is_none")]
    pub project: Option<String>,

    /// Display name for the run
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,

    /// Entity (team) to use for the run
    #[serde(skip_serializing_if = "Option::is_none")]
    pub entity: Option<String>,

    /// Tags for the run
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<String>>,
}

/// OpenAI Fine-tuning Job response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OpenAIFineTuningJob {
    /// The object identifier
    pub id: String,

    /// The object type (always "fine_tuning.job")
    pub object: String,

    /// The Unix timestamp for when the fine-tuning job was created
    pub created_at: i64,

    /// The Unix timestamp for when the fine-tuning job was finished
    #[serde(skip_serializing_if = "Option::is_none")]
    pub finished_at: Option<i64>,

    /// The base model that is being fine-tuned
    pub model: String,

    /// The fine-tuned model name (available after completion)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fine_tuned_model: Option<String>,

    /// The organization that owns the fine-tuning job
    #[serde(skip_serializing_if = "Option::is_none")]
    pub organization_id: Option<String>,

    /// The current status of the fine-tuning job
    pub status: FineTuningStatus,

    /// The hyperparameters used for the fine-tuning job
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hyperparameters: Option<FineTuningHyperparameters>,

    /// The file ID used for training
    pub training_file: String,

    /// The file ID used for validation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub validation_file: Option<String>,

    /// The compiled results file ID(s) for the fine-tuning job
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result_files: Option<Vec<String>>,

    /// The total number of billable tokens processed by this fine-tuning job
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trained_tokens: Option<u64>,

    /// The suffix used to identify the fine-tuned model
    #[serde(skip_serializing_if = "Option::is_none")]
    pub suffix: Option<String>,

    /// Error information if the job failed
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<FineTuningError>,

    /// Estimated finish time
    #[serde(skip_serializing_if = "Option::is_none")]
    pub estimated_finish: Option<i64>,

    /// List of integrations enabled for this job
    #[serde(skip_serializing_if = "Option::is_none")]
    pub integrations: Option<Vec<Integration>>,

    /// Seed used for training
    #[serde(skip_serializing_if = "Option::is_none")]
    pub seed: Option<i32>,
}

/// Fine-tuning job status
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FineTuningStatus {
    ValidatingFiles,
    Queued,
    Running,
    Succeeded,
    Failed,
    Cancelled,
}

/// Fine-tuning error details
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FineTuningError {
    /// Error code
    pub code: String,

    /// Error message
    pub message: String,

    /// Additional error parameters
    #[serde(skip_serializing_if = "Option::is_none")]
    pub param: Option<String>,
}

/// Fine-tuning job events
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FineTuningEvent {
    pub id: String,
    pub object: String,
    pub created_at: i64,
    pub level: EventLevel,
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<serde_json::Value>,
    #[serde(rename = "type")]
    pub event_type: EventType,
}

/// Event level
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum EventLevel {
    Info,
    Warn,
    Error,
}

/// Event type
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EventType {
    Message,
    Metrics,
}

/// Fine-tuning checkpoint
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FineTuningCheckpoint {
    pub id: String,
    pub object: String,
    pub created_at: i64,
    pub fine_tuned_model_checkpoint: String,
    pub fine_tuning_job_id: String,
    pub metrics: CheckpointMetrics,
    pub step_number: u32,
}

/// Checkpoint metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CheckpointMetrics {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub step: Option<u32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub train_loss: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub train_mean_token_accuracy: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub valid_loss: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub valid_mean_token_accuracy: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub full_valid_loss: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub full_valid_mean_token_accuracy: Option<f64>,
}

/// Fine-tuning utilities
pub struct OpenAIFineTuningUtils;

impl OpenAIFineTuningUtils {
    /// Get supported fine-tuning models
    pub fn get_supported_models() -> Vec<&'static str> {
        vec![
            "gpt-3.5-turbo",
            "gpt-3.5-turbo-1106",
            "gpt-3.5-turbo-0613",
            "gpt-4o-mini-2024-07-18",
            "gpt-4-0613",
            "babbage-002",
            "davinci-002",
        ]
    }

    /// Check if model supports fine-tuning
    pub fn supports_fine_tuning(model_id: &str) -> bool {
        Self::get_supported_models().contains(&model_id)
    }

    /// Create fine-tuning job request
    pub fn create_job_request(
        training_file: String,
        model: String,
        suffix: Option<String>,
        hyperparameters: Option<FineTuningHyperparameters>,
    ) -> OpenAIFineTuningRequest {
        OpenAIFineTuningRequest {
            training_file,
            validation_file: None,
            model,
            hyperparameters,
            suffix,
            metadata: None,
            integrations: None,
            seed: None,
        }
    }

    /// Create job with Weights & Biases integration
    pub fn create_job_with_wandb(
        training_file: String,
        model: String,
        project: String,
        tags: Vec<String>,
    ) -> OpenAIFineTuningRequest {
        let wandb_integration = Integration {
            integration_type: "wandb".to_string(),
            wandb: Some(WandBConfig {
                project: Some(project),
                name: None,
                entity: None,
                tags: Some(tags),
            }),
        };

        OpenAIFineTuningRequest {
            training_file,
            validation_file: None,
            model,
            hyperparameters: None,
            suffix: None,
            metadata: None,
            integrations: Some(vec![wandb_integration]),
            seed: None,
        }
    }

    /// Validate fine-tuning request
    pub fn validate_request(request: &OpenAIFineTuningRequest) -> Result<(), ProviderError> {
        // Check if model supports fine-tuning
        if !Self::supports_fine_tuning(&request.model) {
            return Err(ProviderError::ModelNotFound {
                provider: "openai",
                model: request.model.clone(),
            });
        }

        // Check suffix length
        if let Some(suffix) = &request.suffix {
            if suffix.len() > 40 {
                return Err(ProviderError::InvalidRequest {
                    provider: "openai",
                    message: "Suffix must be 40 characters or less".to_string(),
                });
            }

            // Check suffix contains only alphanumeric, hyphens, and underscores
            if !suffix
                .chars()
                .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
            {
                return Err(ProviderError::InvalidRequest {
                    provider: "openai",
                    message:
                        "Suffix can only contain alphanumeric characters, hyphens, and underscores"
                            .to_string(),
                });
            }
        }

        // Validate hyperparameters
        if let Some(hyperparams) = &request.hyperparameters {
            if let Some(n_epochs) = hyperparams.n_epochs
                && (n_epochs == 0 || n_epochs > 50)
            {
                return Err(ProviderError::InvalidRequest {
                    provider: "openai",
                    message: "n_epochs must be between 1 and 50".to_string(),
                });
            }

            if let Some(batch_size) = hyperparams.batch_size
                && ![1, 2, 4, 8, 16, 32].contains(&batch_size)
            {
                return Err(ProviderError::InvalidRequest {
                    provider: "openai",
                    message: "batch_size must be one of: 1, 2, 4, 8, 16, 32".to_string(),
                });
            }

            if let Some(lr_multiplier) = hyperparams.learning_rate_multiplier
                && (lr_multiplier <= 0.0 || lr_multiplier > 10.0)
            {
                return Err(ProviderError::InvalidRequest {
                    provider: "openai",
                    message: "learning_rate_multiplier must be between 0 and 10".to_string(),
                });
            }
        }

        Ok(())
    }

    /// Estimate cost for fine-tuning
    pub fn estimate_cost(model: &str, num_tokens: u64) -> Result<f64, ProviderError> {
        let cost_per_1k_tokens = match model {
            "gpt-3.5-turbo" | "gpt-3.5-turbo-1106" | "gpt-3.5-turbo-0613" => 0.008,
            "gpt-4o-mini-2024-07-18" => 0.0003,
            "gpt-4-0613" => 0.03,
            "babbage-002" => 0.0004,
            "davinci-002" => 0.006,
            _ => {
                return Err(ProviderError::InvalidRequest {
                    provider: "openai",
                    message: format!("Unknown fine-tuning model: {}", model),
                });
            }
        };

        Ok((num_tokens as f64 / 1000.0) * cost_per_1k_tokens)
    }
}

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

    #[test]
    fn test_supports_fine_tuning() {
        assert!(OpenAIFineTuningUtils::supports_fine_tuning("gpt-3.5-turbo"));
        assert!(OpenAIFineTuningUtils::supports_fine_tuning("babbage-002"));
        assert!(!OpenAIFineTuningUtils::supports_fine_tuning("gpt-4"));
        assert!(!OpenAIFineTuningUtils::supports_fine_tuning("dall-e-3"));
    }

    #[test]
    fn test_create_job_request() {
        let request = OpenAIFineTuningUtils::create_job_request(
            "file-123".to_string(),
            "gpt-3.5-turbo".to_string(),
            Some("my-model".to_string()),
            None,
        );

        assert_eq!(request.training_file, "file-123");
        assert_eq!(request.model, "gpt-3.5-turbo");
        assert_eq!(request.suffix, Some("my-model".to_string()));
    }

    #[test]
    fn test_validate_request() {
        let valid_request = OpenAIFineTuningUtils::create_job_request(
            "file-123".to_string(),
            "gpt-3.5-turbo".to_string(),
            Some("valid_suffix".to_string()),
            None,
        );
        assert!(OpenAIFineTuningUtils::validate_request(&valid_request).is_ok());

        // Test invalid model
        let invalid_model = OpenAIFineTuningRequest {
            training_file: "file-123".to_string(),
            validation_file: None,
            model: "gpt-4".to_string(),
            hyperparameters: None,
            suffix: None,
            metadata: None,
            integrations: None,
            seed: None,
        };
        assert!(OpenAIFineTuningUtils::validate_request(&invalid_model).is_err());

        // Test invalid suffix
        let mut invalid_suffix = valid_request.clone();
        invalid_suffix.suffix = Some("a".repeat(50)); // Too long
        assert!(OpenAIFineTuningUtils::validate_request(&invalid_suffix).is_err());
    }

    #[test]
    fn test_estimate_cost() {
        let cost = OpenAIFineTuningUtils::estimate_cost("gpt-3.5-turbo", 10000).unwrap();
        assert_eq!(cost, 0.08); // 10k tokens * $0.008/1k tokens

        let cost = OpenAIFineTuningUtils::estimate_cost("babbage-002", 5000).unwrap();
        assert_eq!(cost, 0.002); // 5k tokens * $0.0004/1k tokens

        assert!(OpenAIFineTuningUtils::estimate_cost("unknown-model", 1000).is_err());
    }
}