ante-llm 0.4.2

Streaming LLM client for Anthropic, OpenAI, Gemini and Chat Completions servers, from the Ante coding agent
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
// Copyright 2026 Antigma Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use crate::effort;
use ante_protocol_shape::Effort;
use serde::Serialize;
use serde_json::{Map, Value};
use std::borrow::Cow;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OpenAiCompatProfile {
    thinking_dialect: ThinkingDialect,
    /// The levels the model takes when it declares none.
    default_levels: &'static [Effort],
    llama_cpp: bool,
    system_role: SystemRolePolicy,
    search: SearchPolicy,
    requires_assistant_reasoning: bool,
}

/// How a model's wire spells an effort level. Which levels a model takes is
/// not part of it: every dialect spells any level it is given.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ThinkingDialect {
    /// `reasoning_effort` carries each level under its own name. `min` goes
    /// as `none` where that turns reasoning off, and as `minimal` where that
    /// is the model's lowest level.
    ReasoningEffort { min: ReasoningEffort },
    /// GLM 5.3 always reasons, at `max` when no effort is set. Its own API
    /// also takes the thinking object.
    Glm53 { native_thinking: bool },
    /// Qwen 3.8 takes effort names and keeps `enable_thinking: false` as its
    /// off switch.
    Qwen38,
    /// A `thinking` object, on unless `min`.
    ThinkingObject,
    /// Kimi K2.x only takes an explicit "disabled" object; on is the default.
    KimiThinkingObject,
    /// `enable_thinking`, on unless `min`.
    QwenEnableThinking,
    /// A `thinking` object beside the effort. Only `high` and the route's top
    /// value are known-good, so the middle of the scale sends `high`, and
    /// below it the effort is left to the server.
    DeepSeek { max_reasoning_effort: ReasoningEffort },
}

/// Every level under its own name, `min` as `minimal`.
const BY_NAME: ThinkingDialect = ThinkingDialect::ReasoningEffort { min: ReasoningEffort::Minimal };

/// As [`BY_NAME`], with `min` as `none`: reasoning off.
const BY_NAME_WITH_OFF: ThinkingDialect =
    ThinkingDialect::ReasoningEffort { min: ReasoningEffort::None };

impl ThinkingDialect {
    fn spell(self, level: Effort) -> ThinkingParams {
        let on = level != Effort::Min;
        let named = reasoning_effort_ident(level);
        let (reasoning_effort, thinking, enable_thinking) = match self {
            Self::ReasoningEffort { min } => (Some(if on { named } else { min }), None, None),
            Self::Glm53 { native_thinking } => (Some(named), native_thinking.then_some(true), None),
            Self::Qwen38 if on => (Some(named), None, None),
            Self::Qwen38 => (None, None, Some(false)),
            Self::ThinkingObject => (None, Some(on), None),
            Self::KimiThinkingObject => (None, (!on).then_some(false), None),
            Self::QwenEnableThinking => (None, None, Some(on)),
            Self::DeepSeek { max_reasoning_effort } => {
                let reasoning_effort = match level {
                    Effort::Min | Effort::Low => None,
                    Effort::Medium | Effort::High | Effort::XHigh => Some(ReasoningEffort::High),
                    Effort::Max => Some(max_reasoning_effort),
                };
                (reasoning_effort, Some(on), None)
            }
        };
        ThinkingParams {
            reasoning_effort,
            thinking: thinking.map(thinking_object),
            enable_thinking,
        }
    }

    /// What a request with no effort set sends: nothing where the field is a
    /// level, so the server's default applies, and "on" where it is a toggle.
    fn unset(self) -> ThinkingParams {
        match self {
            Self::ReasoningEffort { .. } | Self::Qwen38 => ThinkingParams::default(),
            Self::Glm53 { .. } => self.spell(Effort::Max),
            Self::ThinkingObject
            | Self::KimiThinkingObject
            | Self::QwenEnableThinking
            | Self::DeepSeek { .. } => self.spell(Effort::Low),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SystemRolePolicy {
    Separate,
    Merged,
    PrependToFirstUser,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SearchPolicy {
    Unsupported,
    OpenRouterWebSearchTool,
    QwenEnableSearch,
}

#[derive(Debug, Default)]
pub struct ThinkingParams {
    pub reasoning_effort: Option<ReasoningEffort>,
    pub thinking: Option<ThinkingConfig>,
    pub enable_thinking: Option<bool>,
}

#[derive(Debug, Default)]
pub struct SearchParams {
    pub enable_search: Option<bool>,
    pub search_options: Option<SearchOptions>,
    pub enable_thinking: Option<bool>,
    pub extra_body: Map<String, Value>,
}

#[derive(Debug, Serialize)]
pub struct SearchOptions {
    forced_search: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ReasoningEffort {
    None,
    Minimal,
    #[serde(rename = "xhigh")]
    XHigh,
    Low,
    Medium,
    High,
    Max,
}

/// Provider-native thinking configuration.
#[derive(Debug, Serialize)]
pub struct ThinkingConfig {
    #[serde(rename = "type")]
    thinking_type: String,
}

impl ThinkingConfig {
    pub fn thinking_type(&self) -> &str {
        &self.thinking_type
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OpenAiCompatFamily {
    DeepSeek,
    Glm,
    Kimi,
    KimiK3,
    MuseSpark,
    MiniMax,
    Qwen,
    MistralNoSystem,
    /// The `offline` provider. The server applies the model's chat template
    /// itself, so the file name says nothing about the wire.
    LlamaCpp,
    Generic,
}

impl OpenAiCompatProfile {
    pub fn from_model(provider_id: &str, model_id: &str) -> Self {
        let family = OpenAiCompatFamily::from_provider_model(provider_id, model_id);
        let (thinking_dialect, default_levels) = family.thinking(provider_id, model_id);
        Self {
            thinking_dialect,
            default_levels,
            llama_cpp: family == OpenAiCompatFamily::LlamaCpp,
            system_role: family.system_role(),
            search: family.search_policy(provider_id),
            // MiniMax requires replaying reasoning alongside tool calls.
            requires_assistant_reasoning: family.requires_assistant_reasoning()
                || provider_id == "minimax",
        }
    }

    /// What to send for `requested` on a model that declares the `declared`
    /// levels, or none. A request between two levels rounds down to the lower
    /// one, and one below them all takes the lowest. The provider client has
    /// already normalized `declared`.
    pub fn thinking_params(
        self,
        declared: Option<&[Effort]>,
        requested: Option<Effort>,
    ) -> ThinkingParams {
        let (dialect, levels) = self.thinking(declared);
        match requested.and_then(|requested| effort::resolve_level(&levels, requested)) {
            Some(level) => dialect.spell(level),
            None => dialect.unset(),
        }
    }

    /// The dialect and levels of a model that declares `declared`. Declared
    /// levels replace the family's own and go out under their own names.
    fn thinking(self, declared: Option<&[Effort]>) -> (ThinkingDialect, Cow<'_, [Effort]>) {
        let Some(declared) = declared else {
            return (self.thinking_dialect, Cow::Borrowed(self.default_levels));
        };
        // llama.cpp turns thinking off on `none`, so levels that do not
        // themselves start at `min` (`minimal`) get `min` under them for that.
        if self.llama_cpp && declared.first().is_some_and(|lowest| *lowest != Effort::Min) {
            (BY_NAME_WITH_OFF, Cow::Owned([&[Effort::Min], declared].concat()))
        } else {
            (BY_NAME, Cow::Borrowed(declared))
        }
    }

    pub fn search_params(self) -> SearchParams {
        match self.search {
            SearchPolicy::OpenRouterWebSearchTool => SearchParams {
                extra_body: openrouter_web_search_extra_body(),
                ..Default::default()
            },
            SearchPolicy::QwenEnableSearch => SearchParams {
                enable_search: Some(true),
                search_options: Some(SearchOptions { forced_search: true }),
                enable_thinking: Some(false),
                ..Default::default()
            },
            SearchPolicy::Unsupported => SearchParams::default(),
        }
    }

    pub fn supports_search(self) -> bool {
        !matches!(self.search, SearchPolicy::Unsupported)
    }

    pub fn supports_system_role(self) -> bool {
        !matches!(self.system_role, SystemRolePolicy::PrependToFirstUser)
    }

    pub fn merges_system_messages(self) -> bool {
        matches!(self.system_role, SystemRolePolicy::Merged)
    }

    pub fn requires_assistant_reasoning(self) -> bool {
        self.requires_assistant_reasoning
    }
}

impl OpenAiCompatFamily {
    /// The dialect a model of this family speaks, and the levels it takes
    /// when it declares none.
    fn thinking(self, provider_id: &str, model_id: &str) -> (ThinkingDialect, &'static [Effort]) {
        use Effort::{High, Low, Max, Medium, Min, XHigh};

        // The two positions of a toggle.
        const ON_OFF: &[Effort] = &[Min, Low];

        let openrouter = provider_id.eq_ignore_ascii_case("openrouter");
        // Inkling takes both `none` and `minimal` on OpenRouter, and `max`
        // as its top level. `min` asks for the lower of the two.
        if openrouter && model_id == "thinkingmachines/inkling-2-mini" {
            return (BY_NAME_WITH_OFF, &[Min, Low, Medium, High, Max]);
        }
        match self {
            Self::DeepSeek => (
                ThinkingDialect::DeepSeek {
                    max_reasoning_effort: deepseek_max_reasoning_effort(provider_id, model_id),
                },
                &[Min, Medium, Max],
            ),
            Self::Glm if has_model_version(model_id, "glm-5.3") => {
                (ThinkingDialect::Glm53 { native_thinking: !openrouter }, &[Low, High, Max])
            }
            // OpenRouter gives the older GLM models its own effort names,
            // `none` through `xhigh`.
            Self::Glm if openrouter => (BY_NAME_WITH_OFF, &[Min, Low, Medium, High, XHigh]),
            Self::Glm => (ThinkingDialect::ThinkingObject, ON_OFF),
            Self::Kimi => (ThinkingDialect::KimiThinkingObject, ON_OFF),
            // Kimi K3 always reasons and takes only `max`.
            Self::KimiK3 => (BY_NAME, &[Max]),
            // Muse Spark always reasons; `minimal` is its lowest level.
            Self::MuseSpark => (BY_NAME, &[Min, Low, Medium, High, XHigh]),
            Self::Qwen if has_model_version(model_id, "qwen3.8") => {
                (ThinkingDialect::Qwen38, &[Min, Low, Medium, XHigh])
            }
            Self::Qwen => (ThinkingDialect::QwenEnableThinking, ON_OFF),
            // Nothing is sent unless the model declares its levels. A
            // llama.cpp server's are the ones its chat template reports.
            Self::MiniMax | Self::LlamaCpp => (BY_NAME, &[]),
            // Unknown servers commonly reject values above `high`. There is
            // no `min`: no value turns reasoning off on every such server, and
            // leaving the field out lets the provider pick a default above
            // `low`.
            Self::MistralNoSystem | Self::Generic => (BY_NAME, &[Low, Medium, High]),
        }
    }

    fn system_role(self) -> SystemRolePolicy {
        match self {
            // Unknown OpenAI-compatible models may use strict local chat
            // templates that only accept one leading system message. Merge by
            // default; keep separate messages only for families known to
            // support them. llama.cpp folds the one message into the first
            // user turn itself when a template takes no system role.
            Self::MiniMax | Self::Qwen | Self::LlamaCpp | Self::Generic => SystemRolePolicy::Merged,
            Self::MistralNoSystem => SystemRolePolicy::PrependToFirstUser,
            Self::DeepSeek | Self::Glm | Self::Kimi | Self::KimiK3 | Self::MuseSpark => {
                SystemRolePolicy::Separate
            }
        }
    }

    fn search_policy(self, provider_id: &str) -> SearchPolicy {
        if provider_id.eq_ignore_ascii_case("openrouter") {
            return SearchPolicy::OpenRouterWebSearchTool;
        }

        match self {
            Self::Qwen => SearchPolicy::QwenEnableSearch,
            Self::DeepSeek
            | Self::Glm
            | Self::Kimi
            | Self::KimiK3
            | Self::MuseSpark
            | Self::MiniMax
            | Self::MistralNoSystem
            | Self::LlamaCpp
            | Self::Generic => SearchPolicy::Unsupported,
        }
    }

    fn requires_assistant_reasoning(self) -> bool {
        matches!(self, Self::DeepSeek)
    }

    fn from_provider_model(provider_id: &str, model_id: &str) -> Self {
        let provider = provider_id.to_ascii_lowercase();
        if provider == "deepseek" {
            return Self::DeepSeek;
        }
        if provider == "zai" {
            return Self::Glm;
        }
        if provider == "offline" {
            return Self::LlamaCpp;
        }

        let model = model_id.to_ascii_lowercase();
        let (owner, name) = model.split_once('/').unwrap_or(("", model.as_str()));

        if owner == "deepseek" || starts_with_family_token(name, "deepseek") {
            return Self::DeepSeek;
        }
        if owner == "qwen" || starts_with_family_token(name, "qwen") {
            return Self::Qwen;
        }
        if starts_with_family_token(name, "glm") {
            return Self::Glm;
        }
        if starts_with_family_token(name, "kimi-k3") {
            return Self::KimiK3;
        }
        if owner == "meta" && starts_with_family_token(name, "muse-spark") {
            return Self::MuseSpark;
        }
        if starts_with_family_token(name, "kimi") {
            return Self::Kimi;
        }
        if owner == "minimax" || starts_with_family_token(name, "minimax") {
            return Self::MiniMax;
        }
        if owner == "mistralai"
            || starts_with_family_token(name, "mistral")
            || starts_with_family_token(name, "devstral")
            || starts_with_family_token(name, "ministral")
        {
            return Self::MistralNoSystem;
        }

        Self::Generic
    }
}

fn openrouter_web_search_extra_body() -> Map<String, Value> {
    let mut body = Map::new();
    body.insert("tools".to_string(), serde_json::json!([{ "type": "openrouter:web_search" }]));
    body
}

fn thinking_object(on: bool) -> ThinkingConfig {
    let thinking_type = if on { "enabled" } else { "disabled" };
    ThinkingConfig { thinking_type: thinking_type.to_string() }
}

fn deepseek_max_reasoning_effort(provider_id: &str, model_id: &str) -> ReasoningEffort {
    // OpenRouter's April preview accepted `xhigh`; Pro 0813 and V4.1 Flash
    // advertise DeepSeek's native `max` spelling.
    if provider_id.eq_ignore_ascii_case("openrouter")
        && !model_id.eq_ignore_ascii_case("deepseek/deepseek-v4-pro-0813")
        && !model_id.eq_ignore_ascii_case("deepseek/deepseek-v4.1-flash-1017")
    {
        ReasoningEffort::XHigh
    } else {
        ReasoningEffort::Max
    }
}

/// The same-named wire value for each internal level (`min` is spelled
/// `minimal` on the wire).
fn reasoning_effort_ident(level: Effort) -> ReasoningEffort {
    match level {
        Effort::Min => ReasoningEffort::Minimal,
        Effort::Low => ReasoningEffort::Low,
        Effort::Medium => ReasoningEffort::Medium,
        Effort::High => ReasoningEffort::High,
        Effort::XHigh => ReasoningEffort::XHigh,
        Effort::Max => ReasoningEffort::Max,
    }
}

/// The distinct effort levels a compat provider+model exposes, for the UI:
/// the ladder of its `declared` levels when it has them, else its family's.
pub fn effort_levels(
    provider_id: &str,
    model_id: &str,
    declared: Option<&[Effort]>,
) -> Vec<Effort> {
    OpenAiCompatProfile::from_model(provider_id, model_id).thinking(declared).1.into_owned()
}

fn has_model_version(model_id: &str, version: &str) -> bool {
    let model = model_id.to_ascii_lowercase();
    let name = model.split_once('/').map_or(model.as_str(), |(_, name)| name);
    let Some(rest) = name.strip_prefix(version) else {
        return false;
    };
    rest.is_empty() || rest.chars().next().is_some_and(|c| matches!(c, '-' | '_' | ':' | '.'))
}

fn starts_with_family_token(name: &str, family: &str) -> bool {
    let Some(rest) = name.strip_prefix(family) else {
        return false;
    };
    rest.is_empty()
        || rest
            .chars()
            .next()
            .is_some_and(|c| matches!(c, '-' | '_' | ':' | '.') || c.is_ascii_digit())
}

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

    fn profile(provider_id: &str, model_id: &str) -> OpenAiCompatProfile {
        OpenAiCompatProfile::from_model(provider_id, model_id)
    }

    #[test]
    fn explicit_family_profiles_drive_wire_policy() {
        let deepseek = profile("openrouter", "deepseek/deepseek-v4-pro");
        assert_eq!(
            deepseek.thinking_dialect,
            ThinkingDialect::DeepSeek { max_reasoning_effort: ReasoningEffort::XHigh }
        );
        assert_eq!(deepseek.system_role, SystemRolePolicy::Separate);
        assert!(deepseek.requires_assistant_reasoning);

        let deepseek_ga = profile("openrouter", "deepseek/deepseek-v4-pro-0813");
        assert_eq!(
            deepseek_ga.thinking_dialect,
            ThinkingDialect::DeepSeek { max_reasoning_effort: ReasoningEffort::Max }
        );

        let qwen = profile("openai-compatible", "qwen3.7-max");
        assert_eq!(qwen.thinking_dialect, ThinkingDialect::QwenEnableThinking);
        assert_eq!(qwen.system_role, SystemRolePolicy::Merged);
        assert_eq!(qwen.search, SearchPolicy::QwenEnableSearch);

        let qwen38 = profile("openai-compatible", "Qwen3.8-27B-MLX");
        assert_eq!(qwen38.thinking_dialect, ThinkingDialect::Qwen38);
        assert_eq!(qwen38.system_role, SystemRolePolicy::Merged);
        assert_eq!(qwen38.search, SearchPolicy::QwenEnableSearch);

        let minimax = profile("openrouter", "minimax/minimax-m3");
        assert!(minimax.default_levels.is_empty());
        assert_eq!(minimax.system_role, SystemRolePolicy::Merged);

        let openrouter_glm = profile("openrouter", "z-ai/glm-5.2");
        assert_eq!(openrouter_glm.thinking_dialect, BY_NAME_WITH_OFF);

        let direct_glm_53 = profile("zai", "glm-5.3");
        assert_eq!(
            direct_glm_53.thinking_dialect,
            ThinkingDialect::Glm53 { native_thinking: true }
        );

        let openrouter_glm_53 = profile("openrouter", "z-ai/glm-5.3");
        assert_eq!(
            openrouter_glm_53.thinking_dialect,
            ThinkingDialect::Glm53 { native_thinking: false }
        );

        let kimi = profile("openai-compatible", "moonshotai/kimi-k2.6");
        assert_eq!(kimi.thinking_dialect, ThinkingDialect::KimiThinkingObject);

        let kimi_k3 = profile("openrouter", "moonshotai/kimi-k3");
        assert_eq!(kimi_k3.thinking_dialect, BY_NAME);

        let muse_spark = profile("openrouter", "meta/muse-spark-1.3");
        assert_eq!(muse_spark.thinking_dialect, BY_NAME);

        let mistral = profile("openrouter", "mistralai/devstral-small");
        assert_eq!(mistral.system_role, SystemRolePolicy::PrependToFirstUser);
        assert_eq!(mistral.search, SearchPolicy::OpenRouterWebSearchTool);

        let generic =
            profile("openai-compatible", "gbuzhf/KAT-Coder-V2.5-Dev-APEX-MTP-GGUF:I-Mini");
        assert_eq!(generic.system_role, SystemRolePolicy::Merged);
    }

    #[test]
    fn openrouter_search_params_use_server_tool_extra_body() {
        let search = profile("openrouter", "deepseek/deepseek-v4-pro").search_params();

        assert!(search.enable_search.is_none());
        assert!(search.search_options.is_none());
        assert_eq!(
            search.extra_body.get("tools"),
            Some(&serde_json::json!([{ "type": "openrouter:web_search" }]))
        );
    }

    #[test]
    fn profile_detection_does_not_match_arbitrary_substrings() {
        assert_eq!(
            OpenAiCompatFamily::from_provider_model("openai-compatible", "notqwen-model"),
            OpenAiCompatFamily::Generic
        );
        assert_eq!(
            OpenAiCompatFamily::from_provider_model("openai-compatible", "made-by-deepseek-ish"),
            OpenAiCompatFamily::Generic
        );
        assert_eq!(
            profile("openai-compatible", "qwen3.80-max").thinking_dialect,
            ThinkingDialect::QwenEnableThinking
        );
    }

    #[test]
    fn thinking_params_preserve_existing_dialects() {
        let qwen =
            profile("openai-compatible", "qwen3.7-max").thinking_params(None, Some(Effort::Min));
        assert_eq!(qwen.enable_thinking, Some(false));
        assert!(qwen.reasoning_effort.is_none());

        // Unset effort defaults to on.
        let qwen_unset = profile("openai-compatible", "qwen3.7-max").thinking_params(None, None);
        assert_eq!(qwen_unset.enable_thinking, Some(true));

        let deepseek =
            profile("deepseek", "deepseek-flash").thinking_params(None, Some(Effort::Max));
        assert!(matches!(deepseek.reasoning_effort, Some(ReasoningEffort::Max)));
        assert_eq!(deepseek.thinking.unwrap().thinking_type, "enabled");

        let openrouter_deepseek = profile("openrouter", "deepseek/deepseek-v4-pro")
            .thinking_params(None, Some(Effort::Max));
        assert!(matches!(openrouter_deepseek.reasoning_effort, Some(ReasoningEffort::XHigh)));
        assert_eq!(openrouter_deepseek.thinking.unwrap().thinking_type, "enabled");

        let openrouter_deepseek_ga = profile("openrouter", "deepseek/deepseek-v4-pro-0813")
            .thinking_params(None, Some(Effort::Max));
        assert!(matches!(openrouter_deepseek_ga.reasoning_effort, Some(ReasoningEffort::Max)));
        assert_eq!(openrouter_deepseek_ga.thinking.unwrap().thinking_type, "enabled");

        let flash = profile("openrouter", "deepseek/deepseek-v4.1-flash-1017")
            .thinking_params(None, Some(Effort::Max));
        assert_eq!(flash.reasoning_effort, Some(ReasoningEffort::Max));
        assert_eq!(flash.thinking.unwrap().thinking_type, "enabled");

        // The middle of the DeepSeek scale rides on "high", its known-good level.
        let deepseek_mid =
            profile("deepseek", "deepseek-v4-pro").thinking_params(None, Some(Effort::High));
        assert!(matches!(deepseek_mid.reasoning_effort, Some(ReasoningEffort::High)));

        let openrouter_glm =
            profile("openrouter", "z-ai/glm-5.2").thinking_params(None, Some(Effort::Max));
        assert!(matches!(openrouter_glm.reasoning_effort, Some(ReasoningEffort::XHigh)));
        assert!(openrouter_glm.thinking.is_none());

        let kimi = profile("openai-compatible", "moonshotai/kimi-k2.6")
            .thinking_params(None, Some(Effort::Medium));
        assert!(kimi.thinking.is_none());

        let kimi_disabled = profile("openai-compatible", "moonshotai/kimi-k2.6")
            .thinking_params(None, Some(Effort::Min));
        assert_eq!(kimi_disabled.thinking.unwrap().thinking_type, "disabled");

        let kimi_k3 =
            profile("openrouter", "moonshotai/kimi-k3").thinking_params(None, Some(Effort::Min));
        assert_eq!(kimi_k3.reasoning_effort, Some(ReasoningEffort::Max));
        assert!(kimi_k3.thinking.is_none());

        let kimi_k3_unset = profile("openrouter", "moonshotai/kimi-k3").thinking_params(None, None);
        assert!(kimi_k3_unset.reasoning_effort.is_none());
    }

    #[test]
    fn generic_reasoning_effort_maps_levels_by_name_capped_at_high() {
        let cases = [
            // No portable off switch: the least a generic model has is `low`.
            (Effort::Min, ReasoningEffort::Low),
            (Effort::Low, ReasoningEffort::Low),
            (Effort::Medium, ReasoningEffort::Medium),
            (Effort::High, ReasoningEffort::High),
            (Effort::XHigh, ReasoningEffort::High),
            (Effort::Max, ReasoningEffort::High),
        ];
        for (requested, expected) in cases {
            let params =
                profile("openai-compatible", "gpt-oss").thinking_params(None, Some(requested));
            assert_eq!(params.reasoning_effort, Some(expected), "generic {requested}");
        }
        assert!(
            profile("openai-compatible", "gpt-oss")
                .thinking_params(None, None)
                .reasoning_effort
                .is_none()
        );
    }

    #[test]
    fn qwen38_maps_graded_reasoning_effort_and_preserves_explicit_off() {
        let cases = [
            (Effort::Min, None, Some(false)),
            (Effort::Low, Some(ReasoningEffort::Low), None),
            (Effort::Medium, Some(ReasoningEffort::Medium), None),
            (Effort::High, Some(ReasoningEffort::Medium), None),
            (Effort::XHigh, Some(ReasoningEffort::XHigh), None),
            (Effort::Max, Some(ReasoningEffort::XHigh), None),
        ];
        for (requested, reasoning_effort, enable_thinking) in cases {
            let params = profile("openai-compatible", "Qwen3.8-27B-MLX")
                .thinking_params(None, Some(requested));
            assert_eq!(params.reasoning_effort, reasoning_effort, "Qwen 3.8 {requested}");
            assert_eq!(params.enable_thinking, enable_thinking, "Qwen 3.8 {requested}");
        }

        let unset = profile("openai-compatible", "Qwen3.8-27B-MLX").thinking_params(None, None);
        assert!(unset.reasoning_effort.is_none());
        assert!(unset.enable_thinking.is_none());

        let openrouter =
            profile("openrouter", "qwen/qwen3.8-max").thinking_params(None, Some(Effort::Low));
        assert_eq!(openrouter.reasoning_effort, Some(ReasoningEffort::Low));
        assert!(openrouter.enable_thinking.is_none());
    }

    /// Golden table for the OpenRouter dialect: `min` sends an explicit
    /// "none", an unset effort omits the field.
    #[test]
    fn openrouter_dialect_maps_the_full_scale() {
        let cases = [
            (Effort::Min, ReasoningEffort::None),
            (Effort::Low, ReasoningEffort::Low),
            (Effort::Medium, ReasoningEffort::Medium),
            (Effort::High, ReasoningEffort::High),
            (Effort::XHigh, ReasoningEffort::XHigh),
            (Effort::Max, ReasoningEffort::XHigh),
        ];
        for (requested, expected) in cases {
            let params =
                profile("openrouter", "z-ai/glm-5.2").thinking_params(None, Some(requested));
            assert_eq!(params.reasoning_effort, Some(expected), "openrouter {requested}");
        }
        assert!(
            profile("openrouter", "z-ai/glm-5.2")
                .thinking_params(None, None)
                .reasoning_effort
                .is_none()
        );
    }

    #[test]
    fn glm_53_maps_its_mandatory_reasoning_scale() {
        let cases = [
            (Effort::Min, ReasoningEffort::Low),
            (Effort::Low, ReasoningEffort::Low),
            (Effort::Medium, ReasoningEffort::Low),
            (Effort::High, ReasoningEffort::High),
            (Effort::XHigh, ReasoningEffort::High),
            (Effort::Max, ReasoningEffort::Max),
        ];
        for (requested, expected) in cases {
            let direct = profile("zai", "glm-5.3").thinking_params(None, Some(requested));
            assert_eq!(direct.reasoning_effort, Some(expected), "direct GLM 5.3 {requested}");
            assert_eq!(direct.thinking.unwrap().thinking_type(), "enabled");

            let openrouter =
                profile("openrouter", "z-ai/glm-5.3").thinking_params(None, Some(requested));
            assert_eq!(
                openrouter.reasoning_effort,
                Some(expected),
                "OpenRouter GLM 5.3 {requested}"
            );
            assert!(openrouter.thinking.is_none());
        }

        let direct_unset = profile("zai", "glm-5.3").thinking_params(None, None);
        assert_eq!(direct_unset.reasoning_effort, Some(ReasoningEffort::Max));
        assert_eq!(direct_unset.thinking.unwrap().thinking_type(), "enabled");

        let openrouter_unset = profile("openrouter", "z-ai/glm-5.3").thinking_params(None, None);
        assert_eq!(openrouter_unset.reasoning_effort, Some(ReasoningEffort::Max));
        assert!(openrouter_unset.thinking.is_none());
    }

    #[test]
    fn muse_spark_maps_its_mandatory_reasoning_scale() {
        let cases = [
            (Effort::Min, ReasoningEffort::Minimal),
            (Effort::Low, ReasoningEffort::Low),
            (Effort::Medium, ReasoningEffort::Medium),
            (Effort::High, ReasoningEffort::High),
            (Effort::XHigh, ReasoningEffort::XHigh),
            (Effort::Max, ReasoningEffort::XHigh),
        ];
        for (requested, expected) in cases {
            let params =
                profile("openrouter", "meta/muse-spark-1.3").thinking_params(None, Some(requested));
            assert_eq!(params.reasoning_effort, Some(expected), "Muse Spark {requested}");
        }
    }

    #[test]
    fn effort_levels_match_each_dialect() {
        assert_eq!(
            effort_levels("openai-compatible", "qwen3.7-max", None),
            vec![Effort::Min, Effort::Low],
        );
        assert_eq!(
            effort_levels("openai-compatible", "Qwen3.8-27B-MLX", None),
            vec![Effort::Min, Effort::Low, Effort::Medium, Effort::XHigh],
        );
        assert_eq!(
            effort_levels("deepseek", "deepseek-v4-pro", None),
            vec![Effort::Min, Effort::Medium, Effort::Max],
        );
        assert_eq!(
            effort_levels("openrouter", "z-ai/glm-5.2", None),
            vec![Effort::Min, Effort::Low, Effort::Medium, Effort::High, Effort::XHigh],
        );
        assert_eq!(
            effort_levels("zai", "glm-5.3", None),
            vec![Effort::Low, Effort::High, Effort::Max],
        );
        assert_eq!(
            effort_levels("openrouter", "z-ai/glm-5.3", None),
            vec![Effort::Low, Effort::High, Effort::Max],
        );
        assert_eq!(
            effort_levels("openrouter", "meta/muse-spark-1.3", None),
            vec![Effort::Min, Effort::Low, Effort::Medium, Effort::High, Effort::XHigh],
        );
        assert_eq!(
            effort_levels("openai-compatible", "gpt-oss", None),
            vec![Effort::Low, Effort::Medium, Effort::High],
        );
        assert_eq!(
            effort_levels("openrouter", "thinkingmachines/inkling-2-mini", None),
            [Effort::Min, Effort::Low, Effort::Medium, Effort::High, Effort::Max],
        );
        // MiniMax takes no level unless the model declares them.
        assert!(effort_levels("openrouter", "minimax/minimax-m3", None).is_empty());
    }

    #[test]
    fn supported_effort_params_send_the_same_named_value() {
        let generic = profile("openai-compatible", "gpt-oss");
        let supported_efforts = [Effort::Low, Effort::Medium, Effort::High];
        let params = generic.thinking_params(Some(&supported_efforts), Some(Effort::Medium));
        assert_eq!(params.reasoning_effort, Some(ReasoningEffort::Medium));
        assert!(params.thinking.is_none());
        assert!(params.enable_thinking.is_none());
        assert_eq!(
            generic
                .thinking_params(Some(&[Effort::Min, Effort::High]), Some(Effort::Min))
                .reasoning_effort,
            Some(ReasoningEffort::Minimal),
        );
    }

    /// Declared levels replace the family's dialect as well as its levels: a
    /// DeepSeek model that declares them sends plain effort names, with no
    /// thinking object and nothing when no effort is set.
    #[test]
    fn declared_levels_replace_the_family_dialect() {
        let deepseek = profile("openrouter", "deepseek/deepseek-v4.1-flash-1017");
        let declared = [Effort::Low, Effort::High, Effort::Max];
        for (requested, expected) in [
            (Some(Effort::Min), Some(ReasoningEffort::Low)),
            (Some(Effort::Medium), Some(ReasoningEffort::Low)),
            (Some(Effort::Max), Some(ReasoningEffort::Max)),
            (None, None),
        ] {
            let params = deepseek.thinking_params(Some(&declared), requested);
            assert_eq!(params.reasoning_effort, expected, "{requested:?}");
            assert!(params.thinking.is_none(), "{requested:?}");
        }
    }

    /// `offline` is a llama.cpp server whatever the model file is called: no
    /// family guess, no search, and `min` sent as `none`.
    #[test]
    fn offline_is_llama_cpp_whatever_the_model_is_called() {
        for model in ["Qwen3.8-27B-Q4_K_M", "deepseek-r1-distill", "devstral"] {
            let offline = profile("offline", model);
            assert!(offline.llama_cpp);
            assert_eq!(offline.system_role, SystemRolePolicy::Merged);
            assert_eq!(offline.search, SearchPolicy::Unsupported);
            assert!(!offline.requires_assistant_reasoning);
            assert!(effort_levels("offline", model, None).is_empty());
            assert!(effort_levels("offline", model, Some(&[])).is_empty());

            // Without declared levels nothing is sent.
            let undeclared = offline.thinking_params(None, Some(Effort::High));
            assert!(undeclared.reasoning_effort.is_none());
            assert!(undeclared.thinking.is_none() && undeclared.enable_thinking.is_none());
        }

        // Levels that start above `minimal` get `min` under them, sent as
        // `none`: no thinking.
        let model = "Qwen3.8-27B-Q4_K_M";
        let offline = profile("offline", model);
        let declared = [Effort::Low, Effort::Medium, Effort::XHigh];
        assert_eq!(
            effort_levels("offline", model, Some(&declared)),
            [Effort::Min, Effort::Low, Effort::Medium, Effort::XHigh]
        );
        for (requested, expected) in [
            (Effort::Min, ReasoningEffort::None),
            (Effort::Low, ReasoningEffort::Low),
            (Effort::High, ReasoningEffort::Medium),
            (Effort::Max, ReasoningEffort::XHigh),
        ] {
            let params = offline.thinking_params(Some(&declared), Some(requested));
            assert_eq!(params.reasoning_effort, Some(expected), "llama.cpp {requested}");
        }
        let unset = offline.thinking_params(Some(&declared), None);
        assert!(unset.reasoning_effort.is_none(), "unset leaves the template's default");

        // A template that declares `minimal` is sent it: `none` would fall
        // back to that template's default level.
        let declared = [Effort::Min, Effort::Low, Effort::High];
        assert_eq!(effort_levels("offline", model, Some(&declared)), declared);
        for (requested, expected) in [
            (Effort::Min, ReasoningEffort::Minimal),
            (Effort::Medium, ReasoningEffort::Low),
            (Effort::Max, ReasoningEffort::High),
        ] {
            let params = offline.thinking_params(Some(&declared), Some(requested));
            assert_eq!(params.reasoning_effort, Some(expected), "llama.cpp {requested}");
        }

        // Other compat providers offer the declared levels as they are.
        let declared = [Effort::Low, Effort::High];
        assert_eq!(effort_levels("openai-compatible", "some-model", Some(&declared)), declared);
    }
}