clawft-llm 0.5.3

LLM provider abstraction for clawft (OpenAI-compatible + native providers)
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
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
//! Local/Hermes-compatible LLM provider.
//!
//! [`LocalProvider`] connects to any OpenAI-compatible local inference server
//! (Ollama, vLLM, llama.cpp, LM Studio, Hermes). It wraps
//! [`OpenAiCompatProvider`] with key-optional behavior and sensible defaults
//! for air-gapped / local deployments.
//!
//! # Supported backends
//!
//! | Backend   | Default base URL                    | API key required |
//! |-----------|-------------------------------------|------------------|
//! | Ollama    | `http://localhost:11434/v1`          | No               |
//! | vLLM      | `http://localhost:8000/v1`           | No               |
//! | llama.cpp | `http://localhost:8080/v1`           | No               |
//! | LM Studio | `http://localhost:1234/v1`           | No               |
//! | Hermes    | `http://localhost:11434/v1` (Ollama) | No               |
//!
//! All backends expose the standard `/v1/chat/completions` endpoint.

use async_trait::async_trait;
use tokio::sync::mpsc;
use tracing::debug;

use std::collections::HashMap;
use std::time::Duration;

use crate::config::LlmProviderConfig;
use crate::error::{ProviderError, Result};
use crate::provider::Provider;
use crate::sse::parse_sse_line;
use crate::types::{ChatRequest, ChatResponse, StreamChunk};

/// Default base URL for Ollama's OpenAI-compatible endpoint.
pub const OLLAMA_DEFAULT_BASE_URL: &str = "http://localhost:11434/v1";

/// Default base URL for vLLM.
pub const VLLM_DEFAULT_BASE_URL: &str = "http://localhost:8000/v1";

/// Default base URL for llama.cpp server.
pub const LLAMACPP_DEFAULT_BASE_URL: &str = "http://localhost:8080/v1";

/// Default base URL for LM Studio.
pub const LMSTUDIO_DEFAULT_BASE_URL: &str = "http://localhost:1234/v1";

/// Default model for local providers.
pub const DEFAULT_LOCAL_MODEL: &str = "llama3.2";

/// Default timeout for local providers (5 minutes -- local inference can be slow).
const DEFAULT_LOCAL_TIMEOUT_SECS: u64 = 300;

/// A local LLM provider that connects to OpenAI-compatible local inference servers.
///
/// Unlike cloud providers, local providers:
/// - Do not require an API key (but accept one if the server is configured with auth)
/// - Use longer default timeouts (local inference can be slow on CPU)
/// - Default to `http://localhost:11434/v1` (Ollama)
///
/// # Construction
///
/// ```rust,ignore
/// use clawft_llm::LocalProvider;
///
/// // Minimal -- connects to Ollama on default port
/// let provider = LocalProvider::ollama();
///
/// // Custom endpoint
/// let provider = LocalProvider::new(
///     "http://192.168.1.100:8000/v1".to_string(),
///     "my-local-model".to_string(),
///     None, // no API key
/// );
/// ```
pub struct LocalProvider {
    config: LlmProviderConfig,
    http: reqwest::Client,
    api_key: Option<String>,
}

impl LocalProvider {
    /// Create a local provider with explicit parameters.
    ///
    /// - `base_url`: The OpenAI-compatible API base URL.
    /// - `model`: Default model name to use.
    /// - `api_key`: Optional API key (most local servers don't require one).
    pub fn new(base_url: String, model: String, api_key: Option<String>) -> Self {
        Self::from_config(
            LlmProviderConfig {
                name: "local".into(),
                base_url,
                api_key_env: "LOCAL_LLM_API_KEY".into(),
                model_prefix: Some("local/".into()),
                default_model: Some(model),
                headers: HashMap::new(),
                timeout_secs: Some(DEFAULT_LOCAL_TIMEOUT_SECS),
            },
            api_key,
        )
    }

    /// Create a local provider from a full [`LlmProviderConfig`].
    ///
    /// The API key is optional -- if `api_key` is `None` and the environment
    /// variable is not set, requests will be sent without an `Authorization`
    /// header.
    pub fn from_config(config: LlmProviderConfig, api_key: Option<String>) -> Self {
        let timeout_secs = config
            .timeout_secs
            .unwrap_or(DEFAULT_LOCAL_TIMEOUT_SECS);
        Self {
            http: reqwest::ClientBuilder::new()
                .timeout(Duration::from_secs(timeout_secs))
                .build()
                .expect("failed to build reqwest client"),
            config,
            api_key,
        }
    }

    /// Create a provider pre-configured for Ollama on the default port.
    pub fn ollama() -> Self {
        Self::new(
            OLLAMA_DEFAULT_BASE_URL.into(),
            DEFAULT_LOCAL_MODEL.into(),
            None,
        )
    }

    /// Create a provider pre-configured for vLLM on the default port.
    pub fn vllm(model: String) -> Self {
        let mut provider = Self::new(
            VLLM_DEFAULT_BASE_URL.into(),
            model,
            None,
        );
        provider.config.name = "vllm".into();
        provider
    }

    /// Create a provider pre-configured for llama.cpp server on the default port.
    pub fn llamacpp() -> Self {
        let mut provider = Self::new(
            LLAMACPP_DEFAULT_BASE_URL.into(),
            DEFAULT_LOCAL_MODEL.into(),
            None,
        );
        provider.config.name = "llamacpp".into();
        provider
    }

    /// Create a provider pre-configured for LM Studio on the default port.
    pub fn lmstudio(model: String) -> Self {
        let mut provider = Self::new(
            LMSTUDIO_DEFAULT_BASE_URL.into(),
            model,
            None,
        );
        provider.config.name = "lmstudio".into();
        provider
    }

    /// Returns the provider configuration.
    pub fn config(&self) -> &LlmProviderConfig {
        &self.config
    }

    /// Returns the chat completions endpoint URL.
    fn completions_url(&self) -> String {
        let base = self.config.base_url.trim_end_matches('/');
        format!("{base}/chat/completions")
    }

    /// Returns the models listing endpoint URL.
    fn models_url(&self) -> String {
        let base = self.config.base_url.trim_end_matches('/');
        format!("{base}/models")
    }

    /// Resolve the API key, returning `None` if no key is available.
    ///
    /// Unlike cloud providers, missing keys are not an error for local providers.
    fn resolve_api_key(&self) -> Option<String> {
        if let Some(ref key) = self.api_key {
            return Some(key.clone());
        }
        std::env::var(&self.config.api_key_env).ok()
    }

    /// List available models on the local server.
    ///
    /// Calls the `/v1/models` endpoint and returns model IDs.
    ///
    /// # Errors
    ///
    /// Returns [`ProviderError`] if the server is unreachable or returns
    /// an unexpected response format.
    pub async fn list_models(&self) -> Result<Vec<String>> {
        let url = self.models_url();

        debug!(
            provider = %self.config.name,
            url = %url,
            "listing local models"
        );

        let mut req = self.http.get(&url);

        if let Some(ref key) = self.resolve_api_key() {
            req = req.header("Authorization", format!("Bearer {key}"));
        }

        for (k, v) in &self.config.headers {
            req = req.header(k.as_str(), v.as_str());
        }

        let response = req.send().await.map_err(|e| {
            ProviderError::RequestFailed(format!(
                "failed to connect to local LLM server at {}: {e}",
                self.config.base_url
            ))
        })?;

        if !response.status().is_success() {
            let body = response.text().await.unwrap_or_default();
            return Err(ProviderError::RequestFailed(format!(
                "model listing failed: {body}"
            )));
        }

        let body: serde_json::Value = response.json().await.map_err(|e| {
            ProviderError::InvalidResponse(format!("failed to parse models response: {e}"))
        })?;

        // OpenAI format: {"data": [{"id": "model-name", ...}, ...]}
        // Ollama format: {"models": [{"name": "model-name", ...}, ...]}
        let models = if let Some(data) = body.get("data").and_then(|d| d.as_array()) {
            data.iter()
                .filter_map(|m| m.get("id").and_then(|id| id.as_str()))
                .map(String::from)
                .collect()
        } else if let Some(models) = body.get("models").and_then(|m| m.as_array()) {
            models
                .iter()
                .filter_map(|m| {
                    m.get("name")
                        .or_else(|| m.get("id"))
                        .and_then(|n| n.as_str())
                })
                .map(String::from)
                .collect()
        } else {
            Vec::new()
        };

        debug!(
            provider = %self.config.name,
            count = models.len(),
            "local models listed"
        );

        Ok(models)
    }
}

#[async_trait]
impl Provider for LocalProvider {
    fn name(&self) -> &str {
        &self.config.name
    }

    async fn complete(&self, request: &ChatRequest) -> Result<ChatResponse> {
        let url = self.completions_url();

        debug!(
            provider = %self.config.name,
            model = %request.model,
            messages = request.messages.len(),
            url = %url,
            "sending local chat completion request"
        );

        let mut req = self
            .http
            .post(&url)
            .header("Content-Type", "application/json");

        // Only add Authorization header if we have a key
        if let Some(ref key) = self.resolve_api_key() {
            req = req.header("Authorization", format!("Bearer {key}"));
        }

        for (k, v) in &self.config.headers {
            req = req.header(k.as_str(), v.as_str());
        }

        let response = req.json(request).send().await.map_err(|e| {
            ProviderError::RequestFailed(format!(
                "failed to connect to local LLM server at {}: {e}",
                self.config.base_url
            ))
        })?;

        let status = response.status();

        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();

            if status.as_u16() == 404 {
                return Err(ProviderError::ModelNotFound(format!(
                    "model '{}' not found on local server ({}): {}",
                    request.model, self.config.base_url, body
                )));
            }

            let code = status.as_u16();
            if (500..=599).contains(&code) {
                return Err(ProviderError::ServerError {
                    status: code,
                    body,
                });
            }

            return Err(ProviderError::RequestFailed(format!(
                "HTTP {status}: {body}"
            )));
        }

        let chat_response: ChatResponse = response.json().await.map_err(|e| {
            ProviderError::InvalidResponse(format!("failed to parse local response: {e}"))
        })?;

        debug!(
            provider = %self.config.name,
            model = %chat_response.model,
            choices = chat_response.choices.len(),
            "local chat completion response received"
        );

        Ok(chat_response)
    }

    async fn complete_stream(
        &self,
        request: &ChatRequest,
        tx: mpsc::Sender<StreamChunk>,
    ) -> Result<()> {
        let url = self.completions_url();

        debug!(
            provider = %self.config.name,
            model = %request.model,
            messages = request.messages.len(),
            "sending local streaming chat completion request"
        );

        let mut stream_request = request.clone();
        stream_request.stream = Some(true);

        let mut req = self
            .http
            .post(&url)
            .header("Content-Type", "application/json")
            .header("Accept", "text/event-stream");

        if let Some(ref key) = self.resolve_api_key() {
            req = req.header("Authorization", format!("Bearer {key}"));
        }

        for (k, v) in &self.config.headers {
            req = req.header(k.as_str(), v.as_str());
        }

        let response = req.json(&stream_request).send().await.map_err(|e| {
            ProviderError::RequestFailed(format!(
                "failed to connect to local LLM server at {}: {e}",
                self.config.base_url
            ))
        })?;

        let status = response.status();
        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();
            if status.as_u16() == 404 {
                return Err(ProviderError::ModelNotFound(format!(
                    "model '{}' not found on local server: {}",
                    request.model, body
                )));
            }
            let code = status.as_u16();
            if (500..=599).contains(&code) {
                return Err(ProviderError::ServerError {
                    status: code,
                    body,
                });
            }
            return Err(ProviderError::RequestFailed(format!(
                "HTTP {status}: {body}"
            )));
        }

        // Read the SSE stream line by line
        use futures_util::StreamExt;
        let mut byte_stream = response.bytes_stream();
        let mut buffer = String::new();

        while let Some(chunk_result) = byte_stream.next().await {
            let bytes = chunk_result
                .map_err(|e| ProviderError::RequestFailed(format!("stream read error: {e}")))?;

            let text = String::from_utf8_lossy(&bytes);
            buffer.push_str(&text);

            while let Some(newline_pos) = buffer.find('\n') {
                let line = buffer[..newline_pos].to_string();
                buffer = buffer[newline_pos + 1..].to_string();

                let chunks = match parse_sse_line(&line) {
                    Ok(c) => c,
                    Err(_) => continue,
                };

                for chunk in chunks {
                    if tx.send(chunk).await.is_err() {
                        debug!(
                            provider = %self.config.name,
                            "stream receiver dropped, stopping"
                        );
                        return Ok(());
                    }
                }
            }
        }

        if !buffer.trim().is_empty()
            && let Ok(chunks) = parse_sse_line(&buffer)
        {
            for chunk in chunks {
                let _ = tx.send(chunk).await;
            }
        }

        debug!(
            provider = %self.config.name,
            "local streaming complete"
        );

        Ok(())
    }
}

impl std::fmt::Debug for LocalProvider {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LocalProvider")
            .field("name", &self.config.name)
            .field("base_url", &self.config.base_url)
            .field("default_model", &self.config.default_model)
            .field("api_key", &self.api_key.as_ref().map(|_| "***"))
            .finish()
    }
}

/// Create an [`LlmProviderConfig`] for a local/Ollama provider.
///
/// This is a convenience function for use in the builtin provider list.
pub fn local_provider_config(
    name: &str,
    base_url: &str,
    default_model: &str,
    prefix: &str,
) -> LlmProviderConfig {
    LlmProviderConfig {
        name: name.into(),
        base_url: base_url.into(),
        api_key_env: "LOCAL_LLM_API_KEY".into(),
        model_prefix: Some(prefix.into()),
        default_model: Some(default_model.into()),
        headers: HashMap::new(),
        timeout_secs: Some(DEFAULT_LOCAL_TIMEOUT_SECS),
    }
}

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

    // ── Construction tests ──────────────────────────────────────────

    #[test]
    fn ollama_defaults() {
        let provider = LocalProvider::ollama();
        assert_eq!(provider.name(), "local");
        assert_eq!(provider.config().base_url, OLLAMA_DEFAULT_BASE_URL);
        assert_eq!(
            provider.config().default_model.as_deref(),
            Some(DEFAULT_LOCAL_MODEL)
        );
        assert!(provider.api_key.is_none());
    }

    #[test]
    fn vllm_defaults() {
        let provider = LocalProvider::vllm("mistral-7b".into());
        assert_eq!(provider.name(), "vllm");
        assert_eq!(provider.config().base_url, VLLM_DEFAULT_BASE_URL);
        assert_eq!(
            provider.config().default_model.as_deref(),
            Some("mistral-7b")
        );
    }

    #[test]
    fn llamacpp_defaults() {
        let provider = LocalProvider::llamacpp();
        assert_eq!(provider.name(), "llamacpp");
        assert_eq!(provider.config().base_url, LLAMACPP_DEFAULT_BASE_URL);
    }

    #[test]
    fn lmstudio_defaults() {
        let provider = LocalProvider::lmstudio("phi-3".into());
        assert_eq!(provider.name(), "lmstudio");
        assert_eq!(provider.config().base_url, LMSTUDIO_DEFAULT_BASE_URL);
        assert_eq!(
            provider.config().default_model.as_deref(),
            Some("phi-3")
        );
    }

    #[test]
    fn custom_local_endpoint() {
        let provider = LocalProvider::new(
            "http://192.168.1.50:9000/v1".into(),
            "hermes-3-llama-3.1-8b".into(),
            Some("custom-key".into()),
        );
        assert_eq!(provider.config().base_url, "http://192.168.1.50:9000/v1");
        assert_eq!(
            provider.config().default_model.as_deref(),
            Some("hermes-3-llama-3.1-8b")
        );
        assert_eq!(provider.api_key.as_deref(), Some("custom-key"));
    }

    // ── URL construction ────────────────────────────────────────────

    #[test]
    fn completions_url_construction() {
        let provider = LocalProvider::ollama();
        assert_eq!(
            provider.completions_url(),
            "http://localhost:11434/v1/chat/completions"
        );
    }

    #[test]
    fn completions_url_strips_trailing_slash() {
        let provider = LocalProvider::new(
            "http://localhost:11434/v1/".into(),
            "test".into(),
            None,
        );
        assert_eq!(
            provider.completions_url(),
            "http://localhost:11434/v1/chat/completions"
        );
    }

    #[test]
    fn models_url_construction() {
        let provider = LocalProvider::ollama();
        assert_eq!(
            provider.models_url(),
            "http://localhost:11434/v1/models"
        );
    }

    // ── API key resolution ──────────────────────────────────────────

    #[test]
    fn resolve_api_key_none_when_missing() {
        let provider = LocalProvider::ollama();
        // No explicit key and env var unlikely to be set
        // This is the key difference from cloud providers -- no error
        let key = provider.resolve_api_key();
        // We can't assert None because LOCAL_LLM_API_KEY might be set,
        // but at minimum it should not panic or error
        let _ = key;
    }

    #[test]
    fn resolve_api_key_explicit() {
        let provider = LocalProvider::new(
            OLLAMA_DEFAULT_BASE_URL.into(),
            "test".into(),
            Some("my-local-key".into()),
        );
        assert_eq!(provider.resolve_api_key(), Some("my-local-key".into()));
    }

    // ── Request formatting ──────────────────────────────────────────

    #[test]
    fn request_body_format() {
        let request = ChatRequest::new(
            "llama3.2",
            vec![
                ChatMessage::system("You are a helpful assistant."),
                ChatMessage::user("What is Rust?"),
            ],
        );
        let json = serde_json::to_value(&request).unwrap();

        assert_eq!(json["model"], "llama3.2");
        assert_eq!(json["messages"].as_array().unwrap().len(), 2);
        assert_eq!(json["messages"][0]["role"], "system");
        assert_eq!(json["messages"][1]["role"], "user");
        assert_eq!(json["messages"][1]["content"], "What is Rust?");
        // stream should not be present by default
        assert!(json.get("stream").is_none());
    }

    #[test]
    fn request_body_with_stream() {
        let mut request = ChatRequest::new(
            "llama3.2",
            vec![ChatMessage::user("Hello")],
        );
        request.stream = Some(true);
        let json = serde_json::to_value(&request).unwrap();
        assert_eq!(json["stream"], true);
    }

    #[test]
    fn request_body_with_options() {
        let request = ChatRequest {
            model: "hermes-3-llama-3.1-8b".into(),
            messages: vec![ChatMessage::user("test")],
            max_tokens: Some(2048),
            temperature: Some(0.7),
            tools: Vec::new(),
            stream: None,
        };
        let json = serde_json::to_value(&request).unwrap();
        assert_eq!(json["model"], "hermes-3-llama-3.1-8b");
        assert_eq!(json["max_tokens"], 2048);
        assert_eq!(json["temperature"], 0.7);
    }

    // ── Response parsing ────────────────────────────────────────────

    #[test]
    fn parse_ollama_response() {
        // Ollama returns standard OpenAI format via /v1 endpoint
        let json = r#"{
            "id": "chatcmpl-123",
            "object": "chat.completion",
            "created": 1677652288,
            "model": "llama3.2",
            "choices": [{
                "index": 0,
                "message": {
                    "role": "assistant",
                    "content": "Rust is a systems programming language."
                },
                "finish_reason": "stop"
            }],
            "usage": {
                "prompt_tokens": 12,
                "completion_tokens": 8,
                "total_tokens": 20
            }
        }"#;

        let response: ChatResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.model, "llama3.2");
        assert_eq!(response.choices.len(), 1);
        assert_eq!(
            response.choices[0].message.content.as_deref(),
            Some("Rust is a systems programming language.")
        );
        assert_eq!(
            response.choices[0].finish_reason.as_deref(),
            Some("stop")
        );
        let usage = response.usage.unwrap();
        assert_eq!(usage.input_tokens, 12);
        assert_eq!(usage.output_tokens, 8);
        assert_eq!(usage.total_tokens, 20);
    }

    #[test]
    fn parse_vllm_response() {
        // vLLM returns standard OpenAI format
        let json = r#"{
            "id": "cmpl-abc123",
            "object": "chat.completion",
            "created": 1700000000,
            "model": "NousResearch/Hermes-3-Llama-3.1-8B",
            "choices": [{
                "index": 0,
                "message": {
                    "role": "assistant",
                    "content": "Hello! How can I help you today?"
                },
                "finish_reason": "stop"
            }],
            "usage": {
                "prompt_tokens": 5,
                "completion_tokens": 9,
                "total_tokens": 14
            }
        }"#;

        let response: ChatResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.model, "NousResearch/Hermes-3-Llama-3.1-8B");
        assert_eq!(
            response.choices[0].message.content.as_deref(),
            Some("Hello! How can I help you today?")
        );
    }

    #[test]
    fn parse_response_without_usage() {
        // Some local servers omit usage stats
        let json = r#"{
            "id": "chatcmpl-local",
            "choices": [{
                "index": 0,
                "message": {
                    "role": "assistant",
                    "content": "Hi!"
                },
                "finish_reason": "stop"
            }],
            "usage": null,
            "model": "llama3.2"
        }"#;

        let response: ChatResponse = serde_json::from_str(json).unwrap();
        assert!(response.usage.is_none());
        assert_eq!(
            response.choices[0].message.content.as_deref(),
            Some("Hi!")
        );
    }

    #[test]
    fn parse_response_with_tool_calls() {
        // Hermes models support function calling
        let json = r#"{
            "id": "chatcmpl-hermes",
            "model": "hermes-3-llama-3.1-8b",
            "choices": [{
                "index": 0,
                "message": {
                    "role": "assistant",
                    "tool_calls": [{
                        "id": "call_001",
                        "type": "function",
                        "function": {
                            "name": "get_weather",
                            "arguments": "{\"city\": \"San Francisco\"}"
                        }
                    }]
                },
                "finish_reason": "tool_calls"
            }],
            "usage": {
                "prompt_tokens": 20,
                "completion_tokens": 15,
                "total_tokens": 35
            }
        }"#;

        let response: ChatResponse = serde_json::from_str(json).unwrap();
        let tool_calls = response.choices[0].message.tool_calls.as_ref().unwrap();
        assert_eq!(tool_calls.len(), 1);
        assert_eq!(tool_calls[0].function.name, "get_weather");
        assert!(tool_calls[0].function.arguments.contains("San Francisco"));
    }

    // ── Model listing response parsing ──────────────────────────────

    #[test]
    fn parse_openai_models_response() {
        let json = r#"{
            "data": [
                {"id": "llama3.2", "object": "model"},
                {"id": "codellama", "object": "model"},
                {"id": "hermes-3", "object": "model"}
            ]
        }"#;
        let body: serde_json::Value = serde_json::from_str(json).unwrap();
        let models: Vec<String> = body
            .get("data")
            .and_then(|d| d.as_array())
            .unwrap()
            .iter()
            .filter_map(|m| m.get("id").and_then(|id| id.as_str()))
            .map(String::from)
            .collect();
        assert_eq!(models, vec!["llama3.2", "codellama", "hermes-3"]);
    }

    #[test]
    fn parse_ollama_models_response() {
        // Ollama's native /api/tags returns a different format, but
        // the /v1/models endpoint uses the OpenAI format
        let json = r#"{
            "models": [
                {"name": "llama3.2:latest"},
                {"name": "hermes-3:8b"}
            ]
        }"#;
        let body: serde_json::Value = serde_json::from_str(json).unwrap();
        let models: Vec<String> = body
            .get("models")
            .and_then(|m| m.as_array())
            .unwrap()
            .iter()
            .filter_map(|m| m.get("name").and_then(|n| n.as_str()))
            .map(String::from)
            .collect();
        assert_eq!(models, vec!["llama3.2:latest", "hermes-3:8b"]);
    }

    // ── Debug output ────────────────────────────────────────────────

    #[test]
    fn debug_hides_api_key() {
        let provider = LocalProvider::new(
            OLLAMA_DEFAULT_BASE_URL.into(),
            "test".into(),
            Some("secret-key-123".into()),
        );
        let debug_str = format!("{:?}", provider);
        assert!(!debug_str.contains("secret-key-123"));
        assert!(debug_str.contains("***"));
    }

    #[test]
    fn debug_shows_none_for_missing_key() {
        let provider = LocalProvider::ollama();
        let debug_str = format!("{:?}", provider);
        assert!(debug_str.contains("None"));
        assert!(debug_str.contains("localhost:11434"));
    }

    // ── Config helper ───────────────────────────────────────────────

    #[test]
    fn local_provider_config_helper() {
        let config = local_provider_config(
            "ollama",
            OLLAMA_DEFAULT_BASE_URL,
            DEFAULT_LOCAL_MODEL,
            "local/",
        );
        assert_eq!(config.name, "ollama");
        assert_eq!(config.base_url, "http://localhost:11434/v1");
        assert_eq!(config.default_model.as_deref(), Some("llama3.2"));
        assert_eq!(config.model_prefix.as_deref(), Some("local/"));
        assert_eq!(config.timeout_secs, Some(300));
    }

    // ── Timeout configuration ───────────────────────────────────────

    #[test]
    fn default_timeout_is_300s() {
        let provider = LocalProvider::ollama();
        assert_eq!(
            provider.config().timeout_secs,
            Some(DEFAULT_LOCAL_TIMEOUT_SECS)
        );
    }

    #[test]
    fn custom_timeout() {
        let config = LlmProviderConfig {
            name: "local".into(),
            base_url: OLLAMA_DEFAULT_BASE_URL.into(),
            api_key_env: "LOCAL_LLM_API_KEY".into(),
            model_prefix: Some("local/".into()),
            default_model: Some("test".into()),
            headers: HashMap::new(),
            timeout_secs: Some(60),
        };
        let provider = LocalProvider::from_config(config, None);
        assert_eq!(provider.config().timeout_secs, Some(60));
    }

    // ── Streaming request format ────────────────────────────────────

    #[test]
    fn stream_request_sets_stream_true() {
        let mut request = ChatRequest::new(
            "llama3.2",
            vec![ChatMessage::user("Hi")],
        );
        request.stream = Some(true);
        let json = serde_json::to_value(&request).unwrap();
        assert_eq!(json["stream"], true);
        assert_eq!(json["model"], "llama3.2");
    }

    // ── SSE parsing for local providers ─────────────────────────────

    #[test]
    fn parse_local_sse_text_delta() {
        use crate::sse::parse_sse_line;
        let line = r#"data: {"id":"chatcmpl-local","choices":[{"index":0,"delta":{"content":"Hello"},"finish_reason":null}]}"#;
        let chunks = parse_sse_line(line).unwrap();
        assert_eq!(chunks.len(), 1);
        assert_eq!(
            chunks[0],
            StreamChunk::TextDelta {
                text: "Hello".into()
            }
        );
    }

    #[test]
    fn parse_local_sse_done() {
        use crate::sse::parse_sse_line;
        let line = r#"data: {"id":"chatcmpl-local","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}"#;
        let chunks = parse_sse_line(line).unwrap();
        assert_eq!(chunks.len(), 1);
        assert_eq!(
            chunks[0],
            StreamChunk::Done {
                finish_reason: Some("stop".into()),
                usage: None,
            }
        );
    }

    #[test]
    fn parse_local_sse_with_usage() {
        use crate::sse::parse_sse_line;
        // Ollama includes usage in the final chunk
        let line = r#"data: {"id":"chatcmpl-local","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":10,"completion_tokens":20,"total_tokens":30}}"#;
        let chunks = parse_sse_line(line).unwrap();
        assert_eq!(chunks.len(), 1);
        assert_eq!(
            chunks[0],
            StreamChunk::Done {
                finish_reason: Some("stop".into()),
                usage: Some(crate::types::Usage {
                    input_tokens: 10,
                    output_tokens: 20,
                    total_tokens: 30,
                }),
            }
        );
    }
}