返回 CodeWhale
local_reasoning.rs
根目录 / crates / config / src / local_reasoning.rs
1 //! Reviewed local-template facts replacing the provider-wide low/medium/high
2 //! assumption in the vLLM Chat adapter. A server speaks a protocol; its model
3 //! template owns the effort ladder. Unknown models and other routes stay intact.
4 use std::collections::HashMap;
5 use std::sync::OnceLock;
6
7 use serde::Deserialize;
8 use serde_json::{Value, json};
9
10 use crate::ProviderKind;
11
12 /// A reviewed model-template ladder. `high` is the on switch for boolean models;
13 /// `max` is the existing UI identifier for the deepest supported effort.
14 #[derive(Debug, Deserialize)]
15 pub struct LocalReasoningSpec {
16 /// Canonical served-name prefixes, with a required suffix boundary.
17 pub prefixes: Vec<String>,
18 /// Distinct selectable tiers, in ascending order.
19 pub tiers: Vec<String>,
20 /// Lowest meaningful thinking tier when no preference was saved.
21 pub default: String,
22 aliases: HashMap<String, String>,
23 wire: HashMap<String, Option<String>>,
24 }
25
26 impl LocalReasoningSpec {
27 /// Normalize old saved choices without changing their stored value. Unknown
28 /// values are not guessed: the ordinary adapter/server keeps validating them.
29 #[must_use]
30 pub fn normalize(&self, effort: &str) -> Option<&str> {
31 let effort = effort.trim().to_ascii_lowercase();
32 let effort = match effort.as_str() {
33 "minimal" | "minimum" | "light" => "low",
34 "mid" => "medium",
35 "disabled" | "none" | "false" => "off",
36 "maximum" | "ultra" | "ultracode" => "max",
37 "" => return Some(&self.default),
38 other => other,
39 };
40 self.tiers
41 .iter()
42 .find(|tier| tier.as_str() == effort)
43 .map(String::as_str)
44 .or_else(|| self.aliases.get(effort).map(String::as_str))
45 }
46 }
47
48 /// Find a fact only for a reviewed served-name family, including repository IDs.
49 /// A version such as Qwen3.8-27B2 must not inherit Qwen3.8-27B's contract.
50 #[must_use]
51 pub fn local_reasoning_spec(model: &str) -> Option<&'static LocalReasoningSpec> {
52 static SPECS: OnceLock<Vec<LocalReasoningSpec>> = OnceLock::new();
53 let specs = SPECS.get_or_init(|| {
54 serde_json::from_str(include_str!("local_reasoning.json"))
55 .expect("reviewed local reasoning facts")
56 });
57 let normalized = model.trim().to_ascii_lowercase().replace(['_', ' '], "-");
58 let name = normalized.rsplit('/').next()?;
59 // Separately named Thinking variants can be always-on and have a
60 // different template; the reviewed base-family fact does not cover them.
61 if name.contains("thinking") {
62 return None;
63 }
64 specs.iter().find(|spec| {
65 spec.prefixes.iter().any(|prefix| {
66 name.strip_prefix(prefix.as_str())
67 .is_some_and(|suffix| suffix.is_empty() || suffix.starts_with(['-', ':']))
68 })
69 })
70 }
71
72 /// Shape only thinking fields after the generic Chat controls. Route identity,
73 /// authentication, message history, budgets and sampling remain caller-owned.
74 /// SGLang endpoints using the local vLLM wire consume the nested spelling too.
75 pub fn apply_local_reasoning_controls(
76 body: &mut Value,
77 provider: ProviderKind,
78 model: &str,
79 effort: Option<&str>,
80 ) {
81 if provider != ProviderKind::Vllm {
82 return;
83 }
84 let Some((spec, tier)) =
85 local_reasoning_spec(model).and_then(|spec| Some((spec, spec.normalize(effort?)?)))
86 else {
87 return;
88 };
89 let Some(object) = body.as_object_mut() else {
90 return;
91 };
92 let kwargs = object
93 .entry("chat_template_kwargs")
94 .or_insert_with(|| json!({}));
95 let Some(kwargs) = kwargs.as_object_mut() else {
96 return;
97 };
98 kwargs.insert("enable_thinking".into(), json!(tier != "off"));
99 match &spec.wire[tier] {
100 Some(wire) => {
101 kwargs.insert("reasoning_effort".into(), json!(wire));
102 }
103 None => {
104 kwargs.remove("reasoning_effort");
105 }
106 }
107 // Template effort is an extension, not a promise about the server's
108 // top-level OpenAI enum. Older vLLM schemas reject max/xhigh before
109 // rendering. Both reviewed vLLM/SGLang routes accept template kwargs.
110 object.remove("reasoning_effort");
111 }
112
113 #[cfg(test)]
114 mod tests {
115 use super::*;
116
117 #[test]
118 fn registry_tiers_aliases_and_defaults_all_have_wire_contracts() {
119 let specs: Vec<LocalReasoningSpec> =
120 serde_json::from_str(include_str!("local_reasoning.json")).unwrap();
121 assert!(!specs.is_empty());
122 for spec in specs {
123 assert!(!spec.prefixes.is_empty());
124 assert_eq!(spec.tiers.len(), spec.wire.len());
125 for tier in spec.tiers.iter().chain(spec.aliases.values()) {
126 assert!(spec.wire.contains_key(tier));
127 }
128 assert!(spec.tiers.contains(&spec.default));
129 }
130 }
131
132 #[test]
133 fn qwen38_high_uses_xhigh_and_preserves_request_fields() {
134 for model in ["Qwen3.8-27B-NVFP4", "nvidia/Qwen3.8-Flash-Next-NVFP4"] {
135 let mut body = json!({"model":model,"messages":[{"role":"user","content":"hello"}],"max_tokens":123,"stream":true,"tools":[{"type":"function"}],"chat_template_kwargs":{"custom":42},"reasoning_effort":"high"});
136 let before = body.clone();
137 apply_local_reasoning_controls(&mut body, ProviderKind::Vllm, model, Some("high"));
138 assert!(body.get("reasoning_effort").is_none());
139 assert_eq!(body["chat_template_kwargs"]["reasoning_effort"], "xhigh");
140 assert_eq!(body["chat_template_kwargs"]["custom"], 42);
141 for field in ["model", "messages", "max_tokens", "stream", "tools"] {
142 assert_eq!(body[field], before[field]);
143 }
144 }
145 }
146
147 #[test]
148 fn legacy_preference_spellings_keep_their_effective_tier() {
149 let spec = local_reasoning_spec("Qwen3.8-27B-NVFP4").unwrap();
150 for (saved, expected) in [
151 ("maximum", "max"),
152 ("ultra", "max"),
153 ("ultracode", "max"),
154 ("xhigh", "max"),
155 ("minimum", "low"),
156 ("minimal", "low"),
157 ("light", "low"),
158 ("mid", "medium"),
159 ("disabled", "off"),
160 ("none", "off"),
161 ("false", "off"),
162 ("", "low"),
163 (" HIGH ", "max"),
164 ] {
165 assert_eq!(spec.normalize(saved), Some(expected), "{saved}");
166 }
167 }
168
169 #[test]
170 fn every_reviewed_tier_and_legacy_alias_has_a_valid_wire_value() {
171 let fixtures = [
172 (
173 "Qwen3.8-27B-NVFP4",
174 [
175 None,
176 Some("low"),
177 Some("medium"),
178 Some("xhigh"),
179 Some("xhigh"),
180 Some("xhigh"),
181 ],
182 ),
183 (
184 "GLM-5.3-Flash-NVFP4",
185 [
186 Some("low"),
187 Some("low"),
188 Some("high"),
189 Some("high"),
190 Some("max"),
191 Some("max"),
192 ],
193 ),
194 (
195 "DeepSeek-V4-Flash-Vision-Exp",
196 [
197 None,
198 Some("low"),
199 Some("high"),
200 Some("high"),
201 Some("max"),
202 Some("max"),
203 ],
204 ),
205 ];
206 for (model, expected) in fixtures {
207 for (effort, wire) in ["off", "low", "medium", "high", "max", "xhigh"]
208 .into_iter()
209 .zip(expected)
210 {
211 let mut body = json!({});
212 apply_local_reasoning_controls(&mut body, ProviderKind::Vllm, model, Some(effort));
213 assert!(body.get("reasoning_effort").is_none());
214 assert_eq!(
215 body["chat_template_kwargs"]["reasoning_effort"].as_str(),
216 wire,
217 "{model}: {effort}"
218 );
219 assert_eq!(
220 body["chat_template_kwargs"]["enable_thinking"],
221 wire.is_some(),
222 "{model}: {effort}"
223 );
224 }
225 }
226 }
227
228 #[test]
229 fn boolean_templates_only_get_the_thinking_switch() {
230 for model in ["Ornith-1.5-35B-A3B-NVFP4", "Qwen3.6-35B-A3B-NVFP4-Fast"] {
231 for effort in ["off", "low", "medium", "high", "max"] {
232 let mut body = json!({"reasoning_effort":"high","chat_template_kwargs":{"reasoning_effort":"medium"}});
233 apply_local_reasoning_controls(&mut body, ProviderKind::Vllm, model, Some(effort));
234 assert!(body.get("reasoning_effort").is_none());
235 assert!(
236 body["chat_template_kwargs"]
237 .get("reasoning_effort")
238 .is_none()
239 );
240 assert_eq!(
241 body["chat_template_kwargs"]["enable_thinking"],
242 effort != "off"
243 );
244 }
245 }
246 }
247
248 #[test]
249 fn unreviewed_models_non_vllm_routes_and_unspecified_effort_are_untouched() {
250 for model in [
251 "Qwen3.8-27B2",
252 "Qwen3.8-235B",
253 "Qwen3.8-27B-Thinking",
254 "Qwen3.6-35B-A3B-Thinking",
255 "DeepSeek-V4.1-Flash-1017",
256 "custom-model",
257 ] {
258 assert!(local_reasoning_spec(model).is_none());
259 }
260 for (provider, model, effort) in [
261 (ProviderKind::Openai, "Qwen3.8-27B-NVFP4", Some("high")),
262 (ProviderKind::Vllm, "custom-model", Some("high")),
263 (ProviderKind::Vllm, "Qwen3.8-27B-NVFP4", None),
264 (ProviderKind::Vllm, "Qwen3.8-27B-NVFP4", Some("unknown")),
265 ] {
266 let mut body = json!({"reasoning_effort":"high","chat_template_kwargs":{"custom":42}});
267 let before = body.clone();
268 apply_local_reasoning_controls(&mut body, provider, model, effort);
269 assert_eq!(body, before);
270 }
271 }
272 }
273
273 lines RUST