litellm-rs 0.1.1

A high-performance AI Gateway written in Rust, providing OpenAI-compatible APIs with intelligent routing, load balancing, and enterprise features
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
//! Structured logging utilities
//!
//! This module provides structured logging capabilities with consistent
//! formatting and contextual information for better observability.

use crate::utils::types::{ApiKey, ModelName, RequestId, UserId};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::{Duration, Instant};
use tracing::{debug, error, info, warn};
use uuid::Uuid;

/// Log context for structured logging
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogContext {
    /// Request ID for tracing
    pub request_id: Option<RequestId>,
    /// User ID if available
    pub user_id: Option<UserId>,
    /// Organization ID if available
    pub organization_id: Option<Uuid>,
    /// API key (truncated for security)
    pub api_key: Option<String>,
    /// Model being used
    pub model: Option<ModelName>,
    /// Provider being used
    pub provider: Option<String>,
    /// Additional custom fields
    pub extra: HashMap<String, serde_json::Value>,
}

impl LogContext {
    /// Create a new log context
    pub fn new() -> Self {
        Self {
            request_id: None,
            user_id: None,
            organization_id: None,
            api_key: None,
            model: None,
            provider: None,
            extra: HashMap::new(),
        }
    }

    /// Set request ID
    #[allow(dead_code)] // Reserved for future logging context operations
    pub fn with_request_id(mut self, request_id: RequestId) -> Self {
        self.request_id = Some(request_id);
        self
    }

    /// Set user ID
    #[allow(dead_code)] // Reserved for future logging context operations
    pub fn with_user_id(mut self, user_id: UserId) -> Self {
        self.user_id = Some(user_id);
        self
    }

    /// Set organization ID
    #[allow(dead_code)] // Reserved for future logging context operations
    pub fn with_organization_id(mut self, org_id: Uuid) -> Self {
        self.organization_id = Some(org_id);
        self
    }

    /// Set API key (will be truncated for security)
    #[allow(dead_code)] // Reserved for future logging context operations
    pub fn with_api_key(mut self, api_key: &ApiKey) -> Self {
        self.api_key = Some(api_key.as_display_str());
        self
    }

    /// Set model
    #[allow(dead_code)] // Reserved for future logging context operations
    pub fn with_model(mut self, model: ModelName) -> Self {
        self.model = Some(model);
        self
    }

    /// Set provider
    #[allow(dead_code)] // Reserved for future logging context operations
    pub fn with_provider(mut self, provider: String) -> Self {
        self.provider = Some(provider);
        self
    }

    /// Add custom field
    #[allow(dead_code)] // Reserved for future logging context operations
    pub fn with_field<T: Serialize>(mut self, key: &str, value: T) -> Self {
        if let Ok(json_value) = serde_json::to_value(value) {
            self.extra.insert(key.to_string(), json_value);
        }
        self
    }

    /// Get context fields as a formatted string for logging
    #[allow(dead_code)] // Reserved for future logging context operations
    pub fn context_fields(&self) -> String {
        let mut fields = Vec::new();

        if let Some(request_id) = &self.request_id {
            fields.push(format!("request_id={}", request_id.as_str()));
        }
        if let Some(user_id) = &self.user_id {
            fields.push(format!("user_id={}", user_id));
        }
        if let Some(model) = &self.model {
            fields.push(format!("model={}", model.as_str()));
        }
        if let Some(provider) = &self.provider {
            fields.push(format!("provider={}", provider));
        }

        fields.join(", ")
    }
}

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

/// Performance metrics for logging
#[derive(Debug, Clone, Serialize)]
pub struct PerformanceMetrics {
    /// Duration of the operation
    pub duration_ms: u64,
    /// Memory usage in bytes
    pub memory_bytes: Option<u64>,
    /// Number of database queries
    pub db_queries: Option<u32>,
    /// Cache hit/miss information
    pub cache_hits: Option<u32>,
    /// Cache misses count
    /// Number of cache misses during the operation
    pub cache_misses: Option<u32>,
    /// Token usage
    pub tokens_used: Option<u32>,
    /// Cost in USD
    pub cost_usd: Option<f64>,
}

impl PerformanceMetrics {
    /// Create new performance metrics
    #[allow(dead_code)] // Reserved for future performance monitoring
    pub fn new(duration: Duration) -> Self {
        Self {
            duration_ms: duration.as_millis() as u64,
            memory_bytes: None,
            db_queries: None,
            cache_hits: None,
            cache_misses: None,
            tokens_used: None,
            cost_usd: None,
        }
    }

    /// Set memory usage
    #[allow(dead_code)] // Reserved for future performance monitoring
    pub fn with_memory(mut self, bytes: u64) -> Self {
        self.memory_bytes = Some(bytes);
        self
    }

    /// Set database query count
    #[allow(dead_code)] // Reserved for future performance monitoring
    pub fn with_db_queries(mut self, count: u32) -> Self {
        self.db_queries = Some(count);
        self
    }

    /// Set cache statistics
    #[allow(dead_code)] // Reserved for future performance monitoring
    pub fn with_cache_stats(mut self, hits: u32, misses: u32) -> Self {
        self.cache_hits = Some(hits);
        self.cache_misses = Some(misses);
        self
    }

    /// Set token usage
    #[allow(dead_code)] // Reserved for future performance monitoring
    pub fn with_tokens(mut self, tokens: u32) -> Self {
        self.tokens_used = Some(tokens);
        self
    }

    /// Set cost
    #[allow(dead_code)] // Reserved for future performance monitoring
    pub fn with_cost(mut self, cost: f64) -> Self {
        self.cost_usd = Some(cost);
        self
    }
}

/// Structured logger for consistent logging
pub struct StructuredLogger {
    context: LogContext,
}

impl StructuredLogger {
    /// Create a new structured logger
    #[allow(dead_code)] // Reserved for future structured logging
    pub fn new(context: LogContext) -> Self {
        Self { context }
    }

    /// Log an info message
    #[allow(dead_code)] // Reserved for future structured logging
    pub fn info(&self, message: &str) {
        let context_str = self.context.context_fields();
        info!("{} | {}", message, context_str);
    }

    /// Log a warning message
    #[allow(dead_code)] // Reserved for future structured logging
    pub fn warn(&self, message: &str) {
        let context_str = self.context.context_fields();
        warn!("{} | {}", message, context_str);
    }

    /// Log an error message
    #[allow(dead_code)] // Reserved for future structured logging
    pub fn error(&self, message: &str, error: Option<&dyn std::error::Error>) {
        let context_str = self.context.context_fields();
        if let Some(err) = error {
            error!("{} | {} | error={}", message, context_str, err);
        } else {
            error!("{} | {}", message, context_str);
        }
    }

    /// Log a debug message
    #[allow(dead_code)] // Reserved for future structured logging
    pub fn debug(&self, message: &str) {
        let context_str = self.context.context_fields();
        debug!("{} | {}", message, context_str);
    }

    /// Log performance metrics
    #[allow(dead_code)] // Reserved for future structured logging
    pub fn performance(&self, operation: &str, metrics: PerformanceMetrics) {
        let context_str = self.context.context_fields();
        info!(
            "Performance metrics: operation={}, metrics={:?} | {}",
            operation, metrics, context_str
        );
    }

    /// Log an API request
    #[allow(dead_code)] // Reserved for future structured logging
    pub fn api_request(&self, method: &str, path: &str, status_code: u16, duration: Duration) {
        let context_str = self.context.context_fields();
        info!(
            "API request completed: method={}, path={}, status_code={}, duration_ms={} | {}",
            method,
            path,
            status_code,
            duration.as_millis(),
            context_str
        );
    }

    /// Log a database operation
    #[allow(dead_code)] // Reserved for future structured logging
    pub fn database_operation(
        &self,
        operation: &str,
        table: &str,
        duration: Duration,
        rows_affected: Option<u64>,
    ) {
        let context_str = self.context.context_fields();
        debug!(
            "Database operation completed: operation={}, table={}, duration_ms={}, rows_affected={:?} | {}",
            operation,
            table,
            duration.as_millis(),
            rows_affected,
            context_str
        );
    }

    /// Log a cache operation
    #[allow(dead_code)] // Reserved for future structured logging
    pub fn cache_operation(&self, operation: &str, key: &str, hit: bool, duration: Duration) {
        let context_str = self.context.context_fields();
        debug!(
            "Cache operation completed: operation={}, key={}, hit={}, duration_ms={} | {}",
            operation,
            key,
            hit,
            duration.as_millis(),
            context_str
        );
    }

    /// Log provider interaction
    #[allow(dead_code)] // Reserved for future structured logging
    pub fn provider_interaction(
        &self,
        provider: &str,
        model: &str,
        tokens: Option<u32>,
        cost: Option<f64>,
        duration: Duration,
    ) {
        let context_str = self.context.context_fields();
        info!(
            "Provider interaction completed: provider={}, model={}, tokens={:?}, cost_usd={:?}, duration_ms={} | {}",
            provider,
            model,
            tokens,
            cost,
            duration.as_millis(),
            context_str
        );
    }
}

/// Timer for measuring operation duration
pub struct Timer {
    start: Instant,
    operation: String,
    logger: StructuredLogger,
}

impl Timer {
    /// Start a new timer
    #[allow(dead_code)] // Reserved for future performance timing
    pub fn start(operation: String, logger: StructuredLogger) -> Self {
        Self {
            start: Instant::now(),
            operation,
            logger,
        }
    }

    /// Stop the timer and log the duration
    #[allow(dead_code)] // Reserved for future performance timing
    pub fn stop(self) {
        let duration = self.start.elapsed();
        self.logger
            .performance(&self.operation, PerformanceMetrics::new(duration));
    }

    /// Stop the timer with additional metrics
    #[allow(dead_code)] // Reserved for future performance timing
    pub fn stop_with_metrics(self, metrics: PerformanceMetrics) {
        self.logger.performance(&self.operation, metrics);
    }
}

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

    #[test]
    fn test_log_context() {
        let context = LogContext::new()
            .with_request_id(RequestId::new())
            .with_user_id(UserId::new())
            .with_field("test_field", "test_value");

        assert!(context.request_id.is_some());
        assert!(context.user_id.is_some());
        assert!(context.extra.contains_key("test_field"));
    }

    #[test]
    fn test_performance_metrics() {
        let metrics = PerformanceMetrics::new(Duration::from_millis(100))
            .with_memory(1024)
            .with_db_queries(5)
            .with_cache_stats(10, 2)
            .with_tokens(150)
            .with_cost(0.001);

        assert_eq!(metrics.duration_ms, 100);
        assert_eq!(metrics.memory_bytes, Some(1024));
        assert_eq!(metrics.db_queries, Some(5));
        assert_eq!(metrics.cache_hits, Some(10));
        assert_eq!(metrics.cache_misses, Some(2));
        assert_eq!(metrics.tokens_used, Some(150));
        assert_eq!(metrics.cost_usd, Some(0.001));
    }

    #[test]
    fn test_structured_logger() {
        let context = LogContext::new().with_request_id(RequestId::new());
        let logger = StructuredLogger::new(context);

        // These would normally log to the configured tracing subscriber
        logger.info("Test info message");
        logger.debug("Test debug message");
    }

    #[test]
    fn test_timer() {
        let context = LogContext::new();
        let logger = StructuredLogger::new(context);
        let timer = Timer::start("test_operation".to_string(), logger);

        // Simulate some work
        std::thread::sleep(Duration::from_millis(1));

        timer.stop();
    }
}