vlorql-llm 0.5.0

Multi-provider LLM client for SQL query generation supporting Anthropic, DeepSeek, Zhipu, and local models
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
//! DeepSeek chat-completions client.
//!
//! DeepSeek's public API is OpenAI-compatible: it accepts the standard
//! `/chat/completions` payload and returns the same response envelope,
//! including the SSE streaming format. This client reuses that
//! compatibility while applying DeepSeek-specific quirks:
//!
//! * The default endpoint points at `https://api.deepseek.com/v1/chat/completions`
//!   but can be overridden via `LlmConfig::api_base` for proxies / private
//!   deployments.
//! * The API key is sourced from `LlmConfig::api_key` first, then from the
//!   `DEEPSEEK_API_KEY` environment variable.
//! * DeepSeek only accepts the `{"type": "json_object"}` response format.
//!   Unlike OpenAI, it does not (yet) support the strict `json_schema`
//!   mode, so the system prompt must include a JSON Schema example and
//!   the word "json" for the model to honour the structured output.
//!   The returned `content` is then validated client-side by attempting
//!   to deserialise it into a [`QueryPlan`](vlorql_core::schema::QueryPlan).
//! * Operators upgrading from `deepseek-chat` / `deepseek-reasoner`
//!   (deprecated on 2026-07-24) should switch to `deepseek-v4-flash` or
//!   `deepseek-v4-pro`. Building a client with a deprecated model name
//!   emits a `tracing::warn!` hint.
//! * Empty `choices[0].message.content` payloads are surfaced as a
//!   dedicated `LlmErrorKind::ParseError` so callers can distinguish a
//!   refusal / silent failure from a malformed JSON body.

use async_trait::async_trait;
use serde_json::{Value, json};
use std::sync::Arc;
use std::time::Duration;
use tracing::warn;
use vlorql_core::errors::{ConfigErrorKind, LlmErrorKind, VlorQLError};
use vlorql_core::schema::QueryPlan;

use crate::sse::{transport_error, truncate};
use crate::{
    DEFAULT_MAX_ATTEMPTS, LlmClient, LlmConfig, LlmProvider, RetryableHttpClient, StreamResult,
    TokenUsage,
};

const DEFAULT_API_BASE: &str = "https://api.deepseek.com/v1/chat/completions";
const DEEPSEEK_API_KEY_ENV: &str = "DEEPSEEK_API_KEY";

/// DeepSeek chat-completions client.
#[derive(Clone)]
pub struct DeepSeekClient {
    config: LlmConfig,
    client: reqwest::Client,
    api_key: String,
}

impl std::fmt::Debug for DeepSeekClient {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("DeepSeekClient")
            .field("api_key", &"[REDACTED]")
            .field("provider", &self.config.provider)
            .field("model", &self.config.model)
            .field("api_base", &self.config.api_base)
            .field("max_retries", &self.max_attempts())
            .finish()
    }
}

impl DeepSeekClient {
    /// Builds a new DeepSeek client from a populated [`LlmConfig`].
    ///
    /// The API key is taken from `config.api_key` (if non-empty) or from
    /// the `DEEPSEEK_API_KEY` environment variable. Either source must
    /// produce a non-empty key, otherwise a `Config` error is returned.
    pub fn new(config: LlmConfig) -> Result<Self, VlorQLError> {
        if config.model.trim().is_empty() {
            return Err(VlorQLError::config(
                ConfigErrorKind::EmptyModel,
                json!({"provider": LlmProvider::DeepSeek, "field": "model"}),
            ));
        }
        let api_key = config
            .api_key
            .clone()
            .or_else(|| std::env::var(DEEPSEEK_API_KEY_ENV).ok())
            .map(|value| value.trim().to_owned())
            .filter(|value| !value.is_empty())
            .ok_or_else(|| {
                VlorQLError::config(
                    ConfigErrorKind::MissingApiKey {
                        provider: "deepseek".to_owned(),
                    },
                    json!({
                        "provider": LlmProvider::DeepSeek,
                        "env": DEEPSEEK_API_KEY_ENV,
                    }),
                )
            })?;
        let timeout = Duration::from_secs(config.timeout_seconds.max(1));
        let client = reqwest::Client::builder()
            .timeout(timeout)
            .build()
            .unwrap_or_else(|_| reqwest::Client::new());
        let model_lower = config.model.to_ascii_lowercase();
        if model_lower == "deepseek-chat" || model_lower == "deepseek-reasoner" {
            warn!(
                "DeepSeek model `{}` is deprecated and will be removed on 2026-07-24; \
                 switch to `deepseek-v4-flash` or `deepseek-v4-pro`",
                config.model,
            );
        }
        Ok(Self {
            config,
            client,
            api_key,
        })
    }

    /// Returns the effective endpoint URL.
    fn endpoint(&self) -> String {
        self.config
            .api_base
            .clone()
            .unwrap_or_else(|| DEFAULT_API_BASE.to_owned())
    }

    /// Builds the JSON body sent to the DeepSeek chat-completions endpoint.
    ///
    /// The body shape is OpenAI-compatible. DeepSeek does not support the
    /// strict `json_schema` mode, so `response_format` is always set to
    /// `{"type": "json_object"}` and the caller is expected to embed a
    /// JSON Schema example (containing the word "json") in the system
    /// prompt so the model emits structured output. When `stream` is
    /// `true`, the `stream` flag is toggled on for SSE delivery.
    fn build_request_body(
        &self,
        question: &str,
        system_prompt: &str,
        stream: bool,
        temperature: Option<f32>,
    ) -> Value {
        let mut body = json!({
            "model": self.config.model,
            "messages": [
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": question},
            ],
            "response_format": {"type": "json_object"},
            "temperature": temperature.unwrap_or(self.config.temperature),
            "max_tokens": self.config.max_tokens,
        });
        if stream {
            body["stream"] = Value::Bool(true);
        }
        body
    }
}

#[async_trait]
impl RetryableHttpClient for DeepSeekClient {
    fn max_attempts(&self) -> usize {
        usize::try_from(self.config.max_retries.max(1)).unwrap_or(DEFAULT_MAX_ATTEMPTS)
    }

    fn provider_label(&self) -> &'static str {
        "deepseek"
    }

    fn parse_response(&self, body: &str) -> Result<QueryPlan, VlorQLError> {
        parse_completion_payload(body)
    }

    async fn send_request(
        &self,
        endpoint: &str,
        body: &Value,
    ) -> Result<reqwest::Response, VlorQLError> {
        self.client
            .post(endpoint)
            .bearer_auth(&self.api_key)
            .header("accept", "text/event-stream")
            .json(body)
            .send()
            .await
            .map_err(|error| transport_error(&error))
    }
}

#[async_trait]
impl LlmClient for DeepSeekClient {
    async fn generate_plan(
        &self,
        question: &str,
        system_prompt: &str,
        temperature: Option<f32>,
    ) -> Result<(QueryPlan, TokenUsage), VlorQLError> {
        let endpoint = self.endpoint();
        let body = self.build_request_body(question, system_prompt, false, temperature);
        self.generate_with_retry(&endpoint, &body).await
    }

    async fn stream_plan(
        &self,
        question: String,
        system_prompt: String,
    ) -> Result<StreamResult, VlorQLError> {
        let endpoint = self.endpoint();
        let body = self.build_request_body(&question, &system_prompt, true, None);
        let usage = Arc::new(tokio::sync::Mutex::new(None));
        let usage_clone = Arc::clone(&usage);
        let extract = move |data: &Value| {
            if let Some(u) = data.get("usage")
                && let Ok(mut guard) = usage_clone.try_lock()
            {
                *guard = Some(TokenUsage {
                    prompt_tokens: u.get("prompt_tokens").and_then(|v| v.as_u64()).unwrap_or(0),
                    completion_tokens: u
                        .get("completion_tokens")
                        .and_then(|v| v.as_u64())
                        .unwrap_or(0),
                });
            }
            data.pointer("/choices/0/delta/content")
                .and_then(|v| v.as_str().map(String::from))
        };
        let stream = self.stream_with_sse(&endpoint, &body, extract).await?;
        Ok(StreamResult { stream, usage })
    }

    fn provider(&self) -> LlmProvider {
        LlmProvider::DeepSeek
    }

    fn config(&self) -> &LlmConfig {
        &self.config
    }
}

/// Parses a DeepSeek chat-completions JSON response into a [`QueryPlan`](vlorql_core::schema::QueryPlan).
///
/// Empty `content` payloads are converted into a dedicated
/// `LlmErrorKind::ParseError` so callers can distinguish a refusal (or
/// a prompt that forgot the word "json") from a malformed JSON body or
/// an HTTP transport failure.
fn parse_completion_payload(body: &str) -> Result<QueryPlan, VlorQLError> {
    let value: Value = serde_json::from_str(body).map_err(|error| {
        VlorQLError::llm(
            LlmErrorKind::ParseError {
                details: format!("DeepSeek response is not valid JSON: {error}"),
            },
            json!({
                "source": "deepseek_response",
                "body": truncate(body, 1024),
            }),
        )
    })?;
    if let Some(error) = value.get("error") {
        return Err(VlorQLError::llm(
            LlmErrorKind::ApiError {
                status: 0,
                message: error
                    .get("message")
                    .and_then(Value::as_str)
                    .unwrap_or("deepseek returned an error")
                    .to_owned(),
            },
            json!({"source": "deepseek_error", "error": error}),
        ));
    }
    let content = value
        .get("choices")
        .and_then(Value::as_array)
        .and_then(|choices| choices.first())
        .and_then(|choice| choice.get("message"))
        .and_then(|message| message.get("content"))
        .and_then(Value::as_str)
        .ok_or_else(|| {
            VlorQLError::llm(
                LlmErrorKind::ParseError {
                    details: "DeepSeek response did not contain choices[0].message.content"
                        .to_owned(),
                },
                json!({"source": "deepseek_response"}),
            )
        })?;
    if content.is_empty() {
        return Err(VlorQLError::llm(
            LlmErrorKind::ParseError {
                details: "DeepSeek returned an empty content; ensure the system prompt \
                         contains the word 'json' and a JSON Schema example"
                    .to_owned(),
            },
            json!({"source": "deepseek_content"}),
        ));
    }
    crate::parse_llm_response(content).map_err(|error| {
        VlorQLError::llm(
            LlmErrorKind::ParseError {
                details: format!("assistant content is not a valid QueryPlan: {error}"),
            },
            json!({
                "source": "deepseek_content",
                "content": truncate(content, 4096),
            }),
        )
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use mockito::{Matcher, Server};
    use vlorql_core::schema::{FromClause, Projection, QueryPlan};

    const AUTH_HEADER: &str = "authorization";

    struct RestoreEnv(Option<String>);
    impl Drop for RestoreEnv {
        fn drop(&mut self) {
            match &self.0 {
                Some(previous) => unsafe { std::env::set_var(DEEPSEEK_API_KEY_ENV, previous) },
                None => unsafe { std::env::remove_var(DEEPSEEK_API_KEY_ENV) },
            }
        }
    }

    fn plan() -> QueryPlan {
        QueryPlan {
            select: vec![Projection::Column {
                table: Some("users".to_owned()),
                column: "id".to_owned(),
                alias: None,
            }],
            from: FromClause::table("users".to_owned(), Some("t1".to_owned())),
            r#where: None,
            group_by: None,
            having: None,
            order_by: None,
            limit: None,
            offset: None,
            joins: None,
            ctes: None,
            distinct: false,
            distinct_on: None,
            set_operation: None,
        }
    }

    fn deepseek_config(model: &str) -> LlmConfig {
        LlmConfig {
            provider: LlmProvider::DeepSeek,
            api_key: Some("test-key".to_owned()),
            api_base: None,
            model: model.to_owned(),
            max_tokens: 4096,
            temperature: 0.0,
            timeout_seconds: 60,
            max_retries: 1,
            extra: std::collections::HashMap::new(),
        }
    }

    fn chat_response(plan: &QueryPlan) -> String {
        json!({
            "id": "chatcmpl-1",
            "model": "deepseek-v4-pro",
            "choices": [{
                "index": 0,
                "message": {
                    "role": "assistant",
                    "content": serde_json::to_string(plan).expect("plan should serialize"),
                },
                "finish_reason": "stop",
            }],
            "usage": {"prompt_tokens": 1, "completion_tokens": 2, "total_tokens": 3},
        })
        .to_string()
    }

    #[tokio::test]
    async fn deepseek_client_uses_json_object_mode() {
        let mut server = Server::new_async().await;
        let expected = plan();
        let mock = server
            .mock("POST", "/chat/completions")
            .match_header(AUTH_HEADER, "Bearer test-key")
            .match_body(Matcher::Regex(
                r#""model":"deepseek-v4-pro".*"response_format":\{"type":"json_object"\}"#
                    .to_owned(),
            ))
            .with_status(200)
            .with_body(chat_response(&expected))
            .create_async()
            .await;

        let config = LlmConfig {
            api_base: Some(format!("{}/chat/completions", server.url())),
            ..deepseek_config("deepseek-v4-pro")
        };
        let client = DeepSeekClient::new(config).expect("client should build");

        let body = client.build_request_body("show users", "system", false, None);
        assert_eq!(body["model"], "deepseek-v4-pro");
        assert_eq!(body["response_format"]["type"], "json_object");
        assert_eq!(body["temperature"], 0.0);
        assert_eq!(body["max_tokens"], 4096);
        let messages = body["messages"].as_array().expect("messages array");
        assert_eq!(messages.len(), 2);
        assert_eq!(messages[0]["role"], "system");
        assert_eq!(messages[0]["content"], "system");
        assert_eq!(messages[1]["role"], "user");
        assert_eq!(messages[1]["content"], "show users");

        let (actual, _usage) = client
            .generate_plan("show users", "system", None)
            .await
            .expect("plan should parse");
        assert_eq!(actual, expected);
        assert_eq!(client.provider(), LlmProvider::DeepSeek);
        assert_eq!(client.config().model, "deepseek-v4-pro");
        mock.assert_async().await;
    }

    #[test]
    fn deepseek_client_build_request_body_overrides_temperature() {
        let config = deepseek_config("deepseek-v4-pro");
        let client = DeepSeekClient::new(config).expect("client should build");

        let overridden = client.build_request_body("show users", "system", false, Some(0.7));
        let overridden_temperature = overridden["temperature"]
            .as_f64()
            .expect("temperature should serialize as a number");
        assert!(
            (overridden_temperature - 0.7).abs() < 1e-6,
            "expected ~0.7, got {overridden_temperature}"
        );

        let default = client.build_request_body("show users", "system", false, None);
        assert_eq!(default["temperature"], client.config().temperature);
    }

    #[tokio::test]
    async fn deepseek_client_parses_query_plan_response() {
        let mut server = Server::new_async().await;
        let expected = plan();
        let mock = server
            .mock("POST", "/chat/completions")
            .with_status(200)
            .with_body(chat_response(&expected))
            .create_async()
            .await;
        let config = LlmConfig {
            api_base: Some(format!("{}/chat/completions", server.url())),
            ..deepseek_config("deepseek-v4-pro")
        };
        let client = DeepSeekClient::new(config).expect("client should build");
        let (actual, _usage) = client
            .generate_plan("show users", "system", None)
            .await
            .expect("plan should parse");
        assert_eq!(actual, expected);
        mock.assert_async().await;
    }

    #[tokio::test]
    async fn deepseek_client_returns_error_for_empty_content() {
        let mut server = Server::new_async().await;
        let mock = server
            .mock("POST", "/chat/completions")
            .with_status(200)
            .with_body(
                json!({
                    "choices": [{
                        "message": {"role": "assistant", "content": ""}
                    }]
                })
                .to_string(),
            )
            .create_async()
            .await;
        let config = LlmConfig {
            api_base: Some(format!("{}/chat/completions", server.url())),
            ..deepseek_config("deepseek-v4-pro")
        };
        let client = DeepSeekClient::new(config).expect("client should build");
        let error = client
            .generate_plan("hi", "system", None)
            .await
            .expect_err("empty content should fail");
        assert_eq!(error.error_code(), "L003");
        mock.assert_async().await;
    }

    #[tokio::test]
    async fn deepseek_client_returns_error_for_missing_content_field() {
        let mut server = Server::new_async().await;
        let mock = server
            .mock("POST", "/chat/completions")
            .with_status(200)
            .with_body(
                json!({
                    "choices": [{"message": {"role": "assistant"}}]
                })
                .to_string(),
            )
            .create_async()
            .await;
        let config = LlmConfig {
            api_base: Some(format!("{}/chat/completions", server.url())),
            ..deepseek_config("deepseek-v4-pro")
        };
        let client = DeepSeekClient::new(config).expect("client should build");
        let error = client
            .generate_plan("hi", "system", None)
            .await
            .expect_err("missing content should fail");
        assert_eq!(error.error_code(), "L003");
        mock.assert_async().await;
    }

    #[tokio::test]
    async fn deepseek_client_converts_error_response() {
        let mut server = Server::new_async().await;
        let mock = server
            .mock("POST", "/chat/completions")
            .with_status(429)
            .with_body(json!({"error": {"message": "rate limited"}}).to_string())
            .create_async()
            .await;
        let config = LlmConfig {
            api_base: Some(format!("{}/chat/completions", server.url())),
            ..deepseek_config("deepseek-v4-pro")
        };
        let client = DeepSeekClient::new(config).expect("client should build");
        let error = client
            .generate_plan("hi", "system", None)
            .await
            .expect_err("429 should be reported");
        assert_eq!(error.error_code(), "L001");
        mock.assert_async().await;
    }

    #[tokio::test]
    async fn deepseek_client_converts_invalid_plan_to_llm_parse_error() {
        let mut server = Server::new_async().await;
        let mock = server
            .mock("POST", "/chat/completions")
            .with_status(200)
            .with_body(
                json!({
                    "choices": [{
                        "message": {"role": "assistant", "content": r#"{"unexpected":true}"#}
                    }]
                })
                .to_string(),
            )
            .create_async()
            .await;
        let config = LlmConfig {
            api_base: Some(format!("{}/chat/completions", server.url())),
            ..deepseek_config("deepseek-v4-pro")
        };
        let client = DeepSeekClient::new(config).expect("client should build");
        let error = client
            .generate_plan("hi", "system", None)
            .await
            .expect_err("invalid plan should fail");
        assert_eq!(error.error_code(), "L003");
        mock.assert_async().await;
    }

    #[tokio::test]
    async fn deepseek_client_stream_emits_delta_chunks() {
        use futures::StreamExt;
        let mut server = Server::new_async().await;
        let body = [
            format!(
                "data: {}\n\n",
                json!({
                    "id": "1",
                    "choices": [{"delta": {"content": "hello "}}],
                })
            ),
            format!(
                "data: {}\n\n",
                json!({
                    "id": "1",
                    "choices": [{"delta": {"content": "world"}}],
                })
            ),
            "data: [DONE]\n".to_owned(),
        ]
        .join("");
        let mock = server
            .mock("POST", "/chat/completions")
            .match_header("accept", "text/event-stream")
            .with_status(200)
            .with_header("content-type", "text/event-stream")
            .with_body(body)
            .create_async()
            .await;
        let config = LlmConfig {
            api_base: Some(format!("{}/chat/completions", server.url())),
            ..deepseek_config("deepseek-v4-pro")
        };
        let client = DeepSeekClient::new(config).expect("client should build");
        let body = client.build_request_body("hi", "system", true, None);
        assert_eq!(body["stream"], true);
        assert_eq!(body["response_format"]["type"], "json_object");

        let mut result = client
            .stream_plan("hi".to_owned(), "system".to_owned())
            .await
            .expect("stream should be produced");
        let mut combined = String::new();
        while let Some(chunk) = result.stream.next().await {
            combined.push_str(&chunk.expect("chunk should be Ok"));
        }
        assert_eq!(combined, "hello world");
        mock.assert_async().await;
    }

    #[tokio::test]
    async fn deepseek_client_stream_propagates_http_error() {
        let mut server = Server::new_async().await;
        let mock = server
            .mock("POST", "/chat/completions")
            .with_status(500)
            .with_body(r#"{"error":{"message":"down"}}"#)
            .create_async()
            .await;
        let config = LlmConfig {
            api_base: Some(format!("{}/chat/completions", server.url())),
            ..deepseek_config("deepseek-v4-pro")
        };
        let client = DeepSeekClient::new(config).expect("client should build");
        let outcome = client
            .stream_plan("hi".to_owned(), "system".to_owned())
            .await;
        let err = match outcome {
            Ok(_) => panic!("500 should produce an error"),
            Err(error) => error,
        };
        assert_eq!(err.error_code(), "L001");
        mock.assert_async().await;
    }

    #[tokio::test]
    async fn deepseek_client_retries_retryable_http_errors() {
        let mut server = Server::new_async().await;
        let expected = plan();
        let failures = server
            .mock("POST", "/chat/completions")
            .with_status(503)
            .with_body(r#"{"error":{"message":"busy"}}"#)
            .expect(2)
            .create_async()
            .await;
        let success = server
            .mock("POST", "/chat/completions")
            .with_status(200)
            .with_body(chat_response(&expected))
            .create_async()
            .await;

        let config = LlmConfig {
            api_base: Some(format!("{}/chat/completions", server.url())),
            max_retries: 3,
            ..deepseek_config("deepseek-v4-pro")
        };
        let client = DeepSeekClient::new(config).expect("client should build");

        let (actual, _usage) = client
            .generate_plan("hi", "system", None)
            .await
            .expect("retry should succeed");
        assert_eq!(actual, expected);
        failures.assert_async().await;
        success.assert_async().await;
    }

    #[test]
    fn deepseek_client_requires_api_key() {
        let guard = RestoreEnv(std::env::var(DEEPSEEK_API_KEY_ENV).ok());
        // Clear any leaked env var so the test does not depend on the host.
        unsafe {
            std::env::remove_var(DEEPSEEK_API_KEY_ENV);
        }
        let mut config = deepseek_config("deepseek-v4-pro");
        config.api_key = None;
        config.api_base = None;
        let result = DeepSeekClient::new(config);
        drop(guard);
        let error = match result {
            Ok(_) => panic!("missing api key should fail"),
            Err(error) => error,
        };
        assert_eq!(error.error_code(), "G004");
    }

    #[tokio::test]
    async fn deepseek_client_reads_api_key_from_env() {
        let mut server = Server::new_async().await;
        let expected = plan();
        let mock = server
            .mock("POST", "/chat/completions")
            .match_header(AUTH_HEADER, "Bearer env-key")
            .with_status(200)
            .with_body(chat_response(&expected))
            .create_async()
            .await;

        let guard = RestoreEnv(std::env::var(DEEPSEEK_API_KEY_ENV).ok());
        // SAFETY: tests in this module run on a single-threaded test
        // harness so setting an env var here is observable only by this
        // process.
        unsafe {
            std::env::set_var(DEEPSEEK_API_KEY_ENV, "env-key");
        }
        let mut config = deepseek_config("deepseek-v4-pro");
        config.api_key = None;
        config.api_base = Some(format!("{}/chat/completions", server.url()));
        let client = match DeepSeekClient::new(config) {
            Ok(client) => client,
            Err(error) => {
                drop(guard);
                panic!("client should build from env var: {error}");
            }
        };
        let result = client.generate_plan("q", "s", None).await;
        drop(guard);
        let (actual, _usage) = result.expect("env-keyed request should succeed");
        assert_eq!(actual, expected);
        mock.assert_async().await;
    }

    #[test]
    fn deepseek_client_endpoint_uses_default_when_unset() {
        let mut config = deepseek_config("deepseek-v4-pro");
        config.api_base = None;
        let client = DeepSeekClient::new(config).expect("client should build");
        assert_eq!(client.endpoint(), DEFAULT_API_BASE);
    }

    #[test]
    fn deepseek_client_endpoint_uses_override_when_set() {
        let mut config = deepseek_config("deepseek-v4-pro");
        config.api_base = Some("https://proxy.example.test/v1/chat/completions".to_owned());
        let client = DeepSeekClient::new(config).expect("client should build");
        assert_eq!(
            client.endpoint(),
            "https://proxy.example.test/v1/chat/completions"
        );
    }

    #[test]
    fn deepseek_client_rejects_empty_model_name() {
        let key_backup = std::env::var(DEEPSEEK_API_KEY_ENV).ok();
        let mut config = deepseek_config("placeholder");
        config.model = "   ".to_owned();
        config.api_base = None;
        let result = DeepSeekClient::new(config);
        if let Some(previous) = key_backup {
            unsafe {
                std::env::set_var(DEEPSEEK_API_KEY_ENV, previous);
            }
        }
        let error = match result {
            Ok(_) => panic!("empty model should fail"),
            Err(error) => error,
        };
        assert_eq!(error.error_code(), "G005");
    }

    #[test]
    fn deepseek_client_emits_deprecation_warning_for_legacy_models() {
        // Building a client with a deprecated model name should succeed
        // (we still want to let operators migrate), and the tracing
        // warning is exercised in production via the tracing subscriber.
        let config = deepseek_config("deepseek-chat");
        let client = DeepSeekClient::new(config).expect("client should build");
        assert_eq!(client.config().model, "deepseek-chat");

        let config = deepseek_config("deepseek-reasoner");
        let client = DeepSeekClient::new(config).expect("client should build");
        assert_eq!(client.config().model, "deepseek-reasoner");
    }

    #[test]
    fn deepseek_parse_completion_payload_rejects_non_json_body() {
        let error = parse_completion_payload("not json").expect_err("non-JSON body should fail");
        assert_eq!(error.error_code(), "L003");
    }

    #[test]
    fn deepseek_parse_completion_payload_extracts_top_level_error() {
        let body = json!({
            "error": {"type": "rate_limit_error", "message": "slow down"}
        })
        .to_string();
        let error = parse_completion_payload(&body).expect_err("top-level error should fail");
        assert_eq!(error.error_code(), "L001");
    }
}