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
//! V0 AI Provider Module
//!
//! V0 is an OpenAI-compatible AI platform for developers
//! <https://v0.dev/>

pub mod chat;

use crate::core::traits::error_mapper::trait_def::ErrorMapper;
use crate::core::{
    providers::base::HttpErrorMapper,
    providers::unified_provider::ProviderError,
    traits::{
        error_mapper::types::GenericErrorMapper,
        provider::{LLMProvider, ProviderConfig},
    },
    types::{
        chat::ChatRequest, context::RequestContext, health::HealthStatus, model::ModelInfo,
        model::ProviderCapability, responses::ChatResponse,
    },
};
use crate::utils::net::http::create_custom_client;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::sync::LazyLock;

/// Provider name constant for error messages
const PROVIDER_NAME: &str = "v0";

/// V0 Provider configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct V0Config {
    /// API base URL for V0
    pub api_base: String,
    /// API key for authentication
    pub api_key: String,
    /// Request timeout in seconds
    pub timeout_seconds: u64,
    /// Maximum retry attempts
    pub max_retries: u32,
}

impl Default for V0Config {
    fn default() -> Self {
        Self {
            api_base: "https://api.v0.dev/v1".to_string(),
            api_key: String::new(),
            timeout_seconds: 60,
            max_retries: 3,
        }
    }
}

impl V0Config {
    /// Configuration
    pub fn validate(&self) -> Result<(), String> {
        if self.api_key.is_empty() {
            return Err("V0 API key is required".to_string());
        }
        if self.api_base.is_empty() {
            return Err("V0 API base URL is required".to_string());
        }
        Ok(())
    }
}

/// implementation ProviderConfig trait
impl ProviderConfig for V0Config {
    /// Configuration
    fn validate(&self) -> Result<(), String> {
        self.validate()
    }

    /// Get
    fn api_key(&self) -> Option<&str> {
        if self.api_key.is_empty() {
            None
        } else {
            Some(&self.api_key)
        }
    }

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

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

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

/// V0 supported models
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum V0Model {
    /// V0 Default Model
    V0Default,
    /// Custom model
    Custom(String),
}

impl V0Model {
    /// Get model identifier for API calls
    pub fn model_id(&self) -> String {
        match self {
            Self::V0Default => "v0-default".to_string(),
            Self::Custom(id) => id.clone(),
        }
    }

    /// Check if model supports function calling
    pub fn supports_function_calling(&self) -> bool {
        matches!(self, Self::V0Default | Self::Custom(_))
    }

    /// Check if model supports streaming
    pub fn supports_streaming(&self) -> bool {
        true
    }

    /// Get maximum context window size
    pub fn max_context_tokens(&self) -> usize {
        match self {
            Self::V0Default => 32768,
            Self::Custom(_) => 32768, // Default assumption
        }
    }
}

/// Parse model string to V0Model enum
pub fn parse_v0_model(model: &str) -> V0Model {
    match model {
        "v0" | "v0-default" => V0Model::V0Default,
        _ => V0Model::Custom(model.to_string()),
    }
}

/// V0 Provider implementation
#[derive(Debug, Clone)]
pub struct V0Provider {
    config: V0Config,
    client: reqwest::Client,
}

impl V0Provider {
    /// Create a new V0 provider
    ///
    /// # Errors
    /// Returns error if HTTP client cannot be created
    pub fn new(
        config: V0Config,
    ) -> Result<Self, crate::core::providers::unified_provider::ProviderError> {
        let client = create_custom_client(std::time::Duration::from_secs(config.timeout_seconds))
            .map_err(|e| {
            crate::core::providers::unified_provider::ProviderError::Configuration {
                provider: "v0",
                message: format!("Failed to create HTTP client: {}", e),
            }
        })?;

        Ok(Self { config, client })
    }

    /// Create a new V0 provider with default client on error
    pub fn new_or_default(config: V0Config) -> Self {
        Self::new(config.clone()).unwrap_or_else(|e| {
            tracing::error!("Failed to create V0 provider: {}, using default client", e);
            Self {
                config,
                client: reqwest::Client::new(),
            }
        })
    }

    /// Get API endpoint URL
    fn get_endpoint(&self, path: &str) -> String {
        format!(
            "{}/{}",
            self.config.api_base.trim_end_matches('/'),
            path.trim_start_matches('/')
        )
    }

    /// Create request headers
    fn create_headers(&self) -> reqwest::header::HeaderMap {
        let mut headers = reqwest::header::HeaderMap::new();
        if let Ok(auth_value) = format!("Bearer {}", self.config.api_key).parse() {
            headers.insert(reqwest::header::AUTHORIZATION, auth_value);
        }
        if let Ok(content_type) = "application/json".parse() {
            headers.insert(reqwest::header::CONTENT_TYPE, content_type);
        }
        headers
    }

    /// Internal health check method
    async fn check_health(&self) -> Result<(), ProviderError> {
        let url = self.get_endpoint("models");
        let response = self
            .client
            .get(&url)
            .headers(self.create_headers())
            .send()
            .await
            .map_err(|e| ProviderError::network(PROVIDER_NAME, e.to_string()))?;

        if response.status().is_success() {
            Ok(())
        } else {
            Err(HttpErrorMapper::map_status_code(
                PROVIDER_NAME,
                response.status().as_u16(),
                &format!("Health check failed with status: {}", response.status()),
            ))
        }
    }
}

/// Implementation of unified LLMProvider trait
///
/// V0 is an OpenAI-compatible AI platform
impl LLMProvider for V0Provider {
    /// Get
    fn name(&self) -> &'static str {
        "v0"
    }

    /// Get
    fn capabilities(&self) -> &'static [ProviderCapability] {
        &[
            ProviderCapability::ChatCompletion,
            ProviderCapability::ChatCompletionStream,
            ProviderCapability::ToolCalling,
            ProviderCapability::FunctionCalling,
        ]
    }

    /// Model
    fn models(&self) -> &[ModelInfo] {
        // Use LazyLock for lazy initialization of static data
        static MODELS: LazyLock<Vec<ModelInfo>> = LazyLock::new(|| {
            vec![ModelInfo {
                id: "v0-default".to_string(),
                name: "V0 Default Model".to_string(),
                provider: "v0".to_string(),
                max_context_length: 32768,
                max_output_length: Some(8192),
                supports_streaming: true,
                supports_tools: true,
                supports_multimodal: false,
                input_cost_per_1k_tokens: Some(0.1),
                output_cost_per_1k_tokens: Some(0.2),
                currency: "USD".to_string(),
                capabilities: vec![
                    ProviderCapability::ChatCompletion,
                    ProviderCapability::ChatCompletionStream,
                    ProviderCapability::ToolCalling,
                ],
                created_at: None,
                updated_at: None,
                metadata: HashMap::new(),
            }]
        });
        &MODELS
    }

    // ==================== Python LiteLLM compatible interface ====================

    /// Get
    fn get_supported_openai_params(&self, _model: &str) -> &'static [&'static str] {
        &[
            "messages",
            "model",
            "temperature",
            "max_tokens",
            "top_p",
            "stream",
            "tools",
            "tool_choice",
            "user",
            "seed",
        ]
    }

    /// Map OpenAI parameters to V0 parameters
    async fn map_openai_params(
        &self,
        mut params: HashMap<String, Value>,
        _model: &str,
    ) -> Result<HashMap<String, Value>, ProviderError> {
        // V0 uses OpenAI-compatible parameters, so most parameters are passed through directly

        // Can add specific parameter mapping logic here
        // For example: rename certain parameters or convert formats

        // Ensure stream parameter is boolean value, not Option<bool>
        if let Some(stream_val) = params.get("stream")
            && let Some(stream_bool) = stream_val.as_bool()
        {
            params.insert("stream".to_string(), Value::Bool(stream_bool));
        }

        Ok(params)
    }

    /// Request
    async fn transform_request(
        &self,
        request: ChatRequest,
        _context: RequestContext,
    ) -> Result<Value, ProviderError> {
        // Request
        if request.messages.is_empty() {
            return Err(ProviderError::invalid_request(
                PROVIDER_NAME,
                "Messages cannot be empty",
            ));
        }

        if request.model.is_empty() {
            return Err(ProviderError::invalid_request(
                PROVIDER_NAME,
                "Model cannot be empty",
            ));
        }

        // Convert to V0 API format (OpenAI compatible)
        let v0_request = serde_json::json!({
            "model": request.model,
            "messages": request.messages,
            "temperature": request.temperature,
            "max_tokens": request.max_tokens,
            "top_p": request.top_p,
            "stream": request.stream,
            "tools": request.tools,
            "tool_choice": request.tool_choice,
        });

        Ok(v0_request)
    }

    /// Response
    async fn transform_response(
        &self,
        raw_response: &[u8],
        model: &str,
        request_id: &str,
    ) -> Result<ChatResponse, ProviderError> {
        // Response
        let response_json: Value = serde_json::from_slice(raw_response)
            .map_err(|e| ProviderError::serialization(PROVIDER_NAME, e.to_string()))?;

        // Convert to standard ChatResponse format
        // Response
        // Create

        let choices = response_json
            .get("choices")
            .and_then(|c| c.as_array())
            .ok_or_else(|| {
                ProviderError::response_parsing(PROVIDER_NAME, "Invalid response format")
            })?;

        let usage = response_json
            .get("usage")
            .map(|u| serde_json::from_value(u.clone()))
            .transpose()
            .map_err(|e| ProviderError::serialization(PROVIDER_NAME, e.to_string()))?;

        let chat_response = ChatResponse {
            id: request_id.to_string(),
            object: "chat.completion".to_string(),
            created: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs() as i64,
            model: model.to_string(),
            choices: serde_json::from_value(serde_json::Value::Array(choices.clone()))
                .map_err(|e| ProviderError::serialization(PROVIDER_NAME, e.to_string()))?,
            usage,
            system_fingerprint: None,
        };

        Ok(chat_response)
    }

    /// Error
    fn get_error_mapper(&self) -> Box<dyn ErrorMapper<ProviderError>> {
        Box::new(GenericErrorMapper)
    }

    // ==================== Core functionality: chat completion ====================

    /// Request
    async fn chat_completion(
        &self,
        request: ChatRequest,
        context: RequestContext,
    ) -> Result<ChatResponse, ProviderError> {
        // Use new transformation flow
        let _transformed_request = self
            .transform_request(request.clone(), context.clone())
            .await?;

        // Should call actual API here, using original handler for demonstration
        chat::V0ChatHandler::handle_chat_completion(self, request).await
    }

    /// Check
    async fn health_check(&self) -> HealthStatus {
        match self.check_health().await {
            Ok(_) => HealthStatus::Healthy,
            Err(_) => HealthStatus::Unhealthy,
        }
    }

    /// Request
    async fn calculate_cost(
        &self,
        _model: &str,
        input_tokens: u32,
        output_tokens: u32,
    ) -> Result<f64, ProviderError> {
        // V0 pricing: input $0.1/1K tokens, output $0.2/1K tokens
        let input_cost = (input_tokens as f64 / 1000.0) * 0.1;
        let output_cost = (output_tokens as f64 / 1000.0) * 0.2;
        Ok(input_cost + output_cost)
    }
}

// Provider trait implementation removed - V0Provider is now included through the Provider enum variants

// ==================== Unit Tests ====================

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

    // ==================== V0Config Tests ====================

    #[test]
    fn test_v0_config_default() {
        let config = V0Config::default();
        assert_eq!(config.api_base, "https://api.v0.dev/v1");
        assert!(config.api_key.is_empty());
        assert_eq!(config.timeout_seconds, 60);
        assert_eq!(config.max_retries, 3);
    }

    #[test]
    fn test_v0_config_clone() {
        let config = V0Config {
            api_base: "https://custom.api.v0.dev".to_string(),
            api_key: "test-key".to_string(),
            timeout_seconds: 120,
            max_retries: 5,
        };
        let cloned = config.clone();
        assert_eq!(config.api_base, cloned.api_base);
        assert_eq!(config.api_key, cloned.api_key);
        assert_eq!(config.timeout_seconds, cloned.timeout_seconds);
    }

    #[test]
    fn test_v0_config_validate_success() {
        let config = V0Config {
            api_base: "https://api.v0.dev/v1".to_string(),
            api_key: "valid-api-key".to_string(),
            timeout_seconds: 60,
            max_retries: 3,
        };
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_v0_config_validate_empty_api_key() {
        let config = V0Config {
            api_base: "https://api.v0.dev/v1".to_string(),
            api_key: String::new(),
            timeout_seconds: 60,
            max_retries: 3,
        };
        let result = config.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("API key"));
    }

    #[test]
    fn test_v0_config_validate_empty_api_base() {
        let config = V0Config {
            api_base: String::new(),
            api_key: "valid-key".to_string(),
            timeout_seconds: 60,
            max_retries: 3,
        };
        let result = config.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("API base"));
    }

    #[test]
    fn test_v0_config_serialization() {
        let config = V0Config {
            api_base: "https://api.v0.dev/v1".to_string(),
            api_key: "test-key".to_string(),
            timeout_seconds: 60,
            max_retries: 3,
        };
        let json = serde_json::to_string(&config).unwrap();
        assert!(json.contains("\"api_base\""));
        assert!(json.contains("\"api_key\""));
        assert!(json.contains("\"timeout_seconds\":60"));
    }

    #[test]
    fn test_v0_config_deserialization() {
        let json = r#"{
            "api_base": "https://api.v0.dev/v1",
            "api_key": "test-key",
            "timeout_seconds": 90,
            "max_retries": 5
        }"#;
        let config: V0Config = serde_json::from_str(json).unwrap();
        assert_eq!(config.api_base, "https://api.v0.dev/v1");
        assert_eq!(config.api_key, "test-key");
        assert_eq!(config.timeout_seconds, 90);
        assert_eq!(config.max_retries, 5);
    }

    // ==================== ProviderConfig Trait Tests ====================

    #[test]
    fn test_provider_config_api_key() {
        let config = V0Config {
            api_key: "my-key".to_string(),
            ..Default::default()
        };
        assert_eq!(config.api_key(), Some("my-key"));
    }

    #[test]
    fn test_provider_config_api_key_empty() {
        let config = V0Config::default();
        assert_eq!(config.api_key(), None);
    }

    #[test]
    fn test_provider_config_api_base() {
        let config = V0Config {
            api_base: "https://custom.api.com".to_string(),
            ..Default::default()
        };
        assert_eq!(config.api_base(), Some("https://custom.api.com"));
    }

    #[test]
    fn test_provider_config_timeout() {
        let config = V0Config {
            timeout_seconds: 120,
            ..Default::default()
        };
        assert_eq!(config.timeout(), std::time::Duration::from_secs(120));
    }

    #[test]
    fn test_provider_config_max_retries() {
        let config = V0Config {
            max_retries: 5,
            ..Default::default()
        };
        assert_eq!(config.max_retries(), 5);
    }

    // ==================== V0Model Tests ====================

    #[test]
    fn test_v0_model_default_id() {
        let model = V0Model::V0Default;
        assert_eq!(model.model_id(), "v0-default");
    }

    #[test]
    fn test_v0_model_custom_id() {
        let model = V0Model::Custom("my-custom-model".to_string());
        assert_eq!(model.model_id(), "my-custom-model");
    }

    #[test]
    fn test_v0_model_supports_function_calling() {
        assert!(V0Model::V0Default.supports_function_calling());
        assert!(V0Model::Custom("test".to_string()).supports_function_calling());
    }

    #[test]
    fn test_v0_model_supports_streaming() {
        assert!(V0Model::V0Default.supports_streaming());
        assert!(V0Model::Custom("test".to_string()).supports_streaming());
    }

    #[test]
    fn test_v0_model_max_context_tokens() {
        assert_eq!(V0Model::V0Default.max_context_tokens(), 32768);
        assert_eq!(
            V0Model::Custom("test".to_string()).max_context_tokens(),
            32768
        );
    }

    #[test]
    fn test_v0_model_clone() {
        let model = V0Model::V0Default;
        let cloned = model.clone();
        assert!(matches!(cloned, V0Model::V0Default));

        let custom = V0Model::Custom("test".to_string());
        let custom_cloned = custom.clone();
        assert!(matches!(custom_cloned, V0Model::Custom(s) if s == "test"));
    }

    #[test]
    fn test_v0_model_serialization() {
        let model = V0Model::V0Default;
        let json = serde_json::to_string(&model).unwrap();
        assert_eq!(json, "\"V0Default\"");

        let custom = V0Model::Custom("my-model".to_string());
        let json = serde_json::to_string(&custom).unwrap();
        assert!(json.contains("Custom"));
        assert!(json.contains("my-model"));
    }

    // ==================== parse_v0_model Tests ====================

    #[test]
    fn test_parse_v0_model_default() {
        let model = parse_v0_model("v0");
        assert!(matches!(model, V0Model::V0Default));

        let model = parse_v0_model("v0-default");
        assert!(matches!(model, V0Model::V0Default));
    }

    #[test]
    fn test_parse_v0_model_custom() {
        let model = parse_v0_model("custom-model-123");
        assert!(matches!(model, V0Model::Custom(s) if s == "custom-model-123"));
    }

    // ==================== V0Provider Tests ====================

    #[test]
    fn test_v0_provider_new() {
        let config = V0Config {
            api_key: "test-key".to_string(),
            ..Default::default()
        };
        let provider = V0Provider::new(config);
        assert!(provider.is_ok());
    }

    #[test]
    fn test_v0_provider_new_or_default() {
        let config = V0Config {
            api_key: "test-key".to_string(),
            ..Default::default()
        };
        let provider = V0Provider::new_or_default(config);
        assert_eq!(provider.config.api_key, "test-key");
    }

    #[test]
    fn test_v0_provider_clone() {
        let config = V0Config {
            api_key: "test-key".to_string(),
            ..Default::default()
        };
        let provider = V0Provider::new_or_default(config);
        let cloned = provider.clone();
        assert_eq!(provider.config.api_key, cloned.config.api_key);
    }

    #[test]
    fn test_v0_provider_get_endpoint() {
        let config = V0Config {
            api_base: "https://api.v0.dev/v1".to_string(),
            api_key: "test-key".to_string(),
            ..Default::default()
        };
        let provider = V0Provider::new_or_default(config);

        assert_eq!(
            provider.get_endpoint("chat/completions"),
            "https://api.v0.dev/v1/chat/completions"
        );
        assert_eq!(
            provider.get_endpoint("/models"),
            "https://api.v0.dev/v1/models"
        );
    }

    #[test]
    fn test_v0_provider_get_endpoint_trailing_slash() {
        let config = V0Config {
            api_base: "https://api.v0.dev/v1/".to_string(),
            api_key: "test-key".to_string(),
            ..Default::default()
        };
        let provider = V0Provider::new_or_default(config);

        assert_eq!(
            provider.get_endpoint("chat/completions"),
            "https://api.v0.dev/v1/chat/completions"
        );
    }

    #[test]
    fn test_v0_provider_create_headers() {
        let config = V0Config {
            api_key: "test-key-123".to_string(),
            ..Default::default()
        };
        let provider = V0Provider::new_or_default(config);
        let headers = provider.create_headers();

        assert!(headers.contains_key(reqwest::header::AUTHORIZATION));
        assert!(headers.contains_key(reqwest::header::CONTENT_TYPE));
    }

    // ==================== LLMProvider Trait Tests ====================

    #[test]
    fn test_v0_provider_name() {
        let config = V0Config {
            api_key: "test-key".to_string(),
            ..Default::default()
        };
        let provider = V0Provider::new_or_default(config);
        assert_eq!(provider.name(), "v0");
    }

    #[test]
    fn test_v0_provider_capabilities() {
        let config = V0Config {
            api_key: "test-key".to_string(),
            ..Default::default()
        };
        let provider = V0Provider::new_or_default(config);
        let capabilities = provider.capabilities();

        assert!(capabilities.contains(&ProviderCapability::ChatCompletion));
        assert!(capabilities.contains(&ProviderCapability::ChatCompletionStream));
        assert!(capabilities.contains(&ProviderCapability::ToolCalling));
        assert!(capabilities.contains(&ProviderCapability::FunctionCalling));
    }

    #[test]
    fn test_v0_provider_models() {
        let config = V0Config {
            api_key: "test-key".to_string(),
            ..Default::default()
        };
        let provider = V0Provider::new_or_default(config);
        let models = provider.models();

        assert!(!models.is_empty());
        assert!(models.iter().any(|m| m.id == "v0-default"));
    }

    #[test]
    fn test_v0_provider_supported_params() {
        let config = V0Config {
            api_key: "test-key".to_string(),
            ..Default::default()
        };
        let provider = V0Provider::new_or_default(config);
        let params = provider.get_supported_openai_params("v0-default");

        assert!(params.contains(&"messages"));
        assert!(params.contains(&"model"));
        assert!(params.contains(&"temperature"));
        assert!(params.contains(&"stream"));
        assert!(params.contains(&"tools"));
    }

    #[test]
    fn test_v0_provider_get_error_mapper() {
        let config = V0Config {
            api_key: "test-key".to_string(),
            ..Default::default()
        };
        let provider = V0Provider::new_or_default(config);
        let _mapper = provider.get_error_mapper();
        // Just verify it compiles and returns
    }

    #[tokio::test]
    async fn test_v0_provider_calculate_cost() {
        let config = V0Config {
            api_key: "test-key".to_string(),
            ..Default::default()
        };
        let provider = V0Provider::new_or_default(config);

        // 1000 input tokens at $0.1/1K = $0.1
        // 1000 output tokens at $0.2/1K = $0.2
        // Total = $0.3
        let cost = provider
            .calculate_cost("v0-default", 1000, 1000)
            .await
            .unwrap();
        assert!((cost - 0.3).abs() < 0.001);
    }

    #[tokio::test]
    async fn test_v0_provider_calculate_cost_zero_tokens() {
        let config = V0Config {
            api_key: "test-key".to_string(),
            ..Default::default()
        };
        let provider = V0Provider::new_or_default(config);

        let cost = provider.calculate_cost("v0-default", 0, 0).await.unwrap();
        assert_eq!(cost, 0.0);
    }

    #[tokio::test]
    async fn test_v0_provider_map_openai_params() {
        let config = V0Config {
            api_key: "test-key".to_string(),
            ..Default::default()
        };
        let provider = V0Provider::new_or_default(config);

        let mut params = HashMap::new();
        params.insert("temperature".to_string(), serde_json::json!(0.7));
        params.insert("stream".to_string(), serde_json::json!(true));

        let mapped = provider
            .map_openai_params(params, "v0-default")
            .await
            .unwrap();

        assert_eq!(mapped.get("temperature"), Some(&serde_json::json!(0.7)));
        assert_eq!(mapped.get("stream"), Some(&serde_json::json!(true)));
    }
}