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
//! Zhipu GLM chat-completions client.
//!
//! Zhipu'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 a few Zhipu-specific defaults:
//!
//! * The default endpoint points at `https://open.bigmodel.cn/api/paas/v4/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
//!   `ZHIPU_API_KEY` environment variable.
//! * GLM-4.7+ natively supports `{"type": "json_schema", ...}` payloads.
//!   Older GLM models (e.g. `glm-4`, `glm-3-turbo`) only accept the
//!   looser `{"type": "json_object"}`; the client picks the appropriate
//!   shape based on the configured model name.
//! * GLM-4.7 supports a 200K context window, so the client raises the
//!   `max_tokens` default to 4 096 when the operator leaves it at the
//!   crate-wide 1 024 placeholder.

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

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

const DEFAULT_API_BASE: &str = "https://open.bigmodel.cn/api/paas/v4/chat/completions";
const ZHIPU_API_KEY_ENV: &str = "ZHIPU_API_KEY";
const DEFAULT_MAX_TOKENS: u32 = 4_096;
const MIN_MAX_TOKENS: u32 = 256;

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

impl std::fmt::Debug for ZhipuClient {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("ZhipuClient")
            .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 ZhipuClient {
    /// Builds a new Zhipu client from a populated [`LlmConfig`].
    ///
    /// The API key is taken from `config.api_key` (if non-empty) or from
    /// the `ZHIPU_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::Zhipu, "field": "model"}),
            ));
        }
        let api_key = config
            .api_key
            .clone()
            .or_else(|| std::env::var(ZHIPU_API_KEY_ENV).ok())
            .map(|value| value.trim().to_owned())
            .filter(|value| !value.is_empty())
            .ok_or_else(|| {
                VlorQLError::config(
                    ConfigErrorKind::MissingApiKey {
                        provider: "zhipu".to_owned(),
                    },
                    json!({
                        "provider": LlmProvider::Zhipu,
                        "env": ZHIPU_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());
        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())
    }

    /// Returns the `max_tokens` value sent on the wire.
    ///
    /// Zhipu's GLM-4.7+ supports a 200K context window, so the default
    /// 1 024 budget shipped with `LlmConfig` is raised to 4 096 unless
    /// the operator explicitly set a different value.
    fn effective_max_tokens(&self) -> u32 {
        if self.config.max_tokens == 0 {
            DEFAULT_MAX_TOKENS
        } else if self.config.max_tokens < MIN_MAX_TOKENS {
            MIN_MAX_TOKENS
        } else {
            self.config.max_tokens
        }
    }

    /// Returns whether the configured model supports Zhipu's strict
    /// `json_schema` response format.
    ///
    /// GLM-4.7 (and later) and the GLM-5 family accept the full
    /// `{ "type": "json_schema", "json_schema": { ... } }` payload. Older
    /// models only accept `{ "type": "json_object" }` and rely on the
    /// system prompt to coerce the JSON shape. Operators can also force
    /// the choice via `LlmConfig::extra["strict_json_schema"]` (boolean).
    fn supports_strict_json_schema(&self) -> bool {
        if let Some(override_value) = self.config.extra.get("strict_json_schema")
            && let Some(flag) = override_value.as_bool()
        {
            return flag;
        }
        let model = self.config.model.to_ascii_lowercase();
        model.starts_with("glm-4.7")
            || model.starts_with("glm-4.8")
            || model.starts_with("glm-4.9")
            || model.starts_with("glm-5")
            || model.starts_with("glm-6")
    }

    /// Builds the JSON body sent to the Zhipu chat-completions endpoint.
    ///
    /// The body shape is OpenAI-compatible. `response_format` is selected
    /// based on [`Self::supports_strict_json_schema`]. When `stream` is
    /// `true`, `stream` is set on the body and `tool_stream` is enabled
    /// for the GLM-5 family (Zhipu's documented flag for streaming tool
    /// calls). Function calling is not used in this codebase, but the
    /// flag is wired through so callers can opt in via the model name.
    fn build_request_body(
        &self,
        question: &str,
        system_prompt: &str,
        stream: bool,
        temperature: Option<f32>,
    ) -> Value {
        let response_format = if self.supports_strict_json_schema() {
            json!({
                "type": "json_schema",
                "json_schema": {
                    "name": "QueryPlan",
                    "strict": true,
                    "schema": compact_query_plan_schema(),
                },
            })
        } else {
            json!({"type": "json_object"})
        };
        let model = self.config.model.to_ascii_lowercase();
        let supports_tool_stream = model.starts_with("glm-5") || model.starts_with("glm-6");
        let mut body = json!({
            "model": self.config.model,
            "messages": [
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": question},
            ],
            "temperature": temperature.unwrap_or(self.config.temperature),
            "max_tokens": self.effective_max_tokens(),
            "response_format": response_format,
        });
        if stream {
            body["stream"] = Value::Bool(true);
            if supports_tool_stream {
                body["tool_stream"] = Value::Bool(true);
            }
        }
        body
    }
}

#[async_trait]
impl RetryableHttpClient for ZhipuClient {
    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 {
        "zhipu"
    }

    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 ZhipuClient {
    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::Zhipu
    }

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

/// Parses a Zhipu chat-completions JSON response into a [`QueryPlan`](vlorql_core::schema::QueryPlan).
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!("Zhipu response is not valid JSON: {error}"),
            },
            json!({
                "source": "zhipu_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("zhipu returned an error")
                    .to_owned(),
            },
            json!({"source": "zhipu_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: "Zhipu response did not contain choices[0].message.content".to_owned(),
                },
                json!({"source": "zhipu_response"}),
            )
        })?;
    crate::parse_llm_response(content).map_err(|error| {
        VlorQLError::llm(
            LlmErrorKind::ParseError {
                details: format!("assistant content is not a valid QueryPlan: {error}"),
            },
            json!({
                "source": "zhipu_content",
                "content": truncate(content, 4096),
            }),
        )
    })
}

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

    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 zhipu_config(model: &str) -> LlmConfig {
        LlmConfig {
            provider: LlmProvider::Zhipu,
            api_key: Some("test-key".to_owned()),
            api_base: Some("http://127.0.0.1:0/v4/chat/completions".to_owned()),
            model: model.to_owned(),
            max_tokens: 1024,
            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": "glm-4.7",
            "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 zhipu_client_uses_strict_json_schema_for_glm_4_7() {
        let mut server = Server::new_async().await;
        let expected = plan();
        // Note: mockito's regex matcher parses `\{` as a literal `\{` (the
        // regex crate does not collapse the escape), so the body matcher
        // intentionally omits the brace and relies on the surrounding
        // JSON keys instead. The companion assertions below verify the
        // brace-shaped payload directly.
        let mock = server
            .mock("POST", "/v4/chat/completions")
            .match_body(Matcher::Regex(
                r#""model":"glm-4\.7".*"name":"QueryPlan".*"strict":true"#.to_owned(),
            ))
            .with_status(200)
            .with_body(chat_response(&expected))
            .create_async()
            .await;

        let config = LlmConfig {
            api_base: Some(format!("{}/v4/chat/completions", server.url())),
            ..zhipu_config("glm-4.7")
        };
        let client = ZhipuClient::new(config).expect("client should build");
        let request_body = client.build_request_body("show users", "system", false, None);
        assert_eq!(request_body["model"], "glm-4.7");
        assert_eq!(request_body["temperature"], 0.0);
        assert_eq!(request_body["response_format"]["type"], "json_schema");
        assert_eq!(
            request_body["response_format"]["json_schema"]["name"],
            "QueryPlan"
        );
        assert_eq!(
            request_body["response_format"]["json_schema"]["strict"],
            true
        );

        let (actual, _usage) = client
            .generate_plan("show users", "system", None)
            .await
            .expect("zhipu plan should parse");
        assert_eq!(actual, expected);
        assert_eq!(client.provider(), LlmProvider::Zhipu);
        let config_ref = client.config();
        assert_eq!(config_ref.model, "glm-4.7");
        mock.assert_async().await;
    }

    #[tokio::test]
    async fn zhipu_client_falls_back_to_json_object_for_older_models() {
        let mut server = Server::new_async().await;
        let expected = plan();
        // The matcher deliberately avoids `\{` because the regex crate
        // matches that as a literal two-character sequence rather than
        // a single `{`. Key-only matching is sufficient for the
        // contract this test exercises.
        let mock = server
            .mock("POST", "/v4/chat/completions")
            .match_body(Matcher::Regex(
                r#""model":"glm-4".*"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!("{}/v4/chat/completions", server.url())),
            ..zhipu_config("glm-4")
        };
        let client = ZhipuClient::new(config).expect("client should build");
        let request_body = client.build_request_body("q", "s", false, None);
        assert_eq!(request_body["model"], "glm-4");
        assert_eq!(request_body["response_format"]["type"], "json_object");

        let (actual, _usage) = client
            .generate_plan("q", "s", None)
            .await
            .expect("response");
        assert_eq!(actual, expected);
        mock.assert_async().await;
    }

    #[tokio::test]
    async fn zhipu_client_converts_error_response() {
        let mut server = Server::new_async().await;
        let body = json!({
            "error": {"code": "invalid_api_key", "message": "bad key"}
        })
        .to_string();
        let mock = server
            .mock("POST", "/v4/chat/completions")
            .with_status(401)
            .with_body(body)
            .create_async()
            .await;

        let config = LlmConfig {
            api_base: Some(format!("{}/v4/chat/completions", server.url())),
            ..zhipu_config("glm-4.7")
        };
        let client = ZhipuClient::new(config).expect("client should build");
        let error = client
            .generate_plan("hi", "system", None)
            .await
            .expect_err("401 should be reported");
        assert_eq!(error.error_code(), "L001");
        mock.assert_async().await;
    }

    #[tokio::test]
    async fn zhipu_client_converts_invalid_plan_to_llm_parse_error() {
        let mut server = Server::new_async().await;
        let body = json!({
            "choices": [{"message": {"role": "assistant", "content": r#"{"unexpected":true}"#}}]
        })
        .to_string();
        let mock = server
            .mock("POST", "/v4/chat/completions")
            .with_status(200)
            .with_body(body)
            .create_async()
            .await;
        let config = LlmConfig {
            api_base: Some(format!("{}/v4/chat/completions", server.url())),
            ..zhipu_config("glm-4.7")
        };
        let client = ZhipuClient::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 zhipu_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", "/v4/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!("{}/v4/chat/completions", server.url())),
            ..zhipu_config("glm-4.7")
        };
        let client = ZhipuClient::new(config).expect("client should build");
        let body = client.build_request_body("hi", "system", true, None);
        assert_eq!(body["stream"], true);

        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 zhipu_client_stream_propagates_http_error() {
        let mut server = Server::new_async().await;
        let mock = server
            .mock("POST", "/v4/chat/completions")
            .with_status(500)
            .with_body(r#"{"error":{"message":"down"}}"#)
            .create_async()
            .await;
        let config = LlmConfig {
            api_base: Some(format!("{}/v4/chat/completions", server.url())),
            ..zhipu_config("glm-4.7")
        };
        let client = ZhipuClient::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;
    }

    #[test]
    fn zhipu_client_requires_api_key() {
        // Save and clear any pre-existing ZHIPU_API_KEY so the test is
        // deterministic regardless of host environment or sibling tests
        // that mutate the variable.
        let key_backup = std::env::var(ZHIPU_API_KEY_ENV).ok();
        // SAFETY: tests in this module share a single process; we
        // restore the previous value before returning so other tests
        // see the original environment.
        unsafe { std::env::remove_var(ZHIPU_API_KEY_ENV) };
        let mut config = zhipu_config("glm-4.7");
        config.api_key = None;
        config.api_base = None;
        let error = match ZhipuClient::new(config) {
            Ok(client) => {
                if let Some(previous) = key_backup {
                    unsafe { std::env::set_var(ZHIPU_API_KEY_ENV, previous) };
                }
                panic!("missing api key should fail; got client {client:?}");
            }
            Err(error) => {
                if let Some(previous) = key_backup {
                    unsafe { std::env::set_var(ZHIPU_API_KEY_ENV, previous) };
                }
                error
            }
        };
        assert_eq!(error.error_code(), "G004");
    }

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

        let key_backup = std::env::var(ZHIPU_API_KEY_ENV).ok();
        // SAFETY: tests in this module run on a single process; we
        // restore the previous value via the `_guard` drop handle below
        // even on panic.
        struct RestoreEnv(Option<String>);
        impl Drop for RestoreEnv {
            fn drop(&mut self) {
                // SAFETY: see comment above.
                unsafe {
                    match self.0.take() {
                        Some(previous) => std::env::set_var(ZHIPU_API_KEY_ENV, previous),
                        None => std::env::remove_var(ZHIPU_API_KEY_ENV),
                    }
                }
            }
        }
        let _guard = RestoreEnv(key_backup.clone());
        unsafe {
            std::env::set_var(ZHIPU_API_KEY_ENV, "env-key");
        }
        let mut config = zhipu_config("glm-4.7");
        config.api_key = None;
        config.api_base = Some(format!("{}/v4/chat/completions", server.url()));
        let client = ZhipuClient::new(config).expect("client should build from env var");
        let (actual, _usage) = client
            .generate_plan("q", "s", None)
            .await
            .expect("env-keyed request should succeed");
        assert_eq!(actual, expected);
        mock.assert_async().await;
    }

    #[test]
    fn zhipu_client_effective_max_tokens_floors_low_values() {
        let mut config = zhipu_config("glm-4.7");
        config.max_tokens = 0;
        config.api_base = None;
        let client = ZhipuClient::new(config).expect("client should build");
        assert_eq!(client.effective_max_tokens(), DEFAULT_MAX_TOKENS);

        let mut config = zhipu_config("glm-4.7");
        config.max_tokens = 64;
        config.api_base = None;
        let client = ZhipuClient::new(config).expect("client should build");
        assert_eq!(client.effective_max_tokens(), MIN_MAX_TOKENS);
    }

    #[test]
    fn zhipu_client_endpoint_uses_default_when_unset() {
        let mut config = zhipu_config("glm-4.7");
        config.api_base = None;
        let client = ZhipuClient::new(config).expect("client should build");
        assert_eq!(client.endpoint(), DEFAULT_API_BASE);
    }

    #[test]
    fn zhipu_client_supports_strict_json_schema_detection() {
        let mut config = zhipu_config("glm-3-turbo");
        config.api_base = None;
        let client = ZhipuClient::new(config).expect("client should build");
        assert!(!client.supports_strict_json_schema());

        let mut config = zhipu_config("glm-4");
        config.api_base = None;
        let client = ZhipuClient::new(config).expect("client should build");
        assert!(!client.supports_strict_json_schema());

        let mut config = zhipu_config("glm-4.7");
        config.api_base = None;
        let client = ZhipuClient::new(config).expect("client should build");
        assert!(client.supports_strict_json_schema());

        let mut config = zhipu_config("glm-5-air");
        config.api_base = None;
        let client = ZhipuClient::new(config).expect("client should build");
        assert!(client.supports_strict_json_schema());

        let mut config = zhipu_config("glm-4.6");
        config.api_base = None;
        config
            .extra
            .insert("strict_json_schema".to_owned(), Value::Bool(true));
        let client = ZhipuClient::new(config).expect("client should build");
        assert!(client.supports_strict_json_schema());

        let mut config = zhipu_config("glm-4.7");
        config.api_base = None;
        config
            .extra
            .insert("strict_json_schema".to_owned(), Value::Bool(false));
        let client = ZhipuClient::new(config).expect("client should build");
        assert!(!client.supports_strict_json_schema());
    }

    #[test]
    fn zhipu_query_plan_schema_round_trips_through_parse() {
        // Sanity check: the schema we send to Zhipu must serialise to
        // valid JSON (Zhipu rejects malformed JSON Schema payloads).
        let value = compact_query_plan_schema();
        let serialized = serde_json::to_string(&value).expect("schema should serialize");
        let _: Value = serde_json::from_str(&serialized).expect("schema should parse");
    }
}