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
//! Milvus Provider Configuration
//!
//! Configuration for Milvus vector database access including connection settings
//! and authentication options.
//!
//! Milvus is an open-source vector database designed for AI applications,
//! providing high-performance similarity search and vector storage.
//!
//! Reference: <https://milvus.io/docs/restful_api.md>

use crate::core::traits::provider::ProviderConfig;
use serde::{Deserialize, Serialize};

/// Default Milvus REST API port
const DEFAULT_PORT: u16 = 19530;

/// Default request timeout in seconds
const DEFAULT_TIMEOUT: u64 = 60;

/// Default maximum retries
const DEFAULT_MAX_RETRIES: u32 = 3;

/// Milvus provider configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MilvusConfig {
    /// Milvus server host (required)
    /// Examples: "localhost", "milvus.example.com", "192.168.1.100"
    pub host: String,

    /// Milvus server port (default: 19530)
    #[serde(default = "default_port")]
    pub port: u16,

    /// Default collection name for operations (optional)
    /// If not specified, must be provided per-request
    #[serde(skip_serializing_if = "Option::is_none")]
    pub collection_name: Option<String>,

    /// Database name (optional, for multi-tenancy)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub database: Option<String>,

    /// Username for authentication (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub username: Option<String>,

    /// Password for authentication (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub password: Option<String>,

    /// API token for authentication (alternative to username/password)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub token: Option<String>,

    /// Use HTTPS instead of HTTP
    #[serde(default)]
    pub use_https: bool,

    /// Request timeout in seconds
    #[serde(default = "default_timeout")]
    pub timeout: u64,

    /// Maximum number of retries for failed requests
    #[serde(default = "default_max_retries")]
    pub max_retries: u32,

    /// Whether to enable debug logging
    #[serde(default)]
    pub debug: bool,
}

fn default_port() -> u16 {
    DEFAULT_PORT
}

fn default_timeout() -> u64 {
    DEFAULT_TIMEOUT
}

fn default_max_retries() -> u32 {
    DEFAULT_MAX_RETRIES
}

impl Default for MilvusConfig {
    fn default() -> Self {
        Self {
            host: "localhost".to_string(),
            port: DEFAULT_PORT,
            collection_name: None,
            database: None,
            username: None,
            password: None,
            token: None,
            use_https: false,
            timeout: DEFAULT_TIMEOUT,
            max_retries: DEFAULT_MAX_RETRIES,
            debug: false,
        }
    }
}

impl ProviderConfig for MilvusConfig {
    fn validate(&self) -> Result<(), String> {
        // Host is required and must not be empty
        if self.host.is_empty() {
            return Err("Milvus host is required".to_string());
        }

        // Validate port range
        if self.port == 0 {
            return Err("Milvus port must be greater than 0".to_string());
        }

        // Validate timeout
        if self.timeout == 0 {
            return Err("Timeout must be greater than 0".to_string());
        }

        // If username is provided, password should also be provided (and vice versa)
        if self.username.is_some() != self.password.is_some() {
            return Err("Both username and password must be provided together".to_string());
        }

        Ok(())
    }

    fn api_key(&self) -> Option<&str> {
        // Milvus uses token-based auth, return token as api_key
        self.token.as_deref()
    }

    fn api_base(&self) -> Option<&str> {
        // Return None since we construct the URL from host/port
        None
    }

    fn timeout(&self) -> std::time::Duration {
        std::time::Duration::from_secs(self.timeout)
    }

    fn max_retries(&self) -> u32 {
        self.max_retries
    }
}

impl MilvusConfig {
    /// Create a new MilvusConfig with the specified host
    pub fn new(host: impl Into<String>) -> Self {
        Self {
            host: host.into(),
            ..Default::default()
        }
    }

    /// Create config with host and port
    pub fn with_host_port(host: impl Into<String>, port: u16) -> Self {
        Self {
            host: host.into(),
            port,
            ..Default::default()
        }
    }

    /// Set the collection name
    pub fn with_collection(mut self, collection: impl Into<String>) -> Self {
        self.collection_name = Some(collection.into());
        self
    }

    /// Set the database name
    pub fn with_database(mut self, database: impl Into<String>) -> Self {
        self.database = Some(database.into());
        self
    }

    /// Set username and password authentication
    pub fn with_credentials(
        mut self,
        username: impl Into<String>,
        password: impl Into<String>,
    ) -> Self {
        self.username = Some(username.into());
        self.password = Some(password.into());
        self
    }

    /// Set token-based authentication
    pub fn with_token(mut self, token: impl Into<String>) -> Self {
        self.token = Some(token.into());
        self
    }

    /// Enable HTTPS
    pub fn with_https(mut self) -> Self {
        self.use_https = true;
        self
    }

    /// Set timeout
    pub fn with_timeout(mut self, timeout_secs: u64) -> Self {
        self.timeout = timeout_secs;
        self
    }

    /// Get the base URL for the Milvus REST API
    pub fn get_api_base(&self) -> String {
        let scheme = if self.use_https { "https" } else { "http" };
        format!("{}://{}:{}", scheme, self.host, self.port)
    }

    /// Get the full URL for a specific endpoint
    pub fn get_endpoint_url(&self, endpoint: &str) -> String {
        let base = self.get_api_base();
        if endpoint.starts_with('/') {
            format!("{}{}", base, endpoint)
        } else {
            format!("{}/{}", base, endpoint)
        }
    }

    /// Get authentication headers
    pub fn get_auth_headers(&self) -> Vec<(String, String)> {
        let mut headers = Vec::new();

        // Token-based auth takes precedence
        if let Some(ref token) = self.token {
            headers.push(("Authorization".to_string(), format!("Bearer {}", token)));
        } else if let (Some(username), Some(password)) = (&self.username, &self.password) {
            // Basic auth
            let credentials = base64_encode(&format!("{}:{}", username, password));
            headers.push((
                "Authorization".to_string(),
                format!("Basic {}", credentials),
            ));
        }

        headers
    }

    /// Get the effective collection name
    pub fn get_collection_name(&self) -> Option<&str> {
        self.collection_name.as_deref()
    }

    /// Create config from environment variables
    pub fn from_env() -> Self {
        Self {
            host: std::env::var("MILVUS_HOST").unwrap_or_else(|_| "localhost".to_string()),
            port: std::env::var("MILVUS_PORT")
                .ok()
                .and_then(|p| p.parse().ok())
                .unwrap_or(DEFAULT_PORT),
            collection_name: std::env::var("MILVUS_COLLECTION").ok(),
            database: std::env::var("MILVUS_DATABASE").ok(),
            username: std::env::var("MILVUS_USERNAME").ok(),
            password: std::env::var("MILVUS_PASSWORD").ok(),
            token: std::env::var("MILVUS_TOKEN")
                .or_else(|_| std::env::var("MILVUS_API_KEY"))
                .ok(),
            use_https: std::env::var("MILVUS_USE_HTTPS")
                .map(|v| v.to_lowercase() == "true" || v == "1")
                .unwrap_or(false),
            timeout: std::env::var("MILVUS_TIMEOUT")
                .ok()
                .and_then(|t| t.parse().ok())
                .unwrap_or(DEFAULT_TIMEOUT),
            max_retries: std::env::var("MILVUS_MAX_RETRIES")
                .ok()
                .and_then(|r| r.parse().ok())
                .unwrap_or(DEFAULT_MAX_RETRIES),
            debug: std::env::var("MILVUS_DEBUG")
                .map(|v| v.to_lowercase() == "true" || v == "1")
                .unwrap_or(false),
        }
    }
}

/// Simple base64 encoding for basic auth
fn base64_encode(input: &str) -> String {
    use base64::{Engine, engine::general_purpose::STANDARD};
    STANDARD.encode(input.as_bytes())
}

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

    #[test]
    fn test_milvus_config_default() {
        let config = MilvusConfig::default();
        assert_eq!(config.host, "localhost");
        assert_eq!(config.port, 19530);
        assert!(config.collection_name.is_none());
        assert!(config.username.is_none());
        assert!(config.password.is_none());
        assert!(config.token.is_none());
        assert!(!config.use_https);
        assert_eq!(config.timeout, 60);
        assert_eq!(config.max_retries, 3);
    }

    #[test]
    fn test_milvus_config_new() {
        let config = MilvusConfig::new("milvus.example.com");
        assert_eq!(config.host, "milvus.example.com");
        assert_eq!(config.port, 19530);
    }

    #[test]
    fn test_milvus_config_with_host_port() {
        let config = MilvusConfig::with_host_port("milvus.example.com", 19531);
        assert_eq!(config.host, "milvus.example.com");
        assert_eq!(config.port, 19531);
    }

    #[test]
    fn test_milvus_config_builder_pattern() {
        let config = MilvusConfig::new("milvus.example.com")
            .with_collection("my_collection")
            .with_database("my_database")
            .with_credentials("user", "pass")
            .with_https()
            .with_timeout(120);

        assert_eq!(config.host, "milvus.example.com");
        assert_eq!(config.collection_name, Some("my_collection".to_string()));
        assert_eq!(config.database, Some("my_database".to_string()));
        assert_eq!(config.username, Some("user".to_string()));
        assert_eq!(config.password, Some("pass".to_string()));
        assert!(config.use_https);
        assert_eq!(config.timeout, 120);
    }

    #[test]
    fn test_milvus_config_get_api_base() {
        let config = MilvusConfig::new("milvus.example.com");
        assert_eq!(config.get_api_base(), "http://milvus.example.com:19530");

        let config_https = MilvusConfig::new("milvus.example.com").with_https();
        assert_eq!(
            config_https.get_api_base(),
            "https://milvus.example.com:19530"
        );
    }

    #[test]
    fn test_milvus_config_get_endpoint_url() {
        let config = MilvusConfig::new("milvus.example.com");
        assert_eq!(
            config.get_endpoint_url("/v1/vector/insert"),
            "http://milvus.example.com:19530/v1/vector/insert"
        );
        assert_eq!(
            config.get_endpoint_url("v1/vector/search"),
            "http://milvus.example.com:19530/v1/vector/search"
        );
    }

    #[test]
    fn test_milvus_config_validation_valid() {
        let config = MilvusConfig::new("milvus.example.com");
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_milvus_config_validation_empty_host() {
        let config = MilvusConfig::new("");
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_milvus_config_validation_zero_port() {
        let mut config = MilvusConfig::new("milvus.example.com");
        config.port = 0;
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_milvus_config_validation_zero_timeout() {
        let mut config = MilvusConfig::new("milvus.example.com");
        config.timeout = 0;
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_milvus_config_validation_partial_credentials() {
        let mut config = MilvusConfig::new("milvus.example.com");
        config.username = Some("user".to_string());
        // password not set
        assert!(config.validate().is_err());

        let mut config2 = MilvusConfig::new("milvus.example.com");
        config2.password = Some("pass".to_string());
        // username not set
        assert!(config2.validate().is_err());
    }

    #[test]
    fn test_milvus_config_validation_full_credentials() {
        let config = MilvusConfig::new("milvus.example.com").with_credentials("user", "pass");
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_milvus_config_auth_headers_token() {
        let config = MilvusConfig::new("milvus.example.com").with_token("my-secret-token");
        let headers = config.get_auth_headers();
        assert_eq!(headers.len(), 1);
        assert_eq!(headers[0].0, "Authorization");
        assert!(headers[0].1.starts_with("Bearer "));
    }

    #[test]
    fn test_milvus_config_auth_headers_basic() {
        let config = MilvusConfig::new("milvus.example.com").with_credentials("user", "pass");
        let headers = config.get_auth_headers();
        assert_eq!(headers.len(), 1);
        assert_eq!(headers[0].0, "Authorization");
        assert!(headers[0].1.starts_with("Basic "));
    }

    #[test]
    fn test_milvus_config_auth_headers_none() {
        let config = MilvusConfig::new("milvus.example.com");
        let headers = config.get_auth_headers();
        assert!(headers.is_empty());
    }

    #[test]
    fn test_milvus_config_provider_config_trait() {
        let config = MilvusConfig::new("milvus.example.com")
            .with_token("my-token")
            .with_timeout(90);

        assert_eq!(config.api_key(), Some("my-token"));
        assert_eq!(config.api_base(), None);
        assert_eq!(config.timeout(), std::time::Duration::from_secs(90));
        assert_eq!(config.max_retries(), 3);
    }

    #[test]
    fn test_milvus_config_serialization() {
        let config = MilvusConfig::new("milvus.example.com")
            .with_collection("test_collection")
            .with_https();

        let json = serde_json::to_value(&config).unwrap();
        assert_eq!(json["host"], "milvus.example.com");
        assert_eq!(json["collection_name"], "test_collection");
        assert_eq!(json["use_https"], true);
    }

    #[test]
    fn test_milvus_config_deserialization() {
        let json = r#"{
            "host": "milvus.example.com",
            "port": 19531,
            "collection_name": "my_collection",
            "use_https": true
        }"#;

        let config: MilvusConfig = serde_json::from_str(json).unwrap();
        assert_eq!(config.host, "milvus.example.com");
        assert_eq!(config.port, 19531);
        assert_eq!(config.collection_name, Some("my_collection".to_string()));
        assert!(config.use_https);
    }
}