edgequake-llm 0.5.1

Multi-provider LLM abstraction library with caching, rate limiting, and cost tracking
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
//! HuggingFace Hub Provider - Access to open-source models via HuggingFace.
//!
//! @implements OODA-80: HuggingFace Hub Integration
//!
//! # Overview
//!
//! This provider connects to HuggingFace's Inference API for access to
//! open-source models like Llama, Mistral, Qwen, and Gemma. HuggingFace's API
//! is OpenAI-compatible, so we leverage `OpenAICompatibleProvider` internally.
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────────────┐
//! │                  HuggingFace Provider Architecture                       │
//! ├─────────────────────────────────────────────────────────────────────────┤
//! │                                                                          │
//! │   User Request                                                           │
//! │        │                                                                 │
//! │        ▼                                                                 │
//! │   ┌──────────────────┐  ┌──────────────────────┐  ┌──────────────────┐ │
//! │   │ HuggingFaceProvider│─►│ OpenAICompatibleProvider│─►│ api-inference  │ │
//! │   │ (wrapper)          │  │ (implementation)        │  │ .huggingface   │ │
//! │   └──────────────────┘  └──────────────────────┘  │ .co/v1          │ │
//! │                                                     └──────────────────┘ │
//! │                                                                          │
//! │   HuggingFaceProvider provides:                                          │
//! │   - HF_TOKEN environment detection                                       │
//! │   - Dynamic base URL per model                                           │
//! │   - Default model: meta-llama/Meta-Llama-3.1-70B-Instruct               │
//! │   - Model catalog with context sizes                                    │
//! │                                                                          │
//! └─────────────────────────────────────────────────────────────────────────┘
//! ```
//!
//! # Environment Variables
//!
//! | Variable | Required | Default | Description |
//! |----------|----------|---------|-------------|
//! | `HF_TOKEN` | ✅ Yes | - | HuggingFace access token |
//! | `HUGGINGFACE_TOKEN` | ❌ Alt | - | Alternative token variable |
//! | `HF_MODEL` | ❌ No | `meta-llama/Meta-Llama-3.1-70B-Instruct` | Default model |
//! | `HF_BASE_URL` | ❌ No | Auto | Custom API endpoint |
//!
//! # Available Models
//!
//! | Model | Context | Description |
//! |-------|---------|-------------|
//! | `meta-llama/Meta-Llama-3.1-70B-Instruct` | 128K | Llama 3.1 70B |
//! | `meta-llama/Meta-Llama-3.1-8B-Instruct` | 128K | Llama 3.1 8B |
//! | `mistralai/Mistral-7B-Instruct-v0.3` | 32K | Mistral 7B |
//! | `Qwen/Qwen2.5-72B-Instruct` | 128K | Qwen 2.5 72B |
//! | `microsoft/Phi-3-medium-4k-instruct` | 4K | Phi-3 Medium |
//! | `google/gemma-7b-it` | 8K | Gemma 7B IT |
//!
//! # Example
//!
//! ```bash
//! # Set HuggingFace token (from https://huggingface.co/settings/tokens)
//! export HF_TOKEN=hf_xxxxxxxxxx
//!
//! # Use with EdgeCode (auto-detected)
//! edgecode react "Write hello world in Rust"
//!
//! # Explicit provider selection
//! edgecode react --provider huggingface "Write hello world in Rust"
//!
//! # Use specific model
//! export HF_MODEL=mistralai/Mistral-7B-Instruct-v0.3
//! edgecode react "Explain quantum computing"
//! ```
//!
//! # Free Tier
//!
//! HuggingFace offers a free tier with limited requests. For higher throughput,
//! consider a Pro subscription or Inference Endpoints for dedicated infrastructure.

use async_trait::async_trait;
use futures::stream::BoxStream;
use tracing::debug;

use crate::error::{LlmError, Result};
use crate::model_config::{
    ModelCapabilities, ModelCard, ModelType, ProviderConfig, ProviderType as ConfigProviderType,
};
use crate::providers::openai_compatible::OpenAICompatibleProvider;
use crate::traits::{
    ChatMessage, CompletionOptions, EmbeddingProvider, LLMProvider, LLMResponse, StreamChunk,
};

// ============================================================================
// Constants
// ============================================================================

/// HuggingFace Inference API base URL template
///
/// WHY: HuggingFace uses per-model URLs for the serverless inference API
/// Format: https://api-inference.huggingface.co/models/{model_id}/v1
#[allow(dead_code)]
const HF_BASE_URL_TEMPLATE: &str = "https://api-inference.huggingface.co/models";

/// Alternative: Router-based URL for Inference Providers
/// This provides load balancing and provider selection
const HF_ROUTER_URL: &str = "https://router.huggingface.co/hf-inference/v1";

/// Default model - Llama 3.1 70B is a strong general-purpose model
const HF_DEFAULT_MODEL: &str = "meta-llama/Meta-Llama-3.1-70B-Instruct";

/// Provider display name
const HF_PROVIDER_NAME: &str = "huggingface";

/// HuggingFace model catalog with context lengths.
///
/// WHY: Pre-defined models ensure users get correct context limits without
/// having to check documentation. Updated from HuggingFace Hub.
const HF_MODELS: &[(&str, &str, usize)] = &[
    // Meta Llama models
    (
        "meta-llama/Meta-Llama-3.1-70B-Instruct",
        "Llama 3.1 70B Instruct",
        128000,
    ),
    (
        "meta-llama/Meta-Llama-3.1-8B-Instruct",
        "Llama 3.1 8B Instruct",
        128000,
    ),
    (
        "meta-llama/Meta-Llama-3-8B-Instruct",
        "Llama 3 8B Instruct",
        8192,
    ),
    (
        "meta-llama/Meta-Llama-3-70B-Instruct",
        "Llama 3 70B Instruct",
        8192,
    ),
    // Mistral models
    (
        "mistralai/Mistral-7B-Instruct-v0.3",
        "Mistral 7B Instruct v0.3",
        32000,
    ),
    (
        "mistralai/Mixtral-8x7B-Instruct-v0.1",
        "Mixtral 8x7B Instruct",
        32000,
    ),
    // Qwen models
    ("Qwen/Qwen2.5-72B-Instruct", "Qwen 2.5 72B Instruct", 128000),
    ("Qwen/Qwen2.5-7B-Instruct", "Qwen 2.5 7B Instruct", 128000),
    (
        "Qwen/Qwen2.5-Coder-32B-Instruct",
        "Qwen 2.5 Coder 32B",
        128000,
    ),
    // Microsoft Phi models
    (
        "microsoft/Phi-3-medium-4k-instruct",
        "Phi-3 Medium 4K",
        4096,
    ),
    ("microsoft/Phi-3-mini-4k-instruct", "Phi-3 Mini 4K", 4096),
    // Google Gemma models
    ("google/gemma-7b-it", "Gemma 7B IT", 8192),
    ("google/gemma-2b-it", "Gemma 2B IT", 8192),
    // DeepSeek models
    (
        "deepseek-ai/DeepSeek-Coder-V2-Instruct",
        "DeepSeek Coder V2",
        128000,
    ),
];

// ============================================================================
// HuggingFaceProvider
// ============================================================================

/// HuggingFace Hub provider for open-source model access.
///
/// This is a thin wrapper around `OpenAICompatibleProvider` that provides:
/// - Automatic `HF_TOKEN` detection
/// - Default configuration for HuggingFace's API
/// - Model catalog with correct context sizes
///
/// # Why Wrap OpenAICompatibleProvider?
///
/// HuggingFace's Inference API is OpenAI-compatible, so we get:
/// - Battle-tested HTTP client
/// - Streaming support
/// - Tool/function calling
/// - JSON mode
/// - Error handling
/// - Retry logic
///
/// Without code duplication!
#[derive(Debug)]
pub struct HuggingFaceProvider {
    /// Inner OpenAI-compatible provider
    inner: OpenAICompatibleProvider,
    /// Current model name
    model: String,
}

impl HuggingFaceProvider {
    /// Create provider from environment variables.
    ///
    /// # Environment Variables
    ///
    /// - `HF_TOKEN` or `HUGGINGFACE_TOKEN`: Required API token
    /// - `HF_MODEL`: Model name (default: meta-llama/Meta-Llama-3.1-70B-Instruct)
    /// - `HF_BASE_URL`: Custom base URL (default: auto-generated per model)
    ///
    /// # Errors
    ///
    /// Returns error if neither `HF_TOKEN` nor `HUGGINGFACE_TOKEN` is set.
    pub fn from_env() -> Result<Self> {
        // Check both common token variable names
        let api_key = std::env::var("HF_TOKEN")
            .or_else(|_| std::env::var("HUGGINGFACE_TOKEN"))
            .map_err(|_| {
                LlmError::ConfigError(
                    "HF_TOKEN or HUGGINGFACE_TOKEN environment variable not set. \
                     Get your token from https://huggingface.co/settings/tokens"
                        .to_string(),
                )
            })?;

        if api_key.is_empty() {
            return Err(LlmError::ConfigError(
                "HF_TOKEN is empty. Please set a valid token.".to_string(),
            ));
        }

        let model = std::env::var("HF_MODEL").unwrap_or_else(|_| HF_DEFAULT_MODEL.to_string());
        let base_url = std::env::var("HF_BASE_URL").ok();

        Self::new(api_key, model, base_url)
    }

    /// Create provider with explicit configuration.
    ///
    /// # Arguments
    ///
    /// * `api_key` - HuggingFace access token
    /// * `model` - Model name (e.g., "meta-llama/Meta-Llama-3.1-70B-Instruct")
    /// * `base_url` - Optional custom base URL
    pub fn new(api_key: String, model: String, base_url: Option<String>) -> Result<Self> {
        // Set HF_TOKEN env var for OpenAICompatibleProvider to read
        std::env::set_var("HF_TOKEN", &api_key);

        // Build ProviderConfig
        let config = Self::build_config(&model, base_url.as_deref());

        // Create inner provider
        let inner = OpenAICompatibleProvider::from_config(config)?;

        debug!(
            provider = HF_PROVIDER_NAME,
            model = %model,
            "Created HuggingFace provider"
        );

        Ok(Self { inner, model })
    }

    /// Create with a different model.
    ///
    /// Returns a new provider instance configured for the specified model.
    pub fn with_model(mut self, model: &str) -> Self {
        self.model = model.to_string();
        // Update inner provider with new model
        // Note: Base URL stays the same (router URL handles routing)
        self.inner = self.inner.with_model(model);
        self
    }

    /// Generate the API URL for a specific model.
    ///
    /// WHY: HuggingFace uses per-model URLs for serverless inference.
    /// We use the router URL for simpler implementation and load balancing.
    #[allow(dead_code)]
    fn model_url(_model: &str) -> String {
        // Use router URL which handles model routing automatically
        // This is simpler than constructing per-model URLs
        HF_ROUTER_URL.to_string()
    }

    /// Build ProviderConfig for OpenAICompatibleProvider.
    fn build_config(model: &str, base_url: Option<&str>) -> ProviderConfig {
        // Build model cards from HF_MODELS with proper capabilities
        let models: Vec<ModelCard> = HF_MODELS
            .iter()
            .map(|(name, display, context)| ModelCard {
                name: name.to_string(),
                display_name: display.to_string(),
                model_type: ModelType::Llm,
                capabilities: ModelCapabilities {
                    context_length: *context,
                    supports_function_calling: true, // Most HF models support this
                    supports_json_mode: true,
                    supports_streaming: true,
                    supports_system_message: true,
                    supports_vision: false, // Set true for vision models if needed
                    ..Default::default()
                },
                ..Default::default()
            })
            .collect();

        // Use provided base_url or default to router URL
        let effective_base_url = base_url
            .map(|s| s.to_string())
            .unwrap_or_else(|| HF_ROUTER_URL.to_string());

        ProviderConfig {
            name: HF_PROVIDER_NAME.to_string(),
            display_name: "HuggingFace Hub".to_string(),
            provider_type: ConfigProviderType::OpenAICompatible,
            api_key_env: Some("HF_TOKEN".to_string()),
            base_url: Some(effective_base_url),
            base_url_env: Some("HF_BASE_URL".to_string()),
            default_llm_model: Some(model.to_string()),
            default_embedding_model: None,
            models,
            headers: std::collections::HashMap::new(),
            enabled: true,
            ..Default::default()
        }
    }

    /// Get context length for a model.
    pub fn context_length(model: &str) -> usize {
        HF_MODELS
            .iter()
            .find(|(name, _, _)| *name == model)
            .map(|(_, _, ctx)| *ctx)
            .unwrap_or(8192) // Conservative default
    }

    /// List available models.
    pub fn available_models() -> Vec<(&'static str, &'static str, usize)> {
        HF_MODELS.to_vec()
    }

    /// Check if a token looks like a HuggingFace token.
    ///
    /// HuggingFace tokens start with "hf_" prefix.
    pub fn is_hf_token(token: &str) -> bool {
        token.starts_with("hf_")
    }
}

// ============================================================================
// LLMProvider Implementation (delegates to inner OpenAICompatibleProvider)
// ============================================================================

#[async_trait]
impl LLMProvider for HuggingFaceProvider {
    fn name(&self) -> &str {
        HF_PROVIDER_NAME
    }

    fn model(&self) -> &str {
        &self.model
    }

    fn max_context_length(&self) -> usize {
        Self::context_length(&self.model)
    }

    async fn complete(&self, prompt: &str) -> Result<LLMResponse> {
        self.inner.complete(prompt).await
    }

    async fn complete_with_options(
        &self,
        prompt: &str,
        options: &CompletionOptions,
    ) -> Result<LLMResponse> {
        self.inner.complete_with_options(prompt, options).await
    }

    async fn chat(
        &self,
        messages: &[ChatMessage],
        options: Option<&CompletionOptions>,
    ) -> Result<LLMResponse> {
        self.inner.chat(messages, options).await
    }

    async fn chat_with_tools(
        &self,
        messages: &[ChatMessage],
        tools: &[crate::traits::ToolDefinition],
        tool_choice: Option<crate::traits::ToolChoice>,
        options: Option<&CompletionOptions>,
    ) -> Result<LLMResponse> {
        self.inner
            .chat_with_tools(messages, tools, tool_choice, options)
            .await
    }

    async fn stream(&self, prompt: &str) -> Result<BoxStream<'static, Result<String>>> {
        self.inner.stream(prompt).await
    }

    fn supports_streaming(&self) -> bool {
        true
    }

    fn supports_function_calling(&self) -> bool {
        self.inner.supports_function_calling()
    }

    fn supports_tool_streaming(&self) -> bool {
        self.inner.supports_tool_streaming()
    }

    async fn chat_with_tools_stream(
        &self,
        messages: &[ChatMessage],
        tools: &[crate::traits::ToolDefinition],
        tool_choice: Option<crate::traits::ToolChoice>,
        options: Option<&CompletionOptions>,
    ) -> Result<BoxStream<'static, Result<StreamChunk>>> {
        self.inner
            .chat_with_tools_stream(messages, tools, tool_choice, options)
            .await
    }
}

// ============================================================================
// EmbeddingProvider Implementation
// ============================================================================

#[async_trait]
impl EmbeddingProvider for HuggingFaceProvider {
    fn name(&self) -> &str {
        HF_PROVIDER_NAME
    }

    fn model(&self) -> &str {
        "none"
    }

    fn dimension(&self) -> usize {
        0 // Embedding support would require a separate implementation
    }

    fn max_tokens(&self) -> usize {
        0
    }

    async fn embed(&self, _texts: &[String]) -> Result<Vec<Vec<f32>>> {
        // Embeddings require a different API endpoint
        // Could be added in future with a dedicated embedding model
        Err(LlmError::ConfigError(
            "HuggingFace embeddings require a separate provider configuration. \
             Use the HuggingFace Inference API directly for embeddings."
                .to_string(),
        ))
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_context_length_known_model() {
        assert_eq!(
            HuggingFaceProvider::context_length("meta-llama/Meta-Llama-3.1-70B-Instruct"),
            128000
        );
        assert_eq!(
            HuggingFaceProvider::context_length("mistralai/Mistral-7B-Instruct-v0.3"),
            32000
        );
        assert_eq!(
            HuggingFaceProvider::context_length("microsoft/Phi-3-medium-4k-instruct"),
            4096
        );
    }

    #[test]
    fn test_context_length_unknown_model() {
        // Unknown models default to 8K
        assert_eq!(HuggingFaceProvider::context_length("unknown/model"), 8192);
    }

    #[test]
    fn test_available_models() {
        let models = HuggingFaceProvider::available_models();
        assert!(!models.is_empty());
        assert!(models
            .iter()
            .any(|(name, _, _)| *name == "meta-llama/Meta-Llama-3.1-70B-Instruct"));
        assert!(models
            .iter()
            .any(|(name, _, _)| *name == "Qwen/Qwen2.5-72B-Instruct"));
    }

    #[test]
    fn test_build_config() {
        let config =
            HuggingFaceProvider::build_config("meta-llama/Meta-Llama-3.1-70B-Instruct", None);
        assert_eq!(config.name, "huggingface");
        assert_eq!(
            config.base_url,
            Some("https://router.huggingface.co/hf-inference/v1".to_string())
        );
        assert_eq!(
            config.default_llm_model,
            Some("meta-llama/Meta-Llama-3.1-70B-Instruct".to_string())
        );
    }

    #[test]
    fn test_build_config_custom_url() {
        let config = HuggingFaceProvider::build_config(
            "mistralai/Mistral-7B-Instruct-v0.3",
            Some("https://custom.api"),
        );
        assert_eq!(config.base_url, Some("https://custom.api".to_string()));
    }

    #[test]
    fn test_is_hf_token() {
        assert!(HuggingFaceProvider::is_hf_token("hf_xxxxx"));
        assert!(HuggingFaceProvider::is_hf_token("hf_abc123"));
        assert!(!HuggingFaceProvider::is_hf_token("sk-xxxxx"));
        assert!(!HuggingFaceProvider::is_hf_token("xxxxx"));
    }

    #[test]
    fn test_model_url() {
        let url = HuggingFaceProvider::model_url("meta-llama/Meta-Llama-3.1-70B-Instruct");
        assert_eq!(url, "https://router.huggingface.co/hf-inference/v1");
    }

    #[test]
    fn test_context_length_llama_models() {
        // Llama 3.1 series - 128K
        assert_eq!(
            HuggingFaceProvider::context_length("meta-llama/Meta-Llama-3.1-70B-Instruct"),
            128000
        );
        assert_eq!(
            HuggingFaceProvider::context_length("meta-llama/Meta-Llama-3.1-8B-Instruct"),
            128000
        );
        // Llama 3 series - 8K
        assert_eq!(
            HuggingFaceProvider::context_length("meta-llama/Meta-Llama-3-8B-Instruct"),
            8192
        );
        assert_eq!(
            HuggingFaceProvider::context_length("meta-llama/Meta-Llama-3-70B-Instruct"),
            8192
        );
    }

    #[test]
    fn test_context_length_mistral_models() {
        assert_eq!(
            HuggingFaceProvider::context_length("mistralai/Mistral-7B-Instruct-v0.3"),
            32000
        );
        assert_eq!(
            HuggingFaceProvider::context_length("mistralai/Mixtral-8x7B-Instruct-v0.1"),
            32000
        );
    }

    #[test]
    fn test_context_length_qwen_models() {
        assert_eq!(
            HuggingFaceProvider::context_length("Qwen/Qwen2.5-72B-Instruct"),
            128000
        );
        assert_eq!(
            HuggingFaceProvider::context_length("Qwen/Qwen2.5-7B-Instruct"),
            128000
        );
        assert_eq!(
            HuggingFaceProvider::context_length("Qwen/Qwen2.5-Coder-32B-Instruct"),
            128000
        );
    }

    #[test]
    fn test_context_length_phi_models() {
        assert_eq!(
            HuggingFaceProvider::context_length("microsoft/Phi-3-medium-4k-instruct"),
            4096
        );
        assert_eq!(
            HuggingFaceProvider::context_length("microsoft/Phi-3-mini-4k-instruct"),
            4096
        );
    }

    #[test]
    fn test_context_length_gemma_and_deepseek() {
        // Gemma models - 8K
        assert_eq!(
            HuggingFaceProvider::context_length("google/gemma-7b-it"),
            8192
        );
        assert_eq!(
            HuggingFaceProvider::context_length("google/gemma-2b-it"),
            8192
        );
        // DeepSeek - 128K
        assert_eq!(
            HuggingFaceProvider::context_length("deepseek-ai/DeepSeek-Coder-V2-Instruct"),
            128000
        );
    }

    #[test]
    fn test_available_models_contains_all_families() {
        let models = HuggingFaceProvider::available_models();

        // Meta Llama
        assert!(models
            .iter()
            .any(|(name, _, _)| name.contains("meta-llama")));
        // Mistral
        assert!(models.iter().any(|(name, _, _)| name.contains("mistralai")));
        // Qwen
        assert!(models.iter().any(|(name, _, _)| name.contains("Qwen")));
        // Microsoft Phi
        assert!(models.iter().any(|(name, _, _)| name.contains("microsoft")));
        // Google Gemma
        assert!(models.iter().any(|(name, _, _)| name.contains("google")));
        // DeepSeek
        assert!(models.iter().any(|(name, _, _)| name.contains("deepseek")));
    }

    #[test]
    fn test_available_models_has_positive_context() {
        let models = HuggingFaceProvider::available_models();
        for (name, _desc, context_len) in models {
            assert!(
                context_len > 0,
                "Model {} should have positive context length",
                name
            );
        }
    }

    #[test]
    fn test_constants() {
        assert_eq!(HF_DEFAULT_MODEL, "meta-llama/Meta-Llama-3.1-70B-Instruct");
        assert_eq!(HF_PROVIDER_NAME, "huggingface");
        assert_eq!(
            HF_ROUTER_URL,
            "https://router.huggingface.co/hf-inference/v1"
        );
    }

    #[test]
    fn test_from_env_missing_token() {
        // Clear env vars
        std::env::remove_var("HF_TOKEN");
        std::env::remove_var("HUGGINGFACE_TOKEN");
        std::env::remove_var("HF_MODEL");
        std::env::remove_var("HF_BASE_URL");

        let result = HuggingFaceProvider::from_env();
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("HF_TOKEN") || err.to_string().contains("HUGGINGFACE_TOKEN")
        );
    }

    #[test]
    fn test_build_config_has_models() {
        let config =
            HuggingFaceProvider::build_config("meta-llama/Meta-Llama-3.1-70B-Instruct", None);
        assert!(!config.models.is_empty());
        // Should contain the requested model
        assert!(config
            .models
            .iter()
            .any(|m| m.name == "meta-llama/Meta-Llama-3.1-70B-Instruct"));
    }

    #[test]
    fn test_build_config_api_key_env() {
        let config =
            HuggingFaceProvider::build_config("meta-llama/Meta-Llama-3.1-70B-Instruct", None);
        assert_eq!(config.api_key_env, Some("HF_TOKEN".to_string()));
    }

    #[test]
    fn test_is_hf_token_edge_cases() {
        // Valid prefixes - function just checks starts_with("hf_")
        assert!(HuggingFaceProvider::is_hf_token("hf_a"));
        assert!(HuggingFaceProvider::is_hf_token(
            "hf_verylongtokenstring123"
        ));
        assert!(HuggingFaceProvider::is_hf_token("hf_")); // Technically valid prefix match

        // Invalid - wrong prefix
        assert!(!HuggingFaceProvider::is_hf_token("sk_xxxxx"));
        assert!(!HuggingFaceProvider::is_hf_token("api_key"));
        assert!(!HuggingFaceProvider::is_hf_token("HF_token")); // Case sensitive

        // Invalid - too short or empty
        assert!(!HuggingFaceProvider::is_hf_token(""));
        assert!(!HuggingFaceProvider::is_hf_token("h"));
        assert!(!HuggingFaceProvider::is_hf_token("hf"));
    }

    #[test]
    fn test_model_url_always_returns_router() {
        // All models should use the router URL
        let models = vec![
            "meta-llama/Meta-Llama-3.1-70B-Instruct",
            "mistralai/Mistral-7B-Instruct-v0.3",
            "Qwen/Qwen2.5-72B-Instruct",
            "unknown/model",
        ];

        for model in models {
            assert_eq!(
                HuggingFaceProvider::model_url(model),
                "https://router.huggingface.co/hf-inference/v1"
            );
        }
    }
}