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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
//! Main pricing service implementation

use super::types::{
    CostRange, CostResult, CostType, LiteLLMModelInfo, PricingData, PricingEventType,
    PricingStatistics, PricingUpdateEvent,
};
use crate::utils::error::gateway_error::{GatewayError, Result};
use parking_lot::RwLock;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use tokio::sync::broadcast;
use tracing::{info, warn};

/// Pricing service using LiteLLM data format
#[derive(Debug, Clone)]
pub struct PricingService {
    /// Consolidated pricing data - single lock for model data and timestamp
    pub(super) pricing_data: Arc<RwLock<PricingData>>,
    /// HTTP client for fetching updates
    pub(super) http_client: reqwest::Client,
    /// Pricing data source URL
    pub(super) pricing_url: String,
    /// Cache TTL
    pub(super) cache_ttl: Duration,
    /// Event broadcaster for updates
    pub(super) event_sender: broadcast::Sender<PricingUpdateEvent>,
}

impl PricingService {
    /// Create a new pricing service
    pub fn new(pricing_url: Option<String>) -> Self {
        let (event_sender, _) = broadcast::channel(1000);

        let service = Self {
            pricing_data: Arc::new(RwLock::new(PricingData {
                models: HashMap::new(),
                last_updated: SystemTime::UNIX_EPOCH,
            })),
            http_client: reqwest::Client::new(),
            pricing_url: pricing_url.unwrap_or_else(|| {
                "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json".to_string()
            }),
            cache_ttl: Duration::from_secs(3600), // 1 hour
            event_sender,
        };

        info!("Pricing service initialized with LiteLLM data source");
        service
    }

    /// Get model information
    pub fn get_model_info(&self, model: &str) -> Option<LiteLLMModelInfo> {
        let data = self.pricing_data.read();
        data.models.get(model).cloned()
    }

    /// Calculate completion cost
    pub async fn calculate_completion_cost(
        &self,
        model: &str,
        input_tokens: u32,
        output_tokens: u32,
        prompt: Option<&str>,
        completion: Option<&str>,
        total_time_seconds: Option<f64>,
    ) -> Result<CostResult> {
        // Auto-refresh if needed
        if self.needs_refresh()
            && let Err(e) = self.refresh_pricing_data().await
        {
            warn!("Failed to refresh pricing data: {}", e);
        }

        let model_info = self
            .get_model_info(model)
            .ok_or_else(|| GatewayError::not_found(format!("Model not found: {}", model)))?;

        let provider = model_info.litellm_provider.clone();

        // Provider-specific cost calculation
        match provider.as_str() {
            "openai" | "azure" => {
                self.calculate_token_based_cost(model, &model_info, input_tokens, output_tokens)
            }
            "anthropic" => {
                self.calculate_token_based_cost(model, &model_info, input_tokens, output_tokens)
            }
            "google" | "vertex_ai" => self.calculate_google_cost(
                model,
                &model_info,
                input_tokens,
                output_tokens,
                prompt,
                completion,
            ),
            "replicate" | "together_ai" | "baseten" => self.calculate_time_based_cost(
                model,
                &model_info,
                total_time_seconds.unwrap_or(0.0),
            ),
            "zhipuai" | "glm" => {
                self.calculate_token_based_cost(model, &model_info, input_tokens, output_tokens)
            }
            _ => {
                // Default to token-based calculation
                self.calculate_token_based_cost(model, &model_info, input_tokens, output_tokens)
            }
        }
    }

    /// Calculate token-based cost
    pub(super) fn calculate_token_based_cost(
        &self,
        model: &str,
        model_info: &LiteLLMModelInfo,
        input_tokens: u32,
        output_tokens: u32,
    ) -> Result<CostResult> {
        let input_cost_per_token = model_info.input_cost_per_token.unwrap_or(0.0);
        let output_cost_per_token = model_info.output_cost_per_token.unwrap_or(0.0);

        let input_cost = (input_tokens as f64) * input_cost_per_token;
        let output_cost = (output_tokens as f64) * output_cost_per_token;
        let total_cost = input_cost + output_cost;

        Ok(CostResult {
            input_cost,
            output_cost,
            total_cost,
            input_tokens,
            output_tokens,
            model: model.to_string(),
            provider: model_info.litellm_provider.clone(),
            cost_type: CostType::TokenBased,
        })
    }

    /// Calculate Google/Vertex AI cost (character or token based)
    fn calculate_google_cost(
        &self,
        model: &str,
        model_info: &LiteLLMModelInfo,
        input_tokens: u32,
        output_tokens: u32,
        prompt: Option<&str>,
        completion: Option<&str>,
    ) -> Result<CostResult> {
        // Check if character-based pricing is available
        if model_info.input_cost_per_character.is_some()
            || model_info.output_cost_per_character.is_some()
        {
            let input_cost_per_char = model_info.input_cost_per_character.unwrap_or(0.0);
            let output_cost_per_char = model_info.output_cost_per_character.unwrap_or(0.0);

            let input_chars = prompt.map(|p| p.len()).unwrap_or(0) as f64;
            let output_chars = completion.map(|c| c.len()).unwrap_or(0) as f64;

            let input_cost = input_chars * input_cost_per_char;
            let output_cost = output_chars * output_cost_per_char;

            Ok(CostResult {
                input_cost,
                output_cost,
                total_cost: input_cost + output_cost,
                input_tokens,
                output_tokens,
                model: model.to_string(),
                provider: model_info.litellm_provider.clone(),
                cost_type: CostType::CharacterBased,
            })
        } else {
            // Fall back to token-based
            self.calculate_token_based_cost(model, model_info, input_tokens, output_tokens)
        }
    }

    /// Calculate time-based cost (for deployment providers)
    fn calculate_time_based_cost(
        &self,
        model: &str,
        model_info: &LiteLLMModelInfo,
        total_time_seconds: f64,
    ) -> Result<CostResult> {
        let cost_per_second = model_info.cost_per_second.unwrap_or(0.0);
        let total_cost = total_time_seconds * cost_per_second;

        Ok(CostResult {
            input_cost: 0.0,
            output_cost: 0.0,
            total_cost,
            input_tokens: 0,
            output_tokens: 0,
            model: model.to_string(),
            provider: model_info.litellm_provider.clone(),
            cost_type: CostType::TimeBased,
        })
    }

    /// Get cost per token for a model
    pub fn get_cost_per_token(&self, model: &str) -> Option<(f64, f64)> {
        let model_info = self.get_model_info(model)?;
        Some((
            model_info.input_cost_per_token.unwrap_or(0.0),
            model_info.output_cost_per_token.unwrap_or(0.0),
        ))
    }

    /// Check if model supports a feature
    pub fn supports_feature(&self, model: &str, feature: &str) -> bool {
        let model_info = match self.get_model_info(model) {
            Some(info) => info,
            None => return false,
        };

        match feature {
            "function_calling" => model_info.supports_function_calling.unwrap_or(false),
            "vision" => model_info.supports_vision.unwrap_or(false),
            "streaming" => model_info.supports_streaming.unwrap_or(true), // Default to true
            "parallel_function_calling" => model_info
                .supports_parallel_function_calling
                .unwrap_or(false),
            "system_message" => model_info.supports_system_message.unwrap_or(true),
            _ => false,
        }
    }

    /// Get all available models for a provider
    pub fn get_models_by_provider(&self, provider: &str) -> Vec<String> {
        let data = self.pricing_data.read();
        data.models
            .iter()
            .filter(|(_, info)| info.litellm_provider == provider)
            .map(|(model, _)| model.clone())
            .collect()
    }

    /// Get all available providers
    pub fn get_providers(&self) -> Vec<String> {
        let data = self.pricing_data.read();
        let mut providers: Vec<String> = data
            .models
            .values()
            .map(|info| info.litellm_provider.clone())
            .collect::<std::collections::HashSet<_>>()
            .into_iter()
            .collect();
        providers.sort();
        providers
    }

    /// Add custom model pricing
    pub fn add_custom_model(&self, model: String, model_info: LiteLLMModelInfo) {
        {
            let mut data = self.pricing_data.write();
            data.models.insert(model.clone(), model_info.clone());
        }

        // Send update event
        let _ = self.event_sender.send(PricingUpdateEvent {
            event_type: PricingEventType::ModelAdded,
            model,
            provider: model_info.litellm_provider,
            timestamp: SystemTime::now(),
        });
    }

    /// Get pricing statistics
    pub fn get_statistics(&self) -> PricingStatistics {
        let data = self.pricing_data.read();
        let total_models = data.models.len();

        let mut provider_stats = HashMap::new();
        let mut cost_ranges = HashMap::new();

        for (_, model_info) in data.models.iter() {
            let provider = &model_info.litellm_provider;
            *provider_stats.entry(provider.clone()).or_insert(0) += 1;

            // Track cost ranges
            if let (Some(input_cost), Some(output_cost)) = (
                model_info.input_cost_per_token,
                model_info.output_cost_per_token,
            ) {
                let range = cost_ranges.entry(provider.clone()).or_insert(CostRange {
                    input_min: f64::MAX,
                    input_max: f64::MIN,
                    output_min: f64::MAX,
                    output_max: f64::MIN,
                });

                range.input_min = range.input_min.min(input_cost);
                range.input_max = range.input_max.max(input_cost);
                range.output_min = range.output_min.min(output_cost);
                range.output_max = range.output_max.max(output_cost);
            }
        }

        PricingStatistics {
            total_models,
            provider_stats,
            cost_ranges,
            last_updated: data.last_updated,
        }
    }
}

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

    // ==================== Helper Functions ====================

    fn create_test_model_info(provider: &str) -> LiteLLMModelInfo {
        LiteLLMModelInfo {
            max_tokens: Some(4096),
            max_input_tokens: Some(4096),
            max_output_tokens: Some(4096),
            input_cost_per_token: Some(0.00001),
            output_cost_per_token: Some(0.00003),
            input_cost_per_character: None,
            output_cost_per_character: None,
            cost_per_second: None,
            litellm_provider: provider.to_string(),
            mode: "chat".to_string(),
            supports_function_calling: Some(true),
            supports_vision: Some(false),
            supports_streaming: Some(true),
            supports_parallel_function_calling: Some(true),
            supports_system_message: Some(true),
            extra: HashMap::new(),
        }
    }

    fn create_character_based_model_info() -> LiteLLMModelInfo {
        LiteLLMModelInfo {
            max_tokens: Some(8192),
            max_input_tokens: Some(8192),
            max_output_tokens: Some(8192),
            input_cost_per_token: None,
            output_cost_per_token: None,
            input_cost_per_character: Some(0.000001),
            output_cost_per_character: Some(0.000002),
            cost_per_second: None,
            litellm_provider: "google".to_string(),
            mode: "chat".to_string(),
            supports_function_calling: Some(true),
            supports_vision: Some(true),
            supports_streaming: Some(true),
            supports_parallel_function_calling: Some(false),
            supports_system_message: Some(true),
            extra: HashMap::new(),
        }
    }

    fn create_time_based_model_info() -> LiteLLMModelInfo {
        LiteLLMModelInfo {
            max_tokens: Some(4096),
            max_input_tokens: Some(4096),
            max_output_tokens: Some(4096),
            input_cost_per_token: None,
            output_cost_per_token: None,
            input_cost_per_character: None,
            output_cost_per_character: None,
            cost_per_second: Some(0.001),
            litellm_provider: "replicate".to_string(),
            mode: "chat".to_string(),
            supports_function_calling: Some(false),
            supports_vision: Some(false),
            supports_streaming: Some(true),
            supports_parallel_function_calling: Some(false),
            supports_system_message: Some(true),
            extra: HashMap::new(),
        }
    }

    // ==================== PricingService Creation Tests ====================

    #[test]
    fn test_pricing_service_new_default() {
        let service = PricingService::new(None);
        assert!(
            service
                .pricing_url
                .contains("model_prices_and_context_window.json")
        );
        assert_eq!(service.cache_ttl, Duration::from_secs(3600));
    }

    #[test]
    fn test_pricing_service_new_custom_url() {
        let custom_url = "https://example.com/pricing.json";
        let service = PricingService::new(Some(custom_url.to_string()));
        assert_eq!(service.pricing_url, custom_url);
    }

    #[test]
    fn test_pricing_service_initial_state() {
        let service = PricingService::new(None);
        let data = service.pricing_data.read();
        assert!(data.models.is_empty());
        assert_eq!(data.last_updated, SystemTime::UNIX_EPOCH);
    }

    // ==================== Model Info Tests ====================

    #[test]
    fn test_get_model_info_not_found() {
        let service = PricingService::new(None);
        let result = service.get_model_info("nonexistent-model");
        assert!(result.is_none());
    }

    #[test]
    fn test_get_model_info_after_add() {
        let service = PricingService::new(None);
        let model_info = create_test_model_info("openai");

        service.add_custom_model("gpt-4".to_string(), model_info.clone());

        let result = service.get_model_info("gpt-4");
        assert!(result.is_some());
        let info = result.unwrap();
        assert_eq!(info.litellm_provider, "openai");
    }

    // ==================== Token-Based Cost Calculation Tests ====================

    #[test]
    fn test_calculate_token_based_cost_basic() {
        let service = PricingService::new(None);
        let model_info = create_test_model_info("openai");

        let result = service
            .calculate_token_based_cost("gpt-4", &model_info, 1000, 500)
            .unwrap();

        assert_eq!(result.input_tokens, 1000);
        assert_eq!(result.output_tokens, 500);
        assert_eq!(result.input_cost, 1000.0 * 0.00001);
        assert_eq!(result.output_cost, 500.0 * 0.00003);
        assert_eq!(result.total_cost, result.input_cost + result.output_cost);
        assert_eq!(result.cost_type, CostType::TokenBased);
        assert_eq!(result.provider, "openai");
    }

    #[test]
    fn test_calculate_token_based_cost_zero_tokens() {
        let service = PricingService::new(None);
        let model_info = create_test_model_info("openai");

        let result = service
            .calculate_token_based_cost("gpt-4", &model_info, 0, 0)
            .unwrap();

        assert_eq!(result.input_cost, 0.0);
        assert_eq!(result.output_cost, 0.0);
        assert_eq!(result.total_cost, 0.0);
    }

    #[test]
    fn test_calculate_token_based_cost_no_pricing() {
        let service = PricingService::new(None);
        let model_info = LiteLLMModelInfo {
            max_tokens: Some(4096),
            max_input_tokens: None,
            max_output_tokens: None,
            input_cost_per_token: None,
            output_cost_per_token: None,
            input_cost_per_character: None,
            output_cost_per_character: None,
            cost_per_second: None,
            litellm_provider: "custom".to_string(),
            mode: "chat".to_string(),
            supports_function_calling: None,
            supports_vision: None,
            supports_streaming: None,
            supports_parallel_function_calling: None,
            supports_system_message: None,
            extra: HashMap::new(),
        };

        let result = service
            .calculate_token_based_cost("custom-model", &model_info, 1000, 500)
            .unwrap();

        // Should default to 0 cost when no pricing is set
        assert_eq!(result.total_cost, 0.0);
    }

    #[test]
    fn test_calculate_token_based_cost_large_tokens() {
        let service = PricingService::new(None);
        let model_info = create_test_model_info("openai");

        let result = service
            .calculate_token_based_cost("gpt-4", &model_info, 1_000_000, 100_000)
            .unwrap();

        // Large token counts should work correctly
        assert!(result.total_cost > 0.0);
        assert_eq!(result.input_tokens, 1_000_000);
        assert_eq!(result.output_tokens, 100_000);
    }

    // ==================== Time-Based Cost Calculation Tests ====================

    #[test]
    fn test_calculate_time_based_cost_basic() {
        let service = PricingService::new(None);
        let model_info = create_time_based_model_info();

        let result = service
            .calculate_time_based_cost("replicate/llama", &model_info, 10.0)
            .unwrap();

        assert_eq!(result.total_cost, 10.0 * 0.001);
        assert_eq!(result.cost_type, CostType::TimeBased);
        assert_eq!(result.input_cost, 0.0);
        assert_eq!(result.output_cost, 0.0);
        assert_eq!(result.input_tokens, 0);
        assert_eq!(result.output_tokens, 0);
    }

    #[test]
    fn test_calculate_time_based_cost_zero_time() {
        let service = PricingService::new(None);
        let model_info = create_time_based_model_info();

        let result = service
            .calculate_time_based_cost("replicate/llama", &model_info, 0.0)
            .unwrap();

        assert_eq!(result.total_cost, 0.0);
    }

    #[test]
    fn test_calculate_time_based_cost_fractional_seconds() {
        let service = PricingService::new(None);
        let model_info = create_time_based_model_info();

        let result = service
            .calculate_time_based_cost("replicate/llama", &model_info, 0.5)
            .unwrap();

        assert_eq!(result.total_cost, 0.5 * 0.001);
    }

    // ==================== Feature Support Tests ====================

    #[test]
    fn test_supports_feature_function_calling() {
        let service = PricingService::new(None);
        let model_info = create_test_model_info("openai");
        service.add_custom_model("gpt-4".to_string(), model_info);

        assert!(service.supports_feature("gpt-4", "function_calling"));
    }

    #[test]
    fn test_supports_feature_vision() {
        let service = PricingService::new(None);
        let model_info = create_character_based_model_info();
        service.add_custom_model("gemini-pro-vision".to_string(), model_info);

        assert!(service.supports_feature("gemini-pro-vision", "vision"));
    }

    #[test]
    fn test_supports_feature_streaming() {
        let service = PricingService::new(None);
        let model_info = create_test_model_info("openai");
        service.add_custom_model("gpt-4".to_string(), model_info);

        assert!(service.supports_feature("gpt-4", "streaming"));
    }

    #[test]
    fn test_supports_feature_parallel_function_calling() {
        let service = PricingService::new(None);
        let model_info = create_test_model_info("openai");
        service.add_custom_model("gpt-4".to_string(), model_info);

        assert!(service.supports_feature("gpt-4", "parallel_function_calling"));
    }

    #[test]
    fn test_supports_feature_system_message() {
        let service = PricingService::new(None);
        let model_info = create_test_model_info("openai");
        service.add_custom_model("gpt-4".to_string(), model_info);

        assert!(service.supports_feature("gpt-4", "system_message"));
    }

    #[test]
    fn test_supports_feature_unknown_feature() {
        let service = PricingService::new(None);
        let model_info = create_test_model_info("openai");
        service.add_custom_model("gpt-4".to_string(), model_info);

        assert!(!service.supports_feature("gpt-4", "unknown_feature"));
    }

    #[test]
    fn test_supports_feature_nonexistent_model() {
        let service = PricingService::new(None);
        assert!(!service.supports_feature("nonexistent", "function_calling"));
    }

    #[test]
    fn test_supports_feature_streaming_default_true() {
        let service = PricingService::new(None);
        let model_info = LiteLLMModelInfo {
            max_tokens: Some(4096),
            max_input_tokens: None,
            max_output_tokens: None,
            input_cost_per_token: Some(0.00001),
            output_cost_per_token: Some(0.00003),
            input_cost_per_character: None,
            output_cost_per_character: None,
            cost_per_second: None,
            litellm_provider: "openai".to_string(),
            mode: "chat".to_string(),
            supports_function_calling: None,
            supports_vision: None,
            supports_streaming: None, // Not set
            supports_parallel_function_calling: None,
            supports_system_message: None,
            extra: HashMap::new(),
        };
        service.add_custom_model("test-model".to_string(), model_info);

        // Streaming defaults to true when not specified
        assert!(service.supports_feature("test-model", "streaming"));
    }

    // ==================== Cost Per Token Tests ====================

    #[test]
    fn test_get_cost_per_token_exists() {
        let service = PricingService::new(None);
        let model_info = create_test_model_info("openai");
        service.add_custom_model("gpt-4".to_string(), model_info);

        let result = service.get_cost_per_token("gpt-4");
        assert!(result.is_some());
        let (input, output) = result.unwrap();
        assert_eq!(input, 0.00001);
        assert_eq!(output, 0.00003);
    }

    #[test]
    fn test_get_cost_per_token_not_found() {
        let service = PricingService::new(None);
        let result = service.get_cost_per_token("nonexistent");
        assert!(result.is_none());
    }

    #[test]
    fn test_get_cost_per_token_no_pricing() {
        let service = PricingService::new(None);
        let model_info = LiteLLMModelInfo {
            max_tokens: Some(4096),
            max_input_tokens: None,
            max_output_tokens: None,
            input_cost_per_token: None,
            output_cost_per_token: None,
            input_cost_per_character: None,
            output_cost_per_character: None,
            cost_per_second: None,
            litellm_provider: "custom".to_string(),
            mode: "chat".to_string(),
            supports_function_calling: None,
            supports_vision: None,
            supports_streaming: None,
            supports_parallel_function_calling: None,
            supports_system_message: None,
            extra: HashMap::new(),
        };
        service.add_custom_model("free-model".to_string(), model_info);

        let result = service.get_cost_per_token("free-model");
        assert!(result.is_some());
        let (input, output) = result.unwrap();
        assert_eq!(input, 0.0);
        assert_eq!(output, 0.0);
    }

    // ==================== Provider and Model Listing Tests ====================

    #[test]
    fn test_get_models_by_provider_empty() {
        let service = PricingService::new(None);
        let models = service.get_models_by_provider("openai");
        assert!(models.is_empty());
    }

    #[test]
    fn test_get_models_by_provider_with_models() {
        let service = PricingService::new(None);
        service.add_custom_model("gpt-4".to_string(), create_test_model_info("openai"));
        service.add_custom_model("gpt-3.5".to_string(), create_test_model_info("openai"));
        service.add_custom_model("claude-3".to_string(), create_test_model_info("anthropic"));

        let openai_models = service.get_models_by_provider("openai");
        assert_eq!(openai_models.len(), 2);
        assert!(openai_models.contains(&"gpt-4".to_string()));
        assert!(openai_models.contains(&"gpt-3.5".to_string()));

        let anthropic_models = service.get_models_by_provider("anthropic");
        assert_eq!(anthropic_models.len(), 1);
        assert!(anthropic_models.contains(&"claude-3".to_string()));
    }

    #[test]
    fn test_get_providers_empty() {
        let service = PricingService::new(None);
        let providers = service.get_providers();
        assert!(providers.is_empty());
    }

    #[test]
    fn test_get_providers_with_models() {
        let service = PricingService::new(None);
        service.add_custom_model("gpt-4".to_string(), create_test_model_info("openai"));
        service.add_custom_model("claude-3".to_string(), create_test_model_info("anthropic"));
        service.add_custom_model("gemini-pro".to_string(), create_test_model_info("google"));

        let providers = service.get_providers();
        assert_eq!(providers.len(), 3);
        // Sorted alphabetically
        assert_eq!(providers[0], "anthropic");
        assert_eq!(providers[1], "google");
        assert_eq!(providers[2], "openai");
    }

    #[test]
    fn test_get_providers_deduplication() {
        let service = PricingService::new(None);
        service.add_custom_model("gpt-4".to_string(), create_test_model_info("openai"));
        service.add_custom_model("gpt-3.5".to_string(), create_test_model_info("openai"));
        service.add_custom_model("gpt-4-turbo".to_string(), create_test_model_info("openai"));

        let providers = service.get_providers();
        assert_eq!(providers.len(), 1);
        assert_eq!(providers[0], "openai");
    }

    // ==================== Add Custom Model Tests ====================

    #[test]
    fn test_add_custom_model() {
        let service = PricingService::new(None);
        let model_info = create_test_model_info("custom");

        service.add_custom_model("my-custom-model".to_string(), model_info.clone());

        let result = service.get_model_info("my-custom-model");
        assert!(result.is_some());
        assert_eq!(result.unwrap().litellm_provider, "custom");
    }

    #[test]
    fn test_add_custom_model_overwrites() {
        let service = PricingService::new(None);
        let model_info1 = create_test_model_info("provider1");
        let model_info2 = create_test_model_info("provider2");

        service.add_custom_model("model".to_string(), model_info1);
        service.add_custom_model("model".to_string(), model_info2);

        let result = service.get_model_info("model");
        assert!(result.is_some());
        assert_eq!(result.unwrap().litellm_provider, "provider2");
    }

    // ==================== Statistics Tests ====================

    #[test]
    fn test_get_statistics_empty() {
        let service = PricingService::new(None);
        let stats = service.get_statistics();

        assert_eq!(stats.total_models, 0);
        assert!(stats.provider_stats.is_empty());
        assert!(stats.cost_ranges.is_empty());
    }

    #[test]
    fn test_get_statistics_with_models() {
        let service = PricingService::new(None);
        service.add_custom_model("gpt-4".to_string(), create_test_model_info("openai"));
        service.add_custom_model("gpt-3.5".to_string(), create_test_model_info("openai"));
        service.add_custom_model("claude-3".to_string(), create_test_model_info("anthropic"));

        let stats = service.get_statistics();

        assert_eq!(stats.total_models, 3);
        assert_eq!(*stats.provider_stats.get("openai").unwrap(), 2);
        assert_eq!(*stats.provider_stats.get("anthropic").unwrap(), 1);
    }

    #[test]
    fn test_get_statistics_cost_ranges() {
        let service = PricingService::new(None);

        let mut cheap_model = create_test_model_info("openai");
        cheap_model.input_cost_per_token = Some(0.000001);
        cheap_model.output_cost_per_token = Some(0.000002);

        let mut expensive_model = create_test_model_info("openai");
        expensive_model.input_cost_per_token = Some(0.00006);
        expensive_model.output_cost_per_token = Some(0.00012);

        service.add_custom_model("gpt-3.5".to_string(), cheap_model);
        service.add_custom_model("gpt-4".to_string(), expensive_model);

        let stats = service.get_statistics();

        let range = stats.cost_ranges.get("openai").unwrap();
        assert_eq!(range.input_min, 0.000001);
        assert_eq!(range.input_max, 0.00006);
        assert_eq!(range.output_min, 0.000002);
        assert_eq!(range.output_max, 0.00012);
    }

    // ==================== Google/Character-Based Cost Tests ====================

    #[test]
    fn test_calculate_google_cost_character_based() {
        let service = PricingService::new(None);
        let model_info = create_character_based_model_info();

        let prompt = "Hello, world!"; // 13 chars
        let completion = "Hi there!"; // 9 chars

        let result = service
            .calculate_google_cost(
                "gemini-pro",
                &model_info,
                10,
                5,
                Some(prompt),
                Some(completion),
            )
            .unwrap();

        assert_eq!(result.cost_type, CostType::CharacterBased);
        assert_eq!(result.input_cost, 13.0 * 0.000001);
        assert_eq!(result.output_cost, 9.0 * 0.000002);
    }

    #[test]
    fn test_calculate_google_cost_fallback_to_token() {
        let service = PricingService::new(None);
        let model_info = create_test_model_info("google");

        let result = service
            .calculate_google_cost(
                "gemini-pro",
                &model_info,
                1000,
                500,
                Some("prompt"),
                Some("completion"),
            )
            .unwrap();

        // Should fall back to token-based
        assert_eq!(result.cost_type, CostType::TokenBased);
    }

    #[test]
    fn test_calculate_google_cost_no_text() {
        let service = PricingService::new(None);
        let model_info = create_character_based_model_info();

        let result = service
            .calculate_google_cost("gemini-pro", &model_info, 10, 5, None, None)
            .unwrap();

        // Should still calculate based on 0 characters
        assert_eq!(result.input_cost, 0.0);
        assert_eq!(result.output_cost, 0.0);
    }

    // ==================== Clone Tests ====================

    #[test]
    fn test_pricing_service_clone() {
        let service = PricingService::new(None);
        service.add_custom_model("gpt-4".to_string(), create_test_model_info("openai"));

        let cloned = service.clone();

        // Both should see the same data
        assert!(cloned.get_model_info("gpt-4").is_some());

        // Adding to original should be visible in clone (same Arc)
        service.add_custom_model("gpt-3.5".to_string(), create_test_model_info("openai"));
        assert!(cloned.get_model_info("gpt-3.5").is_some());
    }
}