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
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
//! Request types for OpenAI-compatible API
//!
//! This module defines request structures for chat completions, text completions,
//! embeddings, and image generation.

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

use super::audio::AudioParams;
use super::messages::ChatMessage;
use super::tools::{Function, FunctionCall, Tool, ToolChoice};

/// Chat completion request (OpenAI compatible)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatCompletionRequest {
    /// Model to use for completion
    pub model: String,
    /// List of messages
    pub messages: Vec<ChatMessage>,
    /// Temperature (0.0 to 2.0)
    pub temperature: Option<f32>,
    /// Maximum tokens to generate
    pub max_tokens: Option<u32>,
    /// Maximum completion tokens (newer parameter)
    pub max_completion_tokens: Option<u32>,
    /// Top-p sampling
    pub top_p: Option<f32>,
    /// Number of completions to generate
    pub n: Option<u32>,
    /// Whether to stream the response
    pub stream: Option<bool>,
    /// Stream options
    pub stream_options: Option<StreamOptions>,
    /// Stop sequences
    pub stop: Option<Vec<String>>,
    /// Presence penalty
    pub presence_penalty: Option<f32>,
    /// Frequency penalty
    pub frequency_penalty: Option<f32>,
    /// Logit bias
    pub logit_bias: Option<HashMap<String, f32>>,
    /// User identifier
    pub user: Option<String>,
    /// Function calling (legacy)
    pub functions: Option<Vec<Function>>,
    /// Function call (legacy)
    pub function_call: Option<FunctionCall>,
    /// Tools for function calling
    pub tools: Option<Vec<Tool>>,
    /// Tool choice
    pub tool_choice: Option<ToolChoice>,
    /// Response format
    pub response_format: Option<ResponseFormat>,
    /// Seed for deterministic outputs
    pub seed: Option<u32>,
    /// Logprobs
    pub logprobs: Option<bool>,
    /// Top logprobs
    pub top_logprobs: Option<u32>,
    /// Modalities (for multimodal models)
    pub modalities: Option<Vec<String>>,
    /// Audio parameters
    pub audio: Option<AudioParams>,
    /// Reasoning effort for o-series and GPT-5.x models ("low", "medium", "high")
    pub reasoning_effort: Option<String>,
    /// Whether to store the response for model improvement (OpenAI)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub store: Option<bool>,
    /// Key-value metadata to attach to the request (OpenAI)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<HashMap<String, String>>,
    /// Service tier for the request (OpenAI, e.g. "auto", "default", "flex")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub service_tier: Option<String>,
}

impl Default for ChatCompletionRequest {
    fn default() -> Self {
        Self {
            model: "gpt-3.5-turbo".to_string(),
            messages: vec![],
            temperature: None,
            max_tokens: None,
            max_completion_tokens: None,
            top_p: None,
            n: None,
            stream: None,
            stream_options: None,
            stop: None,
            presence_penalty: None,
            frequency_penalty: None,
            logit_bias: None,
            user: None,
            functions: None,
            function_call: None,
            tools: None,
            tool_choice: None,
            response_format: None,
            seed: None,
            logprobs: None,
            top_logprobs: None,
            modalities: None,
            audio: None,
            reasoning_effort: None,
            store: None,
            metadata: None,
            service_tier: None,
        }
    }
}

/// Stream options
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StreamOptions {
    /// Include usage in stream
    pub include_usage: Option<bool>,
}

/// Response format
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResponseFormat {
    /// Format type
    #[serde(rename = "type")]
    pub format_type: String,
    /// JSON schema (for structured outputs)
    pub json_schema: Option<serde_json::Value>,
}

/// Text completion request (legacy)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompletionRequest {
    /// Model to use
    pub model: String,
    /// Prompt text
    pub prompt: String,
    /// Maximum tokens to generate
    pub max_tokens: Option<u32>,
    /// Temperature
    pub temperature: Option<f64>,
    /// Top-p
    pub top_p: Option<f64>,
    /// Number of completions
    pub n: Option<u32>,
    /// Stream response
    pub stream: Option<bool>,
    /// Stop sequences
    pub stop: Option<Vec<String>>,
    /// Presence penalty
    pub presence_penalty: Option<f64>,
    /// Frequency penalty
    pub frequency_penalty: Option<f64>,
    /// Logit bias
    pub logit_bias: Option<HashMap<String, f64>>,
    /// User identifier
    pub user: Option<String>,
    /// Include the log probabilities
    pub logprobs: Option<u32>,
    /// Echo back the prompt
    pub echo: Option<bool>,
}

/// Embedding request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmbeddingRequest {
    /// Model to use
    pub model: String,
    /// Input text or array of texts
    pub input: serde_json::Value,
    /// User identifier
    pub user: Option<String>,
}

/// Image generation request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageGenerationRequest {
    /// Prompt for image generation
    pub prompt: String,
    /// Model to use
    pub model: Option<String>,
    /// Number of images
    pub n: Option<u32>,
    /// Image size
    pub size: Option<String>,
    /// Response format
    pub response_format: Option<String>,
    /// User identifier
    pub user: Option<String>,
}

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

    // ==================== ChatCompletionRequest Tests ====================

    #[test]
    fn test_chat_completion_request_default() {
        let req = ChatCompletionRequest::default();
        assert_eq!(req.model, "gpt-3.5-turbo");
        assert!(req.messages.is_empty());
        assert!(req.temperature.is_none());
        assert!(req.max_tokens.is_none());
        assert!(req.stream.is_none());
    }

    #[test]
    fn test_chat_completion_request_with_model() {
        let req = ChatCompletionRequest {
            model: "gpt-4".to_string(),
            ..Default::default()
        };

        assert_eq!(req.model, "gpt-4");
    }

    #[test]
    fn test_chat_completion_request_with_temperature() {
        let req = ChatCompletionRequest {
            temperature: Some(0.7),
            ..Default::default()
        };

        assert_eq!(req.temperature, Some(0.7));
    }

    #[test]
    fn test_chat_completion_request_with_max_tokens() {
        let req = ChatCompletionRequest {
            max_tokens: Some(100),
            max_completion_tokens: Some(150),
            ..Default::default()
        };

        assert_eq!(req.max_tokens, Some(100));
        assert_eq!(req.max_completion_tokens, Some(150));
    }

    #[test]
    fn test_chat_completion_request_with_sampling() {
        let req = ChatCompletionRequest {
            top_p: Some(0.9),
            n: Some(3),
            ..Default::default()
        };

        assert_eq!(req.top_p, Some(0.9));
        assert_eq!(req.n, Some(3));
    }

    #[test]
    fn test_chat_completion_request_with_stream() {
        let req = ChatCompletionRequest {
            stream: Some(true),
            stream_options: Some(StreamOptions {
                include_usage: Some(true),
            }),
            ..Default::default()
        };

        assert_eq!(req.stream, Some(true));
        assert!(req.stream_options.is_some());
    }

    #[test]
    fn test_chat_completion_request_with_stop() {
        let req = ChatCompletionRequest {
            stop: Some(vec!["END".to_string(), "STOP".to_string()]),
            ..Default::default()
        };

        assert_eq!(req.stop.as_ref().unwrap().len(), 2);
    }

    #[test]
    fn test_chat_completion_request_with_penalties() {
        let req = ChatCompletionRequest {
            presence_penalty: Some(0.5),
            frequency_penalty: Some(0.3),
            ..Default::default()
        };

        assert_eq!(req.presence_penalty, Some(0.5));
        assert_eq!(req.frequency_penalty, Some(0.3));
    }

    #[test]
    fn test_chat_completion_request_with_logit_bias() {
        let mut logit_bias = HashMap::new();
        logit_bias.insert("123".to_string(), -100.0);
        logit_bias.insert("456".to_string(), 50.0);

        let req = ChatCompletionRequest {
            logit_bias: Some(logit_bias),
            ..Default::default()
        };

        assert!(req.logit_bias.is_some());
        assert_eq!(req.logit_bias.as_ref().unwrap().len(), 2);
    }

    #[test]
    fn test_chat_completion_request_with_user() {
        let req = ChatCompletionRequest {
            user: Some("user-123".to_string()),
            ..Default::default()
        };

        assert_eq!(req.user, Some("user-123".to_string()));
    }

    #[test]
    fn test_chat_completion_request_with_response_format() {
        let req = ChatCompletionRequest {
            response_format: Some(ResponseFormat {
                format_type: "json_object".to_string(),
                json_schema: None,
            }),
            ..Default::default()
        };

        assert!(req.response_format.is_some());
        assert_eq!(
            req.response_format.as_ref().unwrap().format_type,
            "json_object"
        );
    }

    #[test]
    fn test_chat_completion_request_with_seed() {
        let req = ChatCompletionRequest {
            seed: Some(42),
            ..Default::default()
        };

        assert_eq!(req.seed, Some(42));
    }

    #[test]
    fn test_chat_completion_request_with_logprobs() {
        let req = ChatCompletionRequest {
            logprobs: Some(true),
            top_logprobs: Some(5),
            ..Default::default()
        };

        assert_eq!(req.logprobs, Some(true));
        assert_eq!(req.top_logprobs, Some(5));
    }

    #[test]
    fn test_chat_completion_request_with_modalities() {
        let req = ChatCompletionRequest {
            modalities: Some(vec!["text".to_string(), "audio".to_string()]),
            ..Default::default()
        };

        assert_eq!(req.modalities.as_ref().unwrap().len(), 2);
    }

    #[test]
    fn test_chat_completion_request_serialize() {
        let req = ChatCompletionRequest {
            model: "gpt-4-turbo".to_string(),
            temperature: Some(0.8),
            max_tokens: Some(500),
            ..Default::default()
        };

        let json = serde_json::to_string(&req).unwrap();
        assert!(json.contains("gpt-4-turbo"));
        assert!(json.contains("0.8"));
        assert!(json.contains("500"));
    }

    #[test]
    fn test_chat_completion_request_deserialize() {
        let json = r#"{"model":"gpt-4","messages":[],"temperature":0.5}"#;
        let req: ChatCompletionRequest = serde_json::from_str(json).unwrap();

        assert_eq!(req.model, "gpt-4");
        assert_eq!(req.temperature, Some(0.5));
    }

    #[test]
    fn test_chat_completion_request_clone() {
        let req = ChatCompletionRequest {
            model: "claude-3-opus".to_string(),
            temperature: Some(0.7),
            ..Default::default()
        };

        let cloned = req.clone();
        assert_eq!(req.model, cloned.model);
        assert_eq!(req.temperature, cloned.temperature);
    }

    // ==================== StreamOptions Tests ====================

    #[test]
    fn test_stream_options_with_usage() {
        let options = StreamOptions {
            include_usage: Some(true),
        };

        assert_eq!(options.include_usage, Some(true));
    }

    #[test]
    fn test_stream_options_without_usage() {
        let options = StreamOptions {
            include_usage: Some(false),
        };

        assert_eq!(options.include_usage, Some(false));
    }

    #[test]
    fn test_stream_options_serialize() {
        let options = StreamOptions {
            include_usage: Some(true),
        };

        let json = serde_json::to_string(&options).unwrap();
        assert!(json.contains("include_usage"));
        assert!(json.contains("true"));
    }

    // ==================== ResponseFormat Tests ====================

    #[test]
    fn test_response_format_text() {
        let format = ResponseFormat {
            format_type: "text".to_string(),
            json_schema: None,
        };

        assert_eq!(format.format_type, "text");
        assert!(format.json_schema.is_none());
    }

    #[test]
    fn test_response_format_json_object() {
        let format = ResponseFormat {
            format_type: "json_object".to_string(),
            json_schema: None,
        };

        assert_eq!(format.format_type, "json_object");
    }

    #[test]
    fn test_response_format_with_schema() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "name": {"type": "string"},
                "age": {"type": "integer"}
            }
        });

        let format = ResponseFormat {
            format_type: "json_schema".to_string(),
            json_schema: Some(schema.clone()),
        };

        assert_eq!(format.format_type, "json_schema");
        assert!(format.json_schema.is_some());
    }

    #[test]
    fn test_response_format_serialize() {
        let format = ResponseFormat {
            format_type: "json_object".to_string(),
            json_schema: None,
        };

        let json = serde_json::to_string(&format).unwrap();
        assert!(json.contains("\"type\":\"json_object\""));
    }

    // ==================== CompletionRequest Tests ====================

    #[test]
    fn test_completion_request_creation() {
        let req = CompletionRequest {
            model: "gpt-3.5-turbo-instruct".to_string(),
            prompt: "Once upon a time".to_string(),
            max_tokens: Some(100),
            temperature: Some(0.7),
            top_p: None,
            n: None,
            stream: None,
            stop: None,
            presence_penalty: None,
            frequency_penalty: None,
            logit_bias: None,
            user: None,
            logprobs: None,
            echo: None,
        };

        assert_eq!(req.model, "gpt-3.5-turbo-instruct");
        assert_eq!(req.prompt, "Once upon a time");
        assert_eq!(req.max_tokens, Some(100));
    }

    #[test]
    fn test_completion_request_with_all_options() {
        let req = CompletionRequest {
            model: "text-davinci-003".to_string(),
            prompt: "Complete this:".to_string(),
            max_tokens: Some(50),
            temperature: Some(0.5),
            top_p: Some(0.9),
            n: Some(2),
            stream: Some(true),
            stop: Some(vec!["END".to_string()]),
            presence_penalty: Some(0.3),
            frequency_penalty: Some(0.2),
            logit_bias: None,
            user: Some("test-user".to_string()),
            logprobs: Some(3),
            echo: Some(true),
        };

        assert_eq!(req.n, Some(2));
        assert_eq!(req.stream, Some(true));
        assert_eq!(req.logprobs, Some(3));
        assert_eq!(req.echo, Some(true));
    }

    #[test]
    fn test_completion_request_serialize() {
        let req = CompletionRequest {
            model: "gpt-3.5-turbo-instruct".to_string(),
            prompt: "Hello".to_string(),
            max_tokens: Some(10),
            temperature: None,
            top_p: None,
            n: None,
            stream: None,
            stop: None,
            presence_penalty: None,
            frequency_penalty: None,
            logit_bias: None,
            user: None,
            logprobs: None,
            echo: None,
        };

        let json = serde_json::to_string(&req).unwrap();
        assert!(json.contains("gpt-3.5-turbo-instruct"));
        assert!(json.contains("Hello"));
    }

    // ==================== EmbeddingRequest Tests ====================

    #[test]
    fn test_embedding_request_single_input() {
        let req = EmbeddingRequest {
            model: "text-embedding-ada-002".to_string(),
            input: serde_json::json!("Hello world"),
            user: None,
        };

        assert_eq!(req.model, "text-embedding-ada-002");
        assert!(req.input.is_string());
    }

    #[test]
    fn test_embedding_request_array_input() {
        let req = EmbeddingRequest {
            model: "text-embedding-3-small".to_string(),
            input: serde_json::json!(["Hello", "World"]),
            user: Some("user-123".to_string()),
        };

        assert_eq!(req.model, "text-embedding-3-small");
        assert!(req.input.is_array());
        assert_eq!(req.user, Some("user-123".to_string()));
    }

    #[test]
    fn test_embedding_request_serialize() {
        let req = EmbeddingRequest {
            model: "text-embedding-3-large".to_string(),
            input: serde_json::json!("Test input"),
            user: None,
        };

        let json = serde_json::to_string(&req).unwrap();
        assert!(json.contains("text-embedding-3-large"));
        assert!(json.contains("Test input"));
    }

    // ==================== ImageGenerationRequest Tests ====================

    #[test]
    fn test_image_generation_request_minimal() {
        let req = ImageGenerationRequest {
            prompt: "A beautiful sunset".to_string(),
            model: None,
            n: None,
            size: None,
            response_format: None,
            user: None,
        };

        assert_eq!(req.prompt, "A beautiful sunset");
        assert!(req.model.is_none());
    }

    #[test]
    fn test_image_generation_request_full() {
        let req = ImageGenerationRequest {
            prompt: "A cat sitting on a chair".to_string(),
            model: Some("dall-e-3".to_string()),
            n: Some(2),
            size: Some("1024x1024".to_string()),
            response_format: Some("url".to_string()),
            user: Some("user-456".to_string()),
        };

        assert_eq!(req.model, Some("dall-e-3".to_string()));
        assert_eq!(req.n, Some(2));
        assert_eq!(req.size, Some("1024x1024".to_string()));
        assert_eq!(req.response_format, Some("url".to_string()));
    }

    #[test]
    fn test_image_generation_request_b64_format() {
        let req = ImageGenerationRequest {
            prompt: "Abstract art".to_string(),
            model: Some("dall-e-2".to_string()),
            n: Some(1),
            size: Some("512x512".to_string()),
            response_format: Some("b64_json".to_string()),
            user: None,
        };

        assert_eq!(req.response_format, Some("b64_json".to_string()));
    }

    #[test]
    fn test_image_generation_request_serialize() {
        let req = ImageGenerationRequest {
            prompt: "Mountain landscape".to_string(),
            model: Some("dall-e-3".to_string()),
            n: Some(1),
            size: Some("1792x1024".to_string()),
            response_format: None,
            user: None,
        };

        let json = serde_json::to_string(&req).unwrap();
        assert!(json.contains("Mountain landscape"));
        assert!(json.contains("dall-e-3"));
        assert!(json.contains("1792x1024"));
    }

    #[test]
    fn test_image_generation_request_clone() {
        let req = ImageGenerationRequest {
            prompt: "Test image".to_string(),
            model: Some("dall-e-3".to_string()),
            n: Some(1),
            size: None,
            response_format: None,
            user: None,
        };

        let cloned = req.clone();
        assert_eq!(req.prompt, cloned.prompt);
        assert_eq!(req.model, cloned.model);
    }
}