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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
//! DataDog APM Integration
//!
//! Provides integration with DataDog for APM, metrics, and logging.

use crate::config::models::defaults::default_true;
use async_trait::async_trait;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::sync::RwLock;
use tracing::{debug, info, warn};

use crate::core::traits::integration::{
    CacheHitEvent, EmbeddingEndEvent, EmbeddingStartEvent, Integration, IntegrationError,
    IntegrationResult, LlmEndEvent, LlmErrorEvent, LlmStartEvent, LlmStreamEvent,
};
use crate::utils::net::http::create_custom_client;

/// DataDog configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DataDogConfig {
    /// DataDog API key
    pub api_key: String,

    /// DataDog site (e.g., datadoghq.com, datadoghq.eu)
    #[serde(default = "default_site")]
    pub site: String,

    /// Service name for APM
    #[serde(default = "default_service")]
    pub service: String,

    /// Environment (e.g., production, staging)
    #[serde(default)]
    pub env: Option<String>,

    /// Version tag
    #[serde(default)]
    pub version: Option<String>,

    /// Enable metrics
    #[serde(default = "default_true")]
    pub enable_metrics: bool,

    /// Enable APM traces
    #[serde(default = "default_true")]
    pub enable_traces: bool,

    /// Enable logs
    #[serde(default = "default_true")]
    pub enable_logs: bool,

    /// Batch size for sending events
    #[serde(default = "default_batch_size")]
    pub batch_size: usize,

    /// Flush interval in milliseconds
    #[serde(default = "default_flush_interval")]
    pub flush_interval_ms: u64,

    /// Additional tags
    #[serde(default)]
    pub tags: HashMap<String, String>,
}

fn default_site() -> String {
    "datadoghq.com".to_string()
}

fn default_service() -> String {
    "litellm-gateway".to_string()
}

fn default_batch_size() -> usize {
    100
}

fn default_flush_interval() -> u64 {
    10000
}

impl Default for DataDogConfig {
    fn default() -> Self {
        Self {
            api_key: String::new(),
            site: default_site(),
            service: default_service(),
            env: None,
            version: None,
            enable_metrics: true,
            enable_traces: true,
            enable_logs: true,
            batch_size: default_batch_size(),
            flush_interval_ms: default_flush_interval(),
            tags: HashMap::new(),
        }
    }
}

impl DataDogConfig {
    /// Create a new DataDog configuration
    pub fn new(api_key: impl Into<String>) -> Self {
        Self {
            api_key: api_key.into(),
            ..Default::default()
        }
    }

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

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

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

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

    /// Add a tag
    pub fn tag(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.tags.insert(key.into(), value.into());
        self
    }

    /// Create from environment variables
    pub fn from_env() -> Option<Self> {
        let api_key = std::env::var("DD_API_KEY")
            .or_else(|_| std::env::var("DATADOG_API_KEY"))
            .ok()?;

        Some(Self {
            api_key,
            site: std::env::var("DD_SITE").unwrap_or_else(|_| default_site()),
            service: std::env::var("DD_SERVICE").unwrap_or_else(|_| default_service()),
            env: std::env::var("DD_ENV").ok(),
            version: std::env::var("DD_VERSION").ok(),
            ..Default::default()
        })
    }

    /// Get the metrics API URL
    pub fn metrics_url(&self) -> String {
        format!("https://api.{}/api/v2/series", self.site)
    }

    /// Get the logs API URL
    pub fn logs_url(&self) -> String {
        format!("https://http-intake.logs.{}/api/v2/logs", self.site)
    }

    /// Get the traces API URL
    pub fn traces_url(&self) -> String {
        format!("https://trace.agent.{}/api/v0.2/traces", self.site)
    }
}

/// DataDog metric point
#[derive(Debug, Clone, Serialize)]
struct MetricPoint {
    timestamp: i64,
    value: f64,
}

/// DataDog metric series
#[derive(Debug, Clone, Serialize)]
struct MetricSeries {
    metric: String,
    #[serde(rename = "type")]
    metric_type: i32,
    points: Vec<MetricPoint>,
    tags: Vec<String>,
    unit: Option<String>,
}

/// DataDog metrics payload
#[derive(Debug, Clone, Serialize)]
struct MetricsPayload {
    series: Vec<MetricSeries>,
}

/// DataDog log entry
#[derive(Debug, Clone, Serialize)]
struct DataDogLogRecord {
    ddsource: String,
    ddtags: String,
    hostname: String,
    message: String,
    service: String,
    status: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    timestamp: Option<i64>,
}

/// Buffered event for batching
#[derive(Debug, Clone)]
enum BufferedEvent {
    Metric(MetricSeries),
    Log(DataDogLogRecord),
}

/// DataDog APM Integration
pub struct DataDogIntegration {
    config: DataDogConfig,
    http_client: Client,
    buffer: Arc<RwLock<Vec<BufferedEvent>>>,
    enabled: bool,
}

impl std::fmt::Debug for DataDogIntegration {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DataDogIntegration")
            .field("service", &self.config.service)
            .field("site", &self.config.site)
            .field("enabled", &self.enabled)
            .finish()
    }
}

impl DataDogIntegration {
    /// Create a new DataDog integration
    pub fn new(config: DataDogConfig) -> IntegrationResult<Self> {
        if config.api_key.is_empty() {
            return Err(IntegrationError::config(
                "DataDog API key is required".to_string(),
            ));
        }

        let http_client = create_custom_client(Duration::from_secs(30)).map_err(|e| {
            IntegrationError::connection(format!("Failed to create HTTP client: {}", e))
        })?;

        info!(
            "DataDog integration initialized for service: {}",
            config.service
        );

        Ok(Self {
            config,
            http_client,
            buffer: Arc::new(RwLock::new(Vec::new())),
            enabled: true,
        })
    }

    /// Create from environment variables
    pub fn from_env() -> IntegrationResult<Self> {
        let config = DataDogConfig::from_env()
            .ok_or_else(|| IntegrationError::config("DD_API_KEY not set".to_string()))?;
        Self::new(config)
    }

    /// Get current timestamp in seconds
    fn current_timestamp() -> i64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs() as i64
    }

    /// Build tags list
    fn build_tags(&self, extra_tags: &[(&str, &str)]) -> Vec<String> {
        let mut tags = Vec::new();

        // Add service tag
        tags.push(format!("service:{}", self.config.service));

        // Add env tag
        if let Some(env) = &self.config.env {
            tags.push(format!("env:{}", env));
        }

        // Add version tag
        if let Some(version) = &self.config.version {
            tags.push(format!("version:{}", version));
        }

        // Add configured tags
        for (key, value) in &self.config.tags {
            tags.push(format!("{}:{}", key, value));
        }

        // Add extra tags
        for (key, value) in extra_tags {
            tags.push(format!("{}:{}", key, value));
        }

        tags
    }

    /// Build tags string for logs
    fn build_tags_string(&self, extra_tags: &[(&str, &str)]) -> String {
        self.build_tags(extra_tags).join(",")
    }

    /// Record a metric
    async fn record_metric(
        &self,
        name: &str,
        value: f64,
        metric_type: i32,
        tags: &[(&str, &str)],
        unit: Option<&str>,
    ) {
        if !self.config.enable_metrics {
            return;
        }

        let metric = MetricSeries {
            metric: format!("litellm.{}", name),
            metric_type,
            points: vec![MetricPoint {
                timestamp: Self::current_timestamp(),
                value,
            }],
            tags: self.build_tags(tags),
            unit: unit.map(String::from),
        };

        let mut buffer = self.buffer.write().await;
        buffer.push(BufferedEvent::Metric(metric));

        if buffer.len() >= self.config.batch_size {
            drop(buffer);
            let _ = self.flush().await;
        }
    }

    /// Record a log entry
    async fn record_log(&self, message: &str, status: &str, tags: &[(&str, &str)]) {
        if !self.config.enable_logs {
            return;
        }

        let hostname = std::env::var("HOSTNAME")
            .or_else(|_| std::env::var("HOST"))
            .unwrap_or_else(|_| "unknown".to_string());

        let log = DataDogLogRecord {
            ddsource: "litellm-gateway".to_string(),
            ddtags: self.build_tags_string(tags),
            hostname,
            message: message.to_string(),
            service: self.config.service.clone(),
            status: status.to_string(),
            timestamp: Some(Self::current_timestamp() * 1000), // milliseconds
        };

        let mut buffer = self.buffer.write().await;
        buffer.push(BufferedEvent::Log(log));

        if buffer.len() >= self.config.batch_size {
            drop(buffer);
            let _ = self.flush().await;
        }
    }

    /// Send metrics to DataDog
    async fn send_metrics(&self, metrics: Vec<MetricSeries>) -> IntegrationResult<()> {
        if metrics.is_empty() {
            return Ok(());
        }

        let payload = MetricsPayload { series: metrics };

        let response = self
            .http_client
            .post(self.config.metrics_url())
            .header("DD-API-KEY", &self.config.api_key)
            .header("Content-Type", "application/json")
            .json(&payload)
            .send()
            .await
            .map_err(|e| IntegrationError::connection(format!("Failed to send metrics: {}", e)))?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            warn!("DataDog metrics API returned {}: {}", status, body);
        }

        Ok(())
    }

    /// Send logs to DataDog
    async fn send_logs(&self, logs: Vec<DataDogLogRecord>) -> IntegrationResult<()> {
        if logs.is_empty() {
            return Ok(());
        }

        let response = self
            .http_client
            .post(self.config.logs_url())
            .header("DD-API-KEY", &self.config.api_key)
            .header("Content-Type", "application/json")
            .json(&logs)
            .send()
            .await
            .map_err(|e| IntegrationError::connection(format!("Failed to send logs: {}", e)))?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            warn!("DataDog logs API returned {}: {}", status, body);
        }

        Ok(())
    }
}

#[async_trait]
impl Integration for DataDogIntegration {
    fn name(&self) -> &'static str {
        "datadog"
    }

    fn is_enabled(&self) -> bool {
        self.enabled
    }

    async fn on_llm_start(&self, event: &LlmStartEvent) -> IntegrationResult<()> {
        debug!("DataDog: LLM request started - {}", event.request_id);

        let tags = [
            ("model", event.model.as_str()),
            ("provider", event.provider.as_deref().unwrap_or("unknown")),
        ];

        // Record request count metric
        self.record_metric("llm.requests", 1.0, 1, &tags, None)
            .await;

        // Log the request start
        self.record_log(
            &format!(
                "LLM request started: request_id={}, model={}",
                event.request_id, event.model
            ),
            "info",
            &tags,
        )
        .await;

        Ok(())
    }

    async fn on_llm_end(&self, event: &LlmEndEvent) -> IntegrationResult<()> {
        debug!("DataDog: LLM request completed - {}", event.request_id);

        let tags = [
            ("model", event.model.as_str()),
            ("provider", event.provider.as_deref().unwrap_or("unknown")),
            ("status", "success"),
        ];

        // Record latency metric
        self.record_metric(
            "llm.latency",
            event.latency_ms as f64,
            3, // Gauge
            &tags,
            Some("millisecond"),
        )
        .await;

        // Record token metrics
        if let Some(input_tokens) = event.input_tokens {
            self.record_metric(
                "llm.tokens.prompt",
                input_tokens as f64,
                1, // Count
                &tags,
                None,
            )
            .await;
        }

        if let Some(output_tokens) = event.output_tokens {
            self.record_metric(
                "llm.tokens.completion",
                output_tokens as f64,
                1,
                &tags,
                None,
            )
            .await;
        }

        if let (Some(input), Some(output)) = (event.input_tokens, event.output_tokens) {
            self.record_metric("llm.tokens.total", (input + output) as f64, 1, &tags, None)
                .await;
        }

        // Record cost metric
        if let Some(cost) = event.cost_usd {
            self.record_metric("llm.cost", cost, 1, &tags, Some("dollar"))
                .await;
        }

        // Log completion
        self.record_log(
            &format!(
                "LLM request completed: request_id={}, model={}, latency={}ms",
                event.request_id, event.model, event.latency_ms
            ),
            "info",
            &tags,
        )
        .await;

        Ok(())
    }

    async fn on_llm_error(&self, event: &LlmErrorEvent) -> IntegrationResult<()> {
        debug!("DataDog: LLM request error - {}", event.request_id);

        let error_type = event.error_type.as_deref().unwrap_or("unknown");
        let tags = [
            ("model", event.model.as_str()),
            ("provider", event.provider.as_deref().unwrap_or("unknown")),
            ("error_type", error_type),
            ("status", "error"),
        ];

        // Record error count
        self.record_metric("llm.errors", 1.0, 1, &tags, None).await;

        // Log the error
        self.record_log(
            &format!(
                "LLM request error: request_id={}, model={}, error={}",
                event.request_id, event.model, event.error_message
            ),
            "error",
            &tags,
        )
        .await;

        Ok(())
    }

    async fn on_llm_stream(&self, _event: &LlmStreamEvent) -> IntegrationResult<()> {
        // Record streaming chunk metric
        let tags: [(&str, &str); 0] = [];

        self.record_metric("llm.stream.chunks", 1.0, 1, &tags, None)
            .await;

        Ok(())
    }

    async fn on_embedding_start(&self, event: &EmbeddingStartEvent) -> IntegrationResult<()> {
        let tags = [
            ("model", event.model.as_str()),
            ("provider", event.provider.as_deref().unwrap_or("unknown")),
        ];

        self.record_metric("embedding.requests", 1.0, 1, &tags, None)
            .await;

        Ok(())
    }

    async fn on_embedding_end(&self, event: &EmbeddingEndEvent) -> IntegrationResult<()> {
        let tags = [
            ("model", event.model.as_str()),
            ("provider", event.provider.as_deref().unwrap_or("unknown")),
        ];

        self.record_metric(
            "embedding.latency",
            event.latency_ms as f64,
            3,
            &tags,
            Some("millisecond"),
        )
        .await;

        if let Some(tokens) = event.total_tokens {
            self.record_metric("embedding.tokens", tokens as f64, 1, &tags, None)
                .await;
        }

        Ok(())
    }

    async fn on_cache_hit(&self, event: &CacheHitEvent) -> IntegrationResult<()> {
        let tags = [("cache_backend", event.cache_backend.as_str())];

        self.record_metric("cache.hits", 1.0, 1, &tags, None).await;

        Ok(())
    }

    async fn flush(&self) -> IntegrationResult<()> {
        let events = {
            let mut buffer = self.buffer.write().await;
            std::mem::take(&mut *buffer)
        };

        if events.is_empty() {
            return Ok(());
        }

        debug!("DataDog: Flushing {} events", events.len());

        let mut metrics = Vec::new();
        let mut logs = Vec::new();

        for event in events {
            match event {
                BufferedEvent::Metric(m) => metrics.push(m),
                BufferedEvent::Log(l) => logs.push(l),
            }
        }

        // Send metrics and logs in parallel
        let (metrics_result, logs_result) =
            tokio::join!(self.send_metrics(metrics), self.send_logs(logs));

        metrics_result?;
        logs_result?;

        Ok(())
    }

    async fn shutdown(&self) -> IntegrationResult<()> {
        info!("DataDog integration shutting down");
        self.flush().await
    }
}

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

    #[test]
    fn test_datadog_config_builder() {
        let config = DataDogConfig::new("test-api-key")
            .site("datadoghq.eu")
            .service("my-service")
            .env("production")
            .version("1.0.0")
            .tag("team", "platform");

        assert_eq!(config.api_key, "test-api-key");
        assert_eq!(config.site, "datadoghq.eu");
        assert_eq!(config.service, "my-service");
        assert_eq!(config.env, Some("production".to_string()));
        assert_eq!(config.version, Some("1.0.0".to_string()));
        assert_eq!(config.tags.get("team"), Some(&"platform".to_string()));
    }

    #[test]
    fn test_datadog_config_urls() {
        let config = DataDogConfig::new("test-key").site("datadoghq.eu");

        assert!(config.metrics_url().contains("datadoghq.eu"));
        assert!(config.logs_url().contains("datadoghq.eu"));
        assert!(config.traces_url().contains("datadoghq.eu"));
    }

    #[test]
    fn test_datadog_config_default() {
        let config = DataDogConfig::default();

        assert_eq!(config.site, "datadoghq.com");
        assert_eq!(config.service, "litellm-gateway");
        assert!(config.enable_metrics);
        assert!(config.enable_traces);
        assert!(config.enable_logs);
    }

    #[test]
    fn test_datadog_integration_requires_api_key() {
        let config = DataDogConfig::default();
        let result = DataDogIntegration::new(config);
        assert!(result.is_err());
    }

    #[test]
    fn test_datadog_integration_creation() {
        let config = DataDogConfig::new("test-api-key");
        let result = DataDogIntegration::new(config);
        assert!(result.is_ok());

        let integration = result.unwrap();
        assert_eq!(integration.name(), "datadog");
        assert!(integration.is_enabled());
    }

    #[test]
    fn test_build_tags() {
        let config = DataDogConfig::new("test-key")
            .service("test-service")
            .env("test")
            .tag("custom", "value");
        let integration = DataDogIntegration::new(config).unwrap();

        let tags = integration.build_tags(&[("extra", "tag")]);

        assert!(tags.contains(&"service:test-service".to_string()));
        assert!(tags.contains(&"env:test".to_string()));
        assert!(tags.contains(&"custom:value".to_string()));
        assert!(tags.contains(&"extra:tag".to_string()));
    }
}