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
//! Gemini Configuration Module
//!
//! Configuration

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

use crate::core::providers::unified_provider::ProviderError;
use crate::core::traits::provider::ProviderConfig;

/// Configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GeminiConfig {
    /// API key (Google AI Studio)
    pub api_key: Option<String>,

    /// Project ID (Vertex AI)
    pub project_id: Option<String>,

    /// Region (Vertex AI)
    pub location: Option<String>,

    /// Service account JSON (Vertex AI)
    pub service_account_json: Option<String>,

    /// Use Vertex AI or Google AI Studio
    pub use_vertex_ai: bool,

    /// Base URL
    pub base_url: String,

    /// API version
    pub api_version: String,

    /// Request timeout
    pub request_timeout: u64,

    /// Connection timeout
    pub connect_timeout: u64,

    /// Maximum number of retries
    pub max_retries: u32,

    /// Retry delay (milliseconds)
    pub retry_delay_ms: u64,

    /// Enable caching
    pub enable_caching: bool,

    /// Cache TTL (seconds)
    pub cache_ttl_seconds: u64,

    /// Enable search grounding
    pub enable_search_grounding: bool,

    /// Safety settings
    pub safety_settings: Option<Vec<SafetySetting>>,

    /// Custom headers
    pub custom_headers: HashMap<String, String>,

    /// Proxy URL
    pub proxy_url: Option<String>,

    /// Enable debug logging
    pub debug: bool,
}

/// Settings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SafetySetting {
    pub category: String,
    pub threshold: String,
}

impl GeminiConfig {
    /// Create
    pub fn new_google_ai(api_key: impl Into<String>) -> Self {
        Self {
            api_key: Some(api_key.into()),
            project_id: None,
            location: None,
            service_account_json: None,
            use_vertex_ai: false,
            base_url: "https://generativelanguage.googleapis.com".to_string(),
            api_version: "v1beta".to_string(),
            request_timeout: 600,
            connect_timeout: 10,
            max_retries: 3,
            retry_delay_ms: 1000,
            enable_caching: true,
            cache_ttl_seconds: 3600,
            enable_search_grounding: false,
            safety_settings: None,
            custom_headers: HashMap::new(),
            proxy_url: None,
            debug: false,
        }
    }

    /// Create
    pub fn new_vertex_ai(project_id: impl Into<String>, location: impl Into<String>) -> Self {
        let location_str = location.into();
        Self {
            api_key: None,
            project_id: Some(project_id.into()),
            location: Some(location_str.clone()),
            service_account_json: None,
            use_vertex_ai: true,
            base_url: format!("https://{}-aiplatform.googleapis.com", location_str),
            api_version: "v1".to_string(),
            request_timeout: 600,
            connect_timeout: 10,
            max_retries: 3,
            retry_delay_ms: 1000,
            enable_caching: true,
            cache_ttl_seconds: 3600,
            enable_search_grounding: false,
            safety_settings: None,
            custom_headers: HashMap::new(),
            proxy_url: None,
            debug: false,
        }
    }

    /// Create
    pub fn from_env() -> Result<Self, ProviderError> {
        // Try Google AI Studio first
        if let Ok(api_key) = std::env::var("GOOGLE_API_KEY") {
            return Ok(Self::new_google_ai(api_key));
        }

        if let Ok(api_key) = std::env::var("GEMINI_API_KEY") {
            return Ok(Self::new_google_ai(api_key));
        }

        // Try Vertex AI
        if let (Ok(project_id), Ok(location)) = (
            std::env::var("GOOGLE_CLOUD_PROJECT"),
            std::env::var("GOOGLE_CLOUD_LOCATION"),
        ) {
            let mut config = Self::new_vertex_ai(project_id, location);

            // Optional service account
            if let Ok(sa_json) = std::env::var("GOOGLE_APPLICATION_CREDENTIALS") {
                config.service_account_json = Some(sa_json);
            }

            return Ok(config);
        }

        Err(ProviderError::configuration(
            "gemini",
            "No valid Gemini configuration found in environment variables",
        ))
    }

    /// Settings
    pub fn with_safety_settings(mut self, settings: Vec<SafetySetting>) -> Self {
        self.safety_settings = Some(settings);
        self
    }

    /// Settings
    pub fn with_search_grounding(mut self, enabled: bool) -> Self {
        self.enable_search_grounding = enabled;
        self
    }

    /// Settings
    pub fn with_caching(mut self, enabled: bool, ttl_seconds: u64) -> Self {
        self.enable_caching = enabled;
        self.cache_ttl_seconds = ttl_seconds;
        self
    }

    /// Settings
    pub fn with_proxy(mut self, proxy_url: impl Into<String>) -> Self {
        self.proxy_url = Some(proxy_url.into());
        self
    }

    /// Settings
    pub fn with_debug(mut self, debug: bool) -> Self {
        self.debug = debug;
        self
    }

    /// Create
    #[cfg(test)]
    pub fn new_test(api_key: impl Into<String>) -> Self {
        let mut config = Self::new_google_ai(api_key);
        config.request_timeout = 5;
        config.max_retries = 0;
        config
    }

    /// Get
    pub fn get_endpoint(&self, model: &str, operation: &str) -> String {
        if self.use_vertex_ai {
            // Vertex AI endpoint format
            format!(
                "{}/v1/projects/{}/locations/{}/publishers/google/models/{}:{}",
                self.base_url,
                self.project_id.as_ref().unwrap_or(&"".to_string()),
                self.location.as_ref().unwrap_or(&"".to_string()),
                model,
                operation
            )
        } else {
            // Google AI Studio endpoint format
            match operation {
                "streamGenerateContent" => format!(
                    "{}/{}/models/{}:streamGenerateContent?key={}",
                    self.base_url,
                    self.api_version,
                    model,
                    self.api_key.as_ref().unwrap_or(&"".to_string())
                ),
                _ => format!(
                    "{}/{}/models/{}:{}?key={}",
                    self.base_url,
                    self.api_version,
                    model,
                    operation,
                    self.api_key.as_ref().unwrap_or(&"".to_string())
                ),
            }
        }
    }

    /// Check
    pub fn is_feature_enabled(&self, feature: &str) -> bool {
        match feature {
            "caching" => self.enable_caching,
            "search_grounding" => self.enable_search_grounding,
            "debug" => self.debug,
            _ => false,
        }
    }
}

impl Default for GeminiConfig {
    fn default() -> Self {
        Self::new_google_ai("")
    }
}

impl ProviderConfig for GeminiConfig {
    fn validate(&self) -> Result<(), String> {
        if self.use_vertex_ai {
            // Vertex AI validation - use pattern matching to avoid unwrap
            match &self.project_id {
                Some(id) if !id.is_empty() => {}
                _ => return Err("Project ID is required for Vertex AI".to_string()),
            }

            match &self.location {
                Some(loc) if !loc.is_empty() => {}
                _ => return Err("Location is required for Vertex AI".to_string()),
            }
        } else {
            // Google AI Studio validation - use pattern matching
            let api_key = match &self.api_key {
                Some(key) if !key.is_empty() => key,
                _ => return Err("API key is required for Google AI Studio".to_string()),
            };

            if api_key.len() < 20 {
                return Err("API key appears to be too short".to_string());
            }
        }

        // General validation
        if self.request_timeout == 0 {
            return Err("Request timeout must be greater than 0".to_string());
        }

        if self.connect_timeout == 0 {
            return Err("Connect timeout must be greater than 0".to_string());
        }

        if self.connect_timeout > self.request_timeout {
            return Err("Connect timeout cannot be greater than request timeout".to_string());
        }

        if self.max_retries > 10 {
            return Err("Max retries cannot exceed 10".to_string());
        }

        Ok(())
    }

    fn api_key(&self) -> Option<&str> {
        self.api_key.as_deref()
    }

    fn api_base(&self) -> Option<&str> {
        Some(&self.base_url)
    }

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

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

/// Configuration builder
pub struct GeminiConfigBuilder {
    config: GeminiConfig,
}

impl GeminiConfigBuilder {
    /// Create
    pub fn google_ai(api_key: impl Into<String>) -> Self {
        Self {
            config: GeminiConfig::new_google_ai(api_key),
        }
    }

    /// Create
    pub fn vertex_ai(project_id: impl Into<String>, location: impl Into<String>) -> Self {
        Self {
            config: GeminiConfig::new_vertex_ai(project_id, location),
        }
    }

    /// Settings
    pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
        self.config.base_url = base_url.into();
        self
    }

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

    /// Settings
    pub fn with_retries(mut self, max_retries: u32) -> Self {
        self.config.max_retries = max_retries;
        self
    }

    /// Settings
    pub fn with_caching(mut self, enabled: bool) -> Self {
        self.config.enable_caching = enabled;
        self
    }

    /// Settings
    pub fn with_debug(mut self, debug: bool) -> Self {
        self.config.debug = debug;
        self
    }

    /// Configuration
    pub fn build(self) -> Result<GeminiConfig, ProviderError> {
        self.config
            .validate()
            .map_err(|e| ProviderError::configuration("gemini", e))?;
        Ok(self.config)
    }
}

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

    #[test]
    fn test_google_ai_config() {
        let config = GeminiConfig::new_google_ai("test-api-key-1234567890123456");
        assert!(!config.use_vertex_ai);
        assert_eq!(
            config.api_key,
            Some("test-api-key-1234567890123456".to_string())
        );
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_vertex_ai_config() {
        let config = GeminiConfig::new_vertex_ai("test-project", "us-central1");
        assert!(config.use_vertex_ai);
        assert_eq!(config.project_id, Some("test-project".to_string()));
        assert_eq!(config.location, Some("us-central1".to_string()));
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_config_validation() {
        let mut config = GeminiConfig::new_google_ai("");
        assert!(config.validate().is_err());

        config.api_key = Some("valid-api-key-12345678901234567890".to_string());
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_endpoint_generation() {
        let config = GeminiConfig::new_google_ai("test-key-1234567890123456");
        let endpoint = config.get_endpoint("gemini-pro", "generateContent");
        assert!(endpoint.contains("generativelanguage.googleapis.com"));
        assert!(endpoint.contains("gemini-pro:generateContent"));
        assert!(endpoint.contains("key=test-key-1234567890123456"));
    }

    #[test]
    fn test_builder_pattern() {
        let config = GeminiConfigBuilder::google_ai("test-key-1234567890123456")
            .with_timeout(300)
            .with_retries(5)
            .with_debug(true)
            .build()
            .unwrap();

        assert_eq!(config.request_timeout, 300);
        assert_eq!(config.max_retries, 5);
        assert!(config.debug);
    }
}