mur_common/llm.rs
1use crate::error::LlmError;
2
3/// Trait for LLM providers (Anthropic, OpenAI, Ollama).
4/// Shared between mur-core and mur-commander.
5///
6/// Edition 2024 supports async fn in traits natively.
7pub trait LlmClient: Send + Sync {
8 /// Text completion
9 fn complete(
10 &self,
11 prompt: &str,
12 system: Option<&str>,
13 ) -> impl Future<Output = Result<String, LlmError>> + Send;
14
15 /// Generate embedding vector
16 fn embed(&self, text: &str) -> impl Future<Output = Result<Vec<f32>, LlmError>> + Send;
17}
18
19use std::future::Future;
20
21/// Default Anthropic API base URL.
22pub const ANTHROPIC_DEFAULT_BASE_URL: &str = "https://api.anthropic.com";
23
24/// Resolve the Anthropic API base URL from `ANTHROPIC_BASE_URL` env, with a
25/// trailing slash stripped. Falls back to `ANTHROPIC_DEFAULT_BASE_URL`.
26///
27/// Honored at every upstream call site so that users can route Anthropic
28/// traffic through Bedrock, Vertex, a corporate egress proxy, an external
29/// auth bridge, or test fixtures without touching code.
30pub fn anthropic_base_url() -> String {
31 let raw = std::env::var("ANTHROPIC_BASE_URL")
32 .unwrap_or_else(|_| ANTHROPIC_DEFAULT_BASE_URL.to_string());
33 raw.trim_end_matches('/').to_string()
34}
35
36/// Check if a model name matches recommended reasoning models for session analysis.
37///
38/// Recommended: Anthropic Opus, OpenAI GPT-5/O3/O4, Gemini Pro 3+,
39/// or any model with "reasoning" or "think" in the name.
40#[allow(clippy::collapsible_if)]
41pub fn is_reasoning_model(model: &str) -> bool {
42 let m = model.to_lowercase();
43
44 if m.contains("opus") {
45 return true;
46 }
47 if m.contains("gpt-5") || m.contains("o3") || m.contains("o4") {
48 return true;
49 }
50 if m.contains("gemini") && m.contains("pro") {
51 // The version may follow ("gemini-pro-3.5") or precede ("gemini-3.5-pro")
52 // the tier, so take the major version from the first number in the name.
53 if let Some(start) = m.find(|c: char| c.is_ascii_digit()) {
54 let tail = &m[start..];
55 let end = tail
56 .find(|c: char| !c.is_ascii_digit())
57 .unwrap_or(tail.len());
58 if let Ok(v) = tail[..end].parse::<u32>()
59 && v >= 3
60 {
61 return true;
62 }
63 }
64 }
65 m.contains("reasoning") || m.contains("think")
66}
67
68/// How hard the model should work on a request — the Anthropic
69/// `output_config.effort` scale.
70///
71/// Effort is a property of the JOB, not of the model: the same model routing a
72/// one-line JSON plan and the same model doing a multi-file refactor want
73/// different levels. Set it at the call site that knows what it is asking for.
74///
75/// Note that NOT sending effort is not neutral — the API default is `High`.
76/// Every call that leaves it unset is already paying for high effort, so the
77/// useful direction for mechanical work is *down*.
78#[derive(
79 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
80)]
81#[serde(rename_all = "lowercase")]
82pub enum Effort {
83 Low,
84 Medium,
85 High,
86 Xhigh,
87 Max,
88}
89
90impl Effort {
91 /// Every level, cheapest first — for `--help` text and error messages, so
92 /// the valid set is never spelled out in two places.
93 pub const ALL: &'static [Effort] = &[
94 Effort::Low,
95 Effort::Medium,
96 Effort::High,
97 Effort::Xhigh,
98 Effort::Max,
99 ];
100
101 pub fn as_str(self) -> &'static str {
102 match self {
103 Effort::Low => "low",
104 Effort::Medium => "medium",
105 Effort::High => "high",
106 Effort::Xhigh => "xhigh",
107 Effort::Max => "max",
108 }
109 }
110}
111
112impl std::str::FromStr for Effort {
113 type Err = String;
114
115 fn from_str(s: &str) -> Result<Self, Self::Err> {
116 let want = s.trim().to_lowercase();
117 Effort::ALL
118 .iter()
119 .copied()
120 .find(|e| e.as_str() == want)
121 .ok_or_else(|| {
122 let valid: Vec<&str> = Effort::ALL.iter().map(|e| e.as_str()).collect();
123 format!("unknown effort '{s}' (valid: {})", valid.join(", "))
124 })
125 }
126}
127
128/// What form of reasoning control a model accepts.
129///
130/// Provider controls do not share a shape, and three of these cannot be
131/// expressed by a level-to-string table:
132///
133/// * [`EffortShape::AlwaysOn`] is not [`EffortShape::None`]. Mistral's
134/// Magistral models always reason and reject `reasoning_effort` with HTTP
135/// 422 — a hard failure, not a degradation. `None` means "passing nothing is
136/// correct"; `AlwaysOn` means "passing anything breaks every call".
137/// * [`EffortShape::Binary`] is not a degenerate `Graded`. Qwen and GLM have a
138/// switch, not a dial, and spell it differently (`chat_template_kwargs`
139/// versus `thinking: {type}`). Two other agent products shipped that exact
140/// confusion.
141/// * [`EffortShape::Budget`] takes an integer on the wire but still carries a
142/// level list, because the user and both UIs deal in levels — only the
143/// client converts, at the last possible moment.
144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145pub enum EffortShape {
146 /// Levels this model accepts, cheapest first.
147 Graded(&'static [Effort]),
148 /// Thinking is a switch; `on_at` is the lowest level that turns it on.
149 Binary { on_at: Effort },
150 /// Wants an integer token budget; these are the levels to offer.
151 Budget(&'static [Effort]),
152 /// Always reasons and rejects the parameter. Send nothing.
153 AlwaysOn,
154 /// No reasoning control.
155 None,
156}
157
158/// A level set is an arbitrary SUBSET of [`Effort::ALL`], not a prefix of it.
159/// Two tiers below have holes: Anthropic's pre-4.7 lines have `max` but no
160/// `xhigh` (that step was inserted between them in 4.7), and DeepSeek V4
161/// publishes low/high/max with no medium. Naming these by a ceiling —
162/// `LEVELS_TO_HIGH` and the like — is what produced a first draft that silently
163/// downgraded `max` to `high` on Opus 4.6. Name the membership, not a bound.
164const LEVELS_ALL: &[Effort] = &[
165 Effort::Low,
166 Effort::Medium,
167 Effort::High,
168 Effort::Xhigh,
169 Effort::Max,
170];
171/// Anthropic before 4.7: the whole scale except the `xhigh` step.
172const LEVELS_NO_XHIGH: &[Effort] = &[Effort::Low, Effort::Medium, Effort::High, Effort::Max];
173const LEVELS_LMHX: &[Effort] = &[Effort::Low, Effort::Medium, Effort::High, Effort::Xhigh];
174const LEVELS_LMH: &[Effort] = &[Effort::Low, Effort::Medium, Effort::High];
175/// DeepSeek V4 publishes low / high / max — there is no medium step.
176const LEVELS_DEEPSEEK: &[Effort] = &[Effort::Low, Effort::High, Effort::Max];
177/// A switch has two positions and must offer two, not three that collapse to
178/// two. `Low` is off, `High` is on; the threshold lives in `Binary::on_at`.
179const LEVELS_BINARY: &[Effort] = &[Effort::Low, Effort::High];
180
181impl EffortShape {
182 /// The levels a UI should offer. Empty for the two shapes that take no
183 /// level from the user.
184 pub fn levels(&self) -> &'static [Effort] {
185 match self {
186 EffortShape::Graded(l) | EffortShape::Budget(l) => l,
187 EffortShape::Binary { .. } => LEVELS_BINARY,
188 EffortShape::AlwaysOn | EffortShape::None => &[],
189 }
190 }
191}
192
193/// Which reasoning control `model` accepts.
194///
195/// Keyed on the model id with any `vendor/` prefix stripped, never on the
196/// registry's `provider:` field — that records the wire protocol, so DeepSeek,
197/// Qwen and every other OpenAI-compatible third party all read `openai`.
198///
199/// Capability is version-scoped, not family-scoped: grok-4.3, 4.5 and 4.6 each
200/// accept a different set, exactly as the Claude 4-5 / 4-6 / 4-7 / 5 lines do.
201/// Named const lists per tier, so a new model is one edit in one place.
202///
203/// Vendor levels below `Low` (`none`, `minimal`) are deliberately dropped:
204/// MUR's scale starts at `Low`, and a level MUR cannot name is a level MUR
205/// does not offer. Nothing is mis-sent.
206pub fn effort_shape(model: &str) -> EffortShape {
207 /// Anthropic lines with the `xhigh` step (Opus 4.7 and later).
208 const ANTHROPIC_FULL: &[&str] = &[
209 "claude-opus-5",
210 "claude-opus-4-8",
211 "claude-opus-4-7",
212 "claude-sonnet-5",
213 "claude-fable-5",
214 "claude-mythos-5",
215 ];
216 /// Anthropic lines that take effort but have no `xhigh` step.
217 const ANTHROPIC_NO_XHIGH: &[&str] =
218 &["claude-opus-4-6", "claude-sonnet-4-6", "claude-opus-4-5"];
219 /// OpenAI reasoning families. `xhigh`/`max` clamp to `high` at the wire.
220 const OPENAI_REASONING: &[&str] = &["gpt-5", "o1", "o3", "o4"];
221 /// DeepSeek V4 thinking effort.
222 const DEEPSEEK_GRADED: &[&str] = &["deepseek-v4"];
223 /// Grok lines that added the `xhigh` step.
224 const GROK_XHIGH: &[&str] = &["grok-4.6", "grok-4.7"];
225 /// Grok lines with low/medium/high only.
226 const GROK_GRADED: &[&str] = &["grok-4.3", "grok-4.5"];
227 /// Gemini 3+ takes `thinkingConfig.thinkingLevel` — a level name.
228 const GEMINI_LEVEL: &[&str] = &["gemini-3"];
229 /// Gemini 2.5 takes `thinkingConfig.thinkingBudget` — an integer.
230 const GEMINI_BUDGET: &[&str] = &["gemini-2.5"];
231 /// Mistral hybrids where `reasoning_effort` enables reasoning.
232 const MISTRAL_GRADED: &[&str] = &["mistral-small-3", "mistral-small-4"];
233 /// Dedicated reasoning models that REJECT the parameter with HTTP 422.
234 const ALWAYS_ON: &[&str] = &["magistral"];
235 /// Models whose only control is an on/off switch.
236 const BINARY: &[&str] = &["qwen3", "glm-"];
237
238 let m = model.to_lowercase();
239 let bare = m.rsplit('/').next().unwrap_or(&m);
240 let has = |prefixes: &[&str]| prefixes.iter().any(|p| bare.starts_with(p));
241
242 // AlwaysOn is checked first: sending anything to these is a hard error, so
243 // no later arm may claim them.
244 if has(ALWAYS_ON) {
245 return EffortShape::AlwaysOn;
246 }
247 if has(ANTHROPIC_FULL) {
248 return EffortShape::Graded(LEVELS_ALL);
249 }
250 // Anthropic pre-4.7 keeps `max`; it is only the `xhigh` step it lacks.
251 if has(ANTHROPIC_NO_XHIGH) {
252 return EffortShape::Graded(LEVELS_NO_XHIGH);
253 }
254 if has(OPENAI_REASONING) || has(GROK_GRADED) {
255 return EffortShape::Graded(LEVELS_LMH);
256 }
257 if has(GROK_XHIGH) {
258 return EffortShape::Graded(LEVELS_LMHX);
259 }
260 if has(DEEPSEEK_GRADED) {
261 return EffortShape::Graded(LEVELS_DEEPSEEK);
262 }
263 if has(GEMINI_LEVEL) || has(MISTRAL_GRADED) {
264 return EffortShape::Graded(LEVELS_LMH);
265 }
266 if has(GEMINI_BUDGET) {
267 return EffortShape::Budget(LEVELS_LMH);
268 }
269 if has(BINARY) {
270 return EffortShape::Binary {
271 on_at: Effort::Medium,
272 };
273 }
274 EffortShape::None
275}
276
277/// Where the effort in force came from, so a surface can say so instead of
278/// showing a bare level the user cannot account for.
279#[derive(Debug, Clone, Copy, PartialEq, Eq)]
280pub enum EffortSource {
281 /// Set for this conversation only (murmur `/effort`).
282 SessionOverride,
283 /// Stored on the agent profile.
284 Profile,
285 /// Nothing set — the provider's own default applies. Note that is not
286 /// "no effort": the API default is high.
287 Unset,
288}
289
290/// The effort actually in force for `model`, and where it came from.
291///
292/// The ONLY derivation of this. murmur and the Hub both call it; neither
293/// computes its own, because two surfaces answering one question differently
294/// is a failure this codebase has already shipped twice.
295///
296/// A stored level the model cannot accept is narrowed to the nearest level it
297/// can, and the source is preserved — the user did set it; they are simply
298/// getting the closest thing that will not 400.
299pub fn effective_effort(
300 session: Option<Effort>,
301 profile: Option<Effort>,
302 model: &str,
303) -> (Option<Effort>, EffortSource) {
304 let (want, source) = match (session, profile) {
305 (Some(e), _) => (e, EffortSource::SessionOverride),
306 (None, Some(e)) => (e, EffortSource::Profile),
307 (None, None) => return (None, EffortSource::Unset),
308 };
309 let levels = effort_shape(model).levels();
310 if levels.is_empty() {
311 return (None, EffortSource::Unset);
312 }
313 if levels.contains(&want) {
314 return (Some(want), source);
315 }
316 match levels.iter().rev().find(|l| **l < want).copied() {
317 Some(narrowed) => (Some(narrowed), source),
318 // `want` is below every level this model offers; take its cheapest.
319 None => (levels.first().copied(), source),
320 }
321}
322
323/// The effort level to actually send for `model`, or `None` when the model
324/// takes no effort parameter at all.
325///
326/// Sending an unsupported level is a 400, and the support matrix is per-model:
327/// the `xhigh` step arrived with Opus 4.7, so older models that otherwise
328/// accept effort reject it, and models before the 4.6 line reject the
329/// parameter outright. Rather than let each call site memorise that, requests
330/// state the effort they *want* and this narrows it — downgrading `xhigh` to
331/// `high` (the cheaper neighbour) and dropping the field entirely where it
332/// isn't understood.
333///
334/// Deliberately shaped like the sampling-param guard next door: one named
335/// list, one place to edit when a model ships, rather than a literal model ID
336/// buried in a conditional that goes stale on the next release.
337pub fn supported_effort(model: &str, want: Effort) -> Option<Effort> {
338 /// This mapper is Anthropic's. [`effort_shape`] is vendor-neutral — it
339 /// answers "which levels", never "whose client is this" — so the vendor
340 /// gate stays here, symmetric with `openai_reasoning_effort`'s family
341 /// gate. Without it a delegated `supported_effort` starts claiming
342 /// `gpt-5`, which an existing test caught immediately.
343 const ANTHROPIC: &str = "claude-";
344
345 let m = model.to_lowercase();
346 let bare = m.rsplit('/').next().unwrap_or(&m);
347 if !bare.starts_with(ANTHROPIC) {
348 return None;
349 }
350 let levels = match effort_shape(model) {
351 EffortShape::Graded(l) => l,
352 // Anthropic is Graded or nothing. Budget/Binary models never reach this
353 // client, and AlwaysOn must be sent nothing anywhere.
354 _ => return None,
355 };
356 if levels.contains(&want) {
357 return Some(want);
358 }
359 // Degrade to the most expensive level this model DOES accept rather than
360 // send one it will 400 on. `levels` is a subset, not a prefix, so this
361 // steps over holes (pre-4.7 Anthropic has `max` but no `xhigh`).
362 levels.iter().rev().find(|l| **l < want).copied()
363}
364
365/// The `reasoning_effort` value to send for an OpenAI-compatible model, or
366/// `None` when the model takes no such parameter.
367///
368/// Verified against the current OpenAI reasoning guide rather than recalled:
369/// the parameter is `reasoning.effort` (accepted as `reasoning_effort` on the
370/// chat endpoint) and its vocabulary is `none | minimal | low | medium | high
371/// | xhigh | max` — a superset of ours, not the three levels an older memory
372/// would suggest. Checking mattered: building the mapping from that memory
373/// would have clamped `xhigh` away for no reason.
374///
375/// Two deliberate narrowings, both because this client is not "OpenAI" — it is
376/// *anything OpenAI-compatible*, including OpenRouter and local servers:
377///
378/// * Gated on the model family, not the provider. A local llama behind an
379/// OpenAI-shaped endpoint has no idea what `reasoning_effort` means.
380/// * `Xhigh`/`Max` clamp to `high`. The docs state the accepted values are
381/// model-dependent and publish no table, so passing the top of the scale
382/// through would be a 400 waiting for whichever model lacks it. Degrading is
383/// the same call made for Anthropic's missing `xhigh` step — and the same
384/// one made everywhere today: never fail the default path, lose a little
385/// depth instead. Lift the clamp per-model once a support table exists.
386pub fn openai_reasoning_effort(model: &str, want: Effort) -> Option<&'static str> {
387 /// Model families that take a reasoning effort. Prefixes, matched after
388 /// any `vendor/` prefix is stripped — OpenRouter names models
389 /// `openai/gpt-5`, and `google/gemini-3.6-flash` must NOT match.
390 const REASONING_FAMILIES: &[&str] = &["gpt-5", "o1", "o3", "o4"];
391
392 let m = model.to_lowercase();
393 let bare = m.rsplit('/').next().unwrap_or(&m);
394 if !REASONING_FAMILIES.iter().any(|f| bare.starts_with(f)) {
395 return None;
396 }
397 // Second gate: the table is the owner, so a family member the table has
398 // demoted (or that becomes AlwaysOn) stops being sent a value here too.
399 if !matches!(effort_shape(model), EffortShape::Graded(_)) {
400 return None;
401 }
402 Some(match want {
403 Effort::Low => "low",
404 Effort::Medium => "medium",
405 Effort::High | Effort::Xhigh | Effort::Max => "high",
406 })
407}
408
409/// Qwen3's thinking switch (`chat_template_kwargs.enable_thinking`) for
410/// `want`, or `None` when `model` is not a Qwen3 switch model.
411///
412/// Gated on the `qwen3` prefix, not on [`EffortShape::Binary`] alone: GLM is
413/// also Binary but spells its switch `thinking: {type}`, and sending Qwen's
414/// kwarg to it would be ignored at best. `on_at` from the table decides the
415/// position, so the threshold has one owner.
416pub fn qwen_enable_thinking(model: &str, want: Effort) -> Option<bool> {
417 const QWEN_SWITCH: &str = "qwen3";
418 let m = model.to_lowercase();
419 let bare = m.rsplit('/').next().unwrap_or(&m);
420 if !bare.starts_with(QWEN_SWITCH) {
421 return None;
422 }
423 match effort_shape(model) {
424 EffortShape::Binary { on_at } => Some(want >= on_at),
425 _ => None,
426 }
427}
428
429#[cfg(test)]
430mod tests {
431 use super::*;
432
433 #[test]
434 fn effective_effort_reports_value_and_where_it_came_from() {
435 use EffortSource::*;
436 // Session beats profile.
437 assert_eq!(
438 effective_effort(Some(Effort::Low), Some(Effort::Max), "claude-opus-5"),
439 (Some(Effort::Low), SessionOverride)
440 );
441 // Profile when there is no session override.
442 assert_eq!(
443 effective_effort(None, Some(Effort::Max), "claude-opus-5"),
444 (Some(Effort::Max), Profile)
445 );
446 // Neither set.
447 assert_eq!(effective_effort(None, None, "claude-opus-5"), (None, Unset));
448 // A value the model cannot take is narrowed, and the SOURCE is
449 // preserved: the user still set it, they just get the nearest level
450 // that works. DeepSeek V4 has no medium step.
451 assert_eq!(
452 effective_effort(None, Some(Effort::Medium), "deepseek-v4-pro"),
453 (Some(Effort::Low), Profile)
454 );
455 // A model with no control reports nothing regardless of what is stored.
456 assert_eq!(
457 effective_effort(Some(Effort::Max), Some(Effort::Max), "gpt-4o"),
458 (None, Unset)
459 );
460 }
461
462 /// Delegation must not change what the mappers return. This pins the exact
463 /// case a first draft of this plan got wrong: Anthropic's pre-4.7 lines keep
464 /// `max` and lack only `xhigh`, so a level set expressed as a ceiling
465 /// silently downgrades `max` to `high` here.
466 #[test]
467 fn delegation_preserves_the_hole_in_the_pre_4_7_scale() {
468 // The hole: xhigh absent, max present.
469 assert_eq!(
470 supported_effort("claude-opus-4-6", Effort::Xhigh),
471 Some(Effort::High)
472 );
473 assert_eq!(
474 supported_effort("claude-opus-4-6", Effort::Max),
475 Some(Effort::Max)
476 );
477 // The full scale is unaffected.
478 assert_eq!(
479 supported_effort("claude-opus-5", Effort::Xhigh),
480 Some(Effort::Xhigh)
481 );
482 // A model the table calls AlwaysOn must get nothing from either mapper,
483 // because sending it anything is a 422.
484 assert_eq!(
485 supported_effort("magistral-small-latest", Effort::High),
486 None
487 );
488 assert_eq!(
489 openai_reasoning_effort("magistral-small-latest", Effort::High),
490 None
491 );
492 }
493
494 #[test]
495 fn effort_shape_covers_each_vendor_tier() {
496 use EffortShape::*;
497 assert!(matches!(effort_shape("claude-opus-5"), Graded(l) if l.len() == 5));
498 // Four, not three: 4.6 keeps `max` and lacks only the `xhigh` step that
499 // 4.7 inserted between them. A level set is a subset, not a prefix.
500 assert!(matches!(effort_shape("claude-opus-4-6"), Graded(l) if l.len() == 4));
501 assert!(matches!(effort_shape("claude-opus-4-6"), Graded(l) if l.contains(&Effort::Max)));
502 assert!(
503 matches!(effort_shape("claude-opus-4-6"), Graded(l) if !l.contains(&Effort::Xhigh))
504 );
505 assert!(matches!(effort_shape("gpt-5"), Graded(_)));
506 assert!(matches!(effort_shape("grok-4.6"), Graded(l) if l.contains(&Effort::Xhigh)));
507 assert!(matches!(effort_shape("grok-4.5"), Graded(l) if !l.contains(&Effort::Xhigh)));
508 assert!(matches!(effort_shape("gemini-3-pro"), Graded(_)));
509 assert!(matches!(effort_shape("gemini-2.5-pro"), Budget(_)));
510 assert!(matches!(effort_shape("qwen3-32b"), Binary { .. }));
511 // A switch offers exactly two positions, never three that collapse to two.
512 assert_eq!(effort_shape("qwen3-32b").levels().len(), 2);
513 assert!(matches!(effort_shape("glm-4.6"), Binary { .. }));
514 assert!(matches!(effort_shape("magistral-medium-latest"), AlwaysOn));
515 assert!(matches!(effort_shape("gpt-4o"), None));
516 assert!(matches!(effort_shape("llama3.2:3b"), None));
517 }
518
519 #[test]
520 fn qwen_thinking_switch_follows_the_table_threshold() {
521 assert_eq!(
522 qwen_enable_thinking("Qwen3.5-4B-MLX-4bit", Effort::Low),
523 Some(false)
524 );
525 assert_eq!(
526 qwen_enable_thinking("qwen/qwen3-32b", Effort::High),
527 Some(true)
528 );
529 // GLM is a switch too, but not this spelling of one.
530 assert_eq!(qwen_enable_thinking("glm-4.6", Effort::Low), None);
531 assert_eq!(qwen_enable_thinking("gpt-5", Effort::Low), None);
532 assert_eq!(qwen_enable_thinking("llama3.2:3b", Effort::Low), None);
533 }
534
535 /// The three cases the design turns on. Each must fail if its guard is removed.
536 #[test]
537 fn effort_shape_negative_cases() {
538 use EffortShape::*;
539 // 1. DeepSeek V4 has low/high/max and NO medium. Offering medium is a 400.
540 let EffortShape::Graded(levels) = effort_shape("deepseek-v4-pro") else {
541 panic!("deepseek-v4-pro must be Graded");
542 };
543 assert!(
544 !levels.contains(&Effort::Medium),
545 "deepseek has no medium: {levels:?}"
546 );
547 assert_eq!(levels, &[Effort::Low, Effort::High, Effort::Max]);
548
549 // 2. A vendor prefix must be stripped before matching, and a Google model
550 // must never match an OpenAI family prefix.
551 assert!(matches!(effort_shape("openai/gpt-5"), Graded(_)));
552 assert!(matches!(effort_shape("google/gemini-3.6-flash"), Graded(_)));
553 assert!(!matches!(
554 effort_shape("google/gemini-2.5-flash"),
555 Graded(_)
556 ));
557
558 // 3. Magistral REJECTS the parameter (HTTP 422). AlwaysOn is not None:
559 // None means "send nothing and that is correct", AlwaysOn means
560 // "send nothing or every call fails".
561 assert!(matches!(effort_shape("magistral-small-latest"), AlwaysOn));
562 assert!(effort_shape("magistral-small-latest").levels().is_empty());
563 }
564
565 #[test]
566 fn supported_effort_narrows_per_model_capability() {
567 // Full scale: passed through unchanged.
568 assert_eq!(
569 supported_effort("claude-opus-5", Effort::Xhigh),
570 Some(Effort::Xhigh)
571 );
572 assert_eq!(
573 supported_effort("claude-sonnet-5", Effort::Low),
574 Some(Effort::Low)
575 );
576 // Prefix match, so dated or suffixed variants resolve the same.
577 assert_eq!(
578 supported_effort("claude-opus-5-preview", Effort::Max),
579 Some(Effort::Max)
580 );
581 // No `xhigh` step before Opus 4.7 — downgrade to the cheaper neighbour
582 // rather than 400.
583 assert_eq!(
584 supported_effort("claude-opus-4-6", Effort::Xhigh),
585 Some(Effort::High)
586 );
587 // …but the levels it does have pass through.
588 assert_eq!(
589 supported_effort("claude-opus-4-6", Effort::Max),
590 Some(Effort::Max)
591 );
592 // Models with no effort parameter: drop the field entirely.
593 assert_eq!(supported_effort("claude-haiku-4-5", Effort::Low), None);
594 assert_eq!(supported_effort("claude-sonnet-4-5", Effort::High), None);
595 // Non-Anthropic models never carry it.
596 assert_eq!(supported_effort("llama3.2:3b", Effort::Low), None);
597 assert_eq!(supported_effort("gpt-5", Effort::Low), None);
598 }
599
600 #[test]
601 fn effort_strings_match_the_api_scale() {
602 assert_eq!(Effort::Low.as_str(), "low");
603 assert_eq!(Effort::Xhigh.as_str(), "xhigh");
604 assert_eq!(Effort::Max.as_str(), "max");
605 // Ordered cheapest-first so a caller can clamp with `min`.
606 assert!(Effort::Low < Effort::High && Effort::High < Effort::Max);
607 }
608
609 #[test]
610 fn openai_effort_gates_on_family_and_clamps_the_top() {
611 // The three shared levels pass through by name.
612 assert_eq!(openai_reasoning_effort("gpt-5", Effort::Low), Some("low"));
613 assert_eq!(
614 openai_reasoning_effort("o3-mini", Effort::Medium),
615 Some("medium")
616 );
617 // Top of the scale degrades rather than risking a 400 on a model whose
618 // subset lacks it — the accepted values are model-dependent and there
619 // is no published table to key on.
620 assert_eq!(
621 openai_reasoning_effort("gpt-5", Effort::Xhigh),
622 Some("high")
623 );
624 assert_eq!(openai_reasoning_effort("gpt-5", Effort::Max), Some("high"));
625 // OpenRouter prefixes its models; the family gate must see through it…
626 assert_eq!(
627 openai_reasoning_effort("openai/gpt-5", Effort::Low),
628 Some("low")
629 );
630 // …without letting a non-OpenAI model routed the same way through.
631 assert_eq!(
632 openai_reasoning_effort("google/gemini-3.6-flash", Effort::Low),
633 None
634 );
635 // A local model behind an OpenAI-shaped endpoint takes no such param.
636 assert_eq!(openai_reasoning_effort("llama3.2:3b", Effort::Low), None);
637 assert_eq!(openai_reasoning_effort("gpt-4o", Effort::Low), None);
638 }
639
640 #[test]
641 fn test_is_reasoning_model() {
642 // Anthropic opus models
643 assert!(is_reasoning_model("claude-opus-5"));
644 assert!(is_reasoning_model("claude-opus-4-20250514"));
645
646 // OpenAI reasoning models
647 assert!(is_reasoning_model("gpt-5"));
648 assert!(is_reasoning_model("chatgpt-5.4"));
649 assert!(is_reasoning_model("o3-mini"));
650 assert!(is_reasoning_model("o4-preview"));
651
652 // Gemini pro >= 3 (version before or after the tier)
653 assert!(is_reasoning_model("gemini-pro-3.5"));
654 assert!(is_reasoning_model("gemini-pro-3"));
655 assert!(is_reasoning_model("gemini-3.5-pro"));
656 assert!(!is_reasoning_model("gemini-2.5-pro"));
657 assert!(!is_reasoning_model("gemini-pro-2"));
658 assert!(!is_reasoning_model("gemini-pro-1.5"));
659
660 // Generic reasoning/thinking
661 assert!(is_reasoning_model("deepseek-reasoning-v2"));
662 assert!(is_reasoning_model("qwen-thinking-32b"));
663
664 // Non-recommended
665 assert!(!is_reasoning_model("claude-sonnet-4-20250514"));
666 assert!(!is_reasoning_model("gpt-4o"));
667 assert!(!is_reasoning_model("gemini-flash-2"));
668 assert!(!is_reasoning_model("llama3"));
669 }
670}