返回 CodeWhale
reasoning_effort.rs
根目录 / crates / engine / src / client / reasoning_effort.rs
1 use codewhale_config::ProviderKind;
2 use serde_json::{Value, json};
3
4 use super::deepseek_effort;
5
6 /// Write DeepSeek's Chat Completions thinking controls from the shared tier
7 /// table.
8 ///
9 /// The table (`client::deepseek_effort`) is the only place the tier ladder is
10 /// written down; this function is just the Chat wire's spelling of it. An
11 /// effort string the table does not name is not a DeepSeek tier request, so
12 /// nothing is written rather than guessing a field the user did not ask for.
13 fn apply_deepseek_chat_reasoning_effort(body: &mut Value, normalized: &str) {
14 let Some(tier) = deepseek_effort::deepseek_effort_tier(normalized) else {
15 return;
16 };
17 if let Some(value) = tier.chat_reasoning_effort() {
18 body["reasoning_effort"] = json!(value);
19 }
20 body["thinking"] = json!({
21 "type": if tier.chat_thinking_enabled() { "enabled" } else { "disabled" },
22 });
23 }
24
25 fn stepfun_reasoning_effort(model: &str, normalized: &str) -> Option<&'static str> {
26 if let Some(offering) =
27 crate::provider_lake::catalog_offering_for_model(ProviderKind::Stepfun, model)
28 {
29 let mut has_low = false;
30 let mut has_medium = false;
31 let mut has_high = false;
32 for option in &offering.reasoning_options {
33 let is_effort = option
34 .get("type")
35 .and_then(Value::as_str)
36 .is_some_and(|kind| kind.eq_ignore_ascii_case("effort"));
37 if !is_effort {
38 continue;
39 }
40 if let Some(values) = option.get("values").and_then(Value::as_array) {
41 for value in values.iter().filter_map(Value::as_str) {
42 if value.eq_ignore_ascii_case("low") {
43 has_low = true;
44 } else if value.eq_ignore_ascii_case("medium") {
45 has_medium = true;
46 } else if value.eq_ignore_ascii_case("high") {
47 has_high = true;
48 }
49 }
50 }
51 }
52 if !has_low && !has_medium && !has_high {
53 return None;
54 }
55 return match normalized {
56 "minimal" | "low" => has_low.then_some("low"),
57 "medium" => has_medium
58 .then_some("medium")
59 .or_else(|| has_high.then_some("high")),
60 "high" | "max" | "xhigh" | "ultra" => has_high.then_some("high"),
61 _ => None,
62 };
63 }
64
65 match (model, normalized) {
66 (
67 "step-5" | "step-5-preview" | "step-3.7-flash" | "step-3.5-flash-2603",
68 "minimal" | "low",
69 ) => Some("low"),
70 ("step-5" | "step-5-preview" | "step-3.7-flash", "medium") => Some("medium"),
71 ("step-3.5-flash-2603", "medium") => Some("high"),
72 (
73 "step-5" | "step-5-preview" | "step-3.7-flash" | "step-3.5-flash-2603",
74 "high" | "max" | "xhigh" | "ultra",
75 ) => Some("high"),
76 _ => None,
77 }
78 }
79
80 fn resolved_openrouter_wire_effort(
81 normalized: &str,
82 reasoning_options: Option<&[Value]>,
83 ) -> Option<&'static str> {
84 let fallback = match normalized {
85 "low" | "minimal" => "low",
86 "medium" | "mid" => "medium",
87 "xhigh" | "max" | "highest" | "ultra" | "ultracode" => "xhigh",
88 _ => "high",
89 };
90 let Some(options) = reasoning_options.filter(|options| !options.is_empty()) else {
91 return Some(fallback);
92 };
93 let effort_values = options.iter().find_map(|option| {
94 (option.get("type").and_then(Value::as_str) == Some("effort"))
95 .then(|| option.get("values").and_then(Value::as_array))
96 .flatten()
97 });
98 let Some(values) = effort_values.filter(|values| !values.is_empty()) else {
99 let has_toggle = options
100 .iter()
101 .any(|option| option.get("type").and_then(Value::as_str) == Some("toggle"));
102 return (!has_toggle).then_some(fallback);
103 };
104 let preferences: &[&str] = match normalized {
105 "low" | "minimal" => &["low", "minimal", "medium", "high"],
106 "medium" | "mid" => &["medium", "mid", "high", "low"],
107 "xhigh" => &["xhigh", "max", "high", "medium", "low"],
108 "max" | "highest" | "ultra" | "ultracode" => &["max", "xhigh", "high", "medium", "low"],
109 _ => &["high", "medium", "max", "xhigh", "low"],
110 };
111 preferences
112 .iter()
113 .copied()
114 .find(|candidate| {
115 values
116 .iter()
117 .any(|value| value.as_str() == Some(*candidate))
118 })
119 .or(Some(fallback))
120 }
121
122 pub fn apply_reasoning_effort(body: &mut Value, effort: Option<&str>, provider: ProviderKind) {
123 apply_reasoning_effort_with_options(body, effort, provider, None);
124 }
125
126 pub fn apply_reasoning_effort_with_options(
127 body: &mut Value,
128 effort: Option<&str>,
129 provider: ProviderKind,
130 reasoning_options: Option<&[Value]>,
131 ) {
132 let Some(effort) = effort else {
133 return;
134 };
135 let normalized = effort.trim().to_ascii_lowercase();
136 // DeepSeek's first-party routes read their tier ladder from the one
137 // annotated table (`client::deepseek_effort`), shared with the Responses
138 // wire, so a documented mapping change is a single edit. Every other
139 // provider keeps its own dialect below.
140 if matches!(provider, ProviderKind::Deepseek) {
141 apply_deepseek_chat_reasoning_effort(body, &normalized);
142 return;
143 }
144 if provider == ProviderKind::Stepfun {
145 let model = body.get("model").and_then(Value::as_str).unwrap_or("");
146 if let Some(tier) = stepfun_reasoning_effort(model, normalized.as_str()) {
147 body["reasoning_effort"] = json!(tier);
148 }
149 return;
150 }
151 match normalized.as_str() {
152 "off" | "disabled" | "none" | "false" => match provider {
153 // Handled by the shared DeepSeek table above, before this match.
154 ProviderKind::Deepseek => {}
155 ProviderKind::Openrouter
156 | ProviderKind::Orcarouter
157 | ProviderKind::XiaomiMimo
158 | ProviderKind::Novita
159 | ProviderKind::Siliconflow
160 | ProviderKind::SiliconflowCN
161 | ProviderKind::Sglang
162 | ProviderKind::Volcengine
163 | ProviderKind::Deepinfra
164 | ProviderKind::Together
165 | ProviderKind::Atlascloud
166 | ProviderKind::Zai => {
167 body["thinking"] = json!({ "type": "disabled" });
168 }
169 // TelecomJS TokenHub: the gateway's OpenAI Chat Completions API
170 // (POST /v1/chat/completions) does not document `reasoning_effort`
171 // or `thinking` as supported parameters. The `thinking` field is
172 // only available on the Anthropic Messages API (POST /v1/messages)
173 // with a different shape ({"type":"enabled","budget_tokens":N}).
174 // Since CodeWhale routes TelecomJS through the Chat Completions
175 // path, we must NOT inject these fields — the gateway may silently
176 // ignore them or reject the request, and not every gateway model
177 // (qwen-max, deepseek-chat, gpt-4o, claude, etc.) accepts the same
178 // reasoning dialect (#4188 review: verify against actual behavior).
179 ProviderKind::Telecomjs => {}
180 // Eden AI documents `thinking` only for Anthropic Claude models.
181 // This gateway can route unrelated model families, so the generic
182 // provider must not inject a model-specific reasoning dialect.
183 ProviderKind::Edenai => {}
184 ProviderKind::Zenmux => {}
185 // CSDN 星图 is OpenAI-compatible but documents no provider-owned
186 // reasoning dialect; do not invent one.
187 ProviderKind::Csdn => {}
188 // The Codewhale API is a passthrough to the account's own
189 // connected provider; it documents no Codewhale-owned
190 // reasoning-effort translation, so nothing is invented here.
191 ProviderKind::Codewhale => {}
192 // Concentrate rides the Responses wire (`reasoning.effort`), never
193 // these Chat Completions controls.
194 ProviderKind::Concentrate => {}
195 // Model Studio (DashScope): its top-level controls are route- AND
196 // model-specific, so the provider enum alone cannot decide them —
197 // a custom `base_url` on the same identity is an arbitrary
198 // gateway. `apply_modelstudio_route_reasoning_controls` in
199 // client::chat is the sole writer; it strips these fields for all
200 // four variants and re-adds them only on a verified Alibaba host.
201 // Source: <https://www.alibabacloud.com/help/en/model-studio/deep-thinking>
202 ProviderKind::ModelstudioTokenPlan
203 | ProviderKind::ModelstudioTokenPlanAnthropic
204 | ProviderKind::ModelstudioCodingPlan
205 | ProviderKind::ModelstudioCodingPlanAnthropic => {}
206 ProviderKind::OpenaiCodex => {
207 // OpenAI Codex uses Responses API — thinking handled differently
208 }
209 ProviderKind::Fireworks => {}
210 // vLLM is an OpenAI-protocol server, not an Anthropic-protocol one.
211 // For Qwen3 / DeepSeek-R1 / other reasoning models hosted via vLLM,
212 // the canonical OpenAI extension to disable thinking is
213 // `chat_template_kwargs.enable_thinking`. The old
214 // `thinking: {type: disabled}` field is Anthropic-native and
215 // silently ignored by vLLM — the model still emits a full
216 // reasoning trace into the `reasoning` field (which this client
217 // doesn't surface), causing 10+ seconds of perceived "freeze"
218 // before the first content token (PR #1480 by @h3c-hexin).
219 ProviderKind::Vllm => {
220 body["chat_template_kwargs"] = json!({
221 "enable_thinking": false,
222 });
223 }
224 ProviderKind::Openai
225 | ProviderKind::WanjieArk
226 | ProviderKind::Qianfan
227 | ProviderKind::Arcee
228 | ProviderKind::Huggingface
229 | ProviderKind::Modelscope
230 | ProviderKind::Custom => {}
231 ProviderKind::Moonshot => {
232 // #3024: Kimi models accept thinking enable/disable.
233 body["thinking"] = json!({ "type": "disabled" });
234 }
235 ProviderKind::Ollama => {
236 // #3024: Ollama OpenAI-compat endpoint accepts think param.
237 body["think"] = json!(false);
238 }
239 ProviderKind::OllamaCloud => {
240 // Ollama Cloud stays on the documented OpenAI-compatible
241 // `/v1/chat/completions` wire. Native `/api/chat` uses
242 // `think`; this wire uses `reasoning_effort`.
243 body["reasoning_effort"] = json!("none");
244 }
245 ProviderKind::Anthropic
246 | ProviderKind::DeepseekAnthropic
247 | ProviderKind::MinimaxAnthropic
248 | ProviderKind::Openmodel => {
249 // Thinking shaping happens in the Messages adapter, which
250 // applies each provider's supported control fields.
251 }
252 ProviderKind::NvidiaNim => {
253 body["chat_template_kwargs"] = json!({
254 "thinking": false,
255 });
256 }
257 ProviderKind::Minimax => {}
258 ProviderKind::Stepfun => {}
259 ProviderKind::Sakana => {}
260 ProviderKind::LongCat => {}
261 ProviderKind::OpencodeGo | ProviderKind::OpencodeZen => {}
262 ProviderKind::Meta => {}
263 ProviderKind::Xai => {}
264 ProviderKind::Mistral => {}
265 ProviderKind::Google => {}
266 ProviderKind::Antigravity => {}
267 },
268 "low" | "minimal" | "medium" | "mid" | "high" | "" => match provider {
269 // Handled by the shared DeepSeek table above, before this match.
270 ProviderKind::Deepseek => {}
271 // DeepSeek-compatible hosted routes: low/medium both map to high.
272 // Their own wire contracts are not verified here, so the historic
273 // collapse stays rather than inventing unsupported wire values.
274 ProviderKind::Siliconflow
275 | ProviderKind::SiliconflowCN
276 | ProviderKind::Sglang
277 | ProviderKind::Volcengine
278 | ProviderKind::Deepinfra
279 | ProviderKind::Atlascloud => {
280 body["reasoning_effort"] = json!("high");
281 body["thinking"] = json!({ "type": "enabled" });
282 }
283 // TelecomJS: see comment in the "off" branch above — the gateway's
284 // Chat Completions API does not support reasoning_effort or thinking.
285 ProviderKind::Telecomjs => {}
286 ProviderKind::Edenai => {}
287 ProviderKind::Zenmux => {}
288 // CSDN 星图 is OpenAI-compatible but documents no provider-owned
289 // reasoning dialect; do not invent one.
290 ProviderKind::Csdn => {}
291 // The Codewhale API is a passthrough to the account's own
292 // connected provider; it documents no Codewhale-owned
293 // reasoning-effort translation, so nothing is invented here.
294 ProviderKind::Codewhale => {}
295 // Concentrate rides the Responses wire (`reasoning.effort`), never
296 // these Chat Completions controls.
297 ProviderKind::Concentrate => {}
298 // Model Studio: see the "off" branch — the route- and model-aware
299 // shaper in client::chat is the sole writer of these fields.
300 ProviderKind::ModelstudioTokenPlan
301 | ProviderKind::ModelstudioTokenPlanAnthropic
302 | ProviderKind::ModelstudioCodingPlan
303 | ProviderKind::ModelstudioCodingPlanAnthropic => {}
304 // OpenRouter/OrcaRouter/Novita/Together: pass through the actual
305 // user-chosen value. OpenRouter's unified scale is
306 // none/minimal/low/medium/high/xhigh; DeepSeek models hosted there
307 // accept those directly.
308 ProviderKind::Openrouter
309 | ProviderKind::Orcarouter
310 | ProviderKind::Novita
311 | ProviderKind::Together => {
312 if let Some(value) =
313 resolved_openrouter_wire_effort(normalized.as_str(), reasoning_options)
314 {
315 body["reasoning_effort"] = json!(value);
316 }
317 body["thinking"] = json!({ "type": "enabled" });
318 }
319 ProviderKind::XiaomiMimo => {
320 body["thinking"] = json!({ "type": "enabled" });
321 }
322 ProviderKind::Arcee | ProviderKind::Huggingface | ProviderKind::Modelscope => {
323 let value = match normalized.as_str() {
324 "minimal" => "minimal",
325 "low" => "low",
326 "medium" | "mid" => "medium",
327 _ => "high",
328 };
329 body["reasoning_effort"] = json!(value);
330 }
331 ProviderKind::Fireworks => {
332 body["reasoning_effort"] = json!("high");
333 }
334 ProviderKind::Vllm => {
335 body["chat_template_kwargs"] = json!({
336 "enable_thinking": true,
337 });
338 // vLLM supports low/medium/high natively — pass through the
339 // user-chosen value instead of hard-coding "high".
340 let value = match normalized.as_str() {
341 "low" | "minimal" => "low",
342 "medium" | "mid" => "medium",
343 _ => "high",
344 };
345 body["reasoning_effort"] = json!(value);
346 }
347 ProviderKind::Openai
348 | ProviderKind::WanjieArk
349 | ProviderKind::Qianfan
350 | ProviderKind::OpenaiCodex
351 | ProviderKind::Custom => {}
352 ProviderKind::Moonshot => {
353 // #3024: Kimi models accept thinking enable.
354 body["thinking"] = json!({ "type": "enabled" });
355 }
356 ProviderKind::Ollama => {
357 // #3024: Ollama think param.
358 body["think"] = json!(true);
359 }
360 ProviderKind::OllamaCloud => {
361 let value = match normalized.as_str() {
362 "low" | "minimal" => "low",
363 "medium" | "mid" => "medium",
364 _ => "high",
365 };
366 body["reasoning_effort"] = json!(value);
367 }
368 ProviderKind::Anthropic
369 | ProviderKind::DeepseekAnthropic
370 | ProviderKind::MinimaxAnthropic
371 | ProviderKind::Openmodel => {
372 // Thinking shaping happens in the Messages adapter, which
373 // applies each provider's supported control fields.
374 }
375 ProviderKind::NvidiaNim => {
376 body["chat_template_kwargs"] = json!({
377 "thinking": true,
378 "reasoning_effort": "high",
379 });
380 }
381 ProviderKind::Minimax => {}
382 ProviderKind::Zai => {
383 body["thinking"] = json!({
384 "type": "enabled",
385 "clear_thinking": false,
386 });
387 }
388 ProviderKind::Stepfun => {}
389 ProviderKind::Sakana => {}
390 ProviderKind::LongCat => {}
391 ProviderKind::OpencodeGo | ProviderKind::OpencodeZen => {}
392 ProviderKind::Meta => {}
393 ProviderKind::Xai => {}
394 ProviderKind::Mistral => {}
395 ProviderKind::Google => {}
396 ProviderKind::Antigravity => {}
397 },
398 "xhigh" | "max" | "highest" | "ultra" | "ultracode" => match provider {
399 // Handled by the shared DeepSeek table above, before this match.
400 ProviderKind::Deepseek => {}
401 ProviderKind::Siliconflow
402 | ProviderKind::SiliconflowCN
403 | ProviderKind::Sglang
404 | ProviderKind::Volcengine
405 | ProviderKind::Deepinfra
406 | ProviderKind::Atlascloud => {
407 body["reasoning_effort"] = json!("max");
408 body["thinking"] = json!({ "type": "enabled" });
409 }
410 // TelecomJS: see comment in the "off" branch above — the gateway's
411 // Chat Completions API does not support reasoning_effort or thinking.
412 ProviderKind::Telecomjs => {}
413 ProviderKind::Edenai => {}
414 ProviderKind::Zenmux => {}
415 // CSDN 星图 is OpenAI-compatible but documents no provider-owned
416 // reasoning dialect; do not invent one.
417 ProviderKind::Csdn => {}
418 // The Codewhale API is a passthrough to the account's own
419 // connected provider; it documents no Codewhale-owned
420 // reasoning-effort translation, so nothing is invented here.
421 ProviderKind::Codewhale => {}
422 // Concentrate rides the Responses wire (`reasoning.effort`), never
423 // these Chat Completions controls.
424 ProviderKind::Concentrate => {}
425 // Model Studio: see the "off" branch — the route- and model-aware
426 // shaper in client::chat is the sole writer of these fields.
427 ProviderKind::ModelstudioTokenPlan
428 | ProviderKind::ModelstudioTokenPlanAnthropic
429 | ProviderKind::ModelstudioCodingPlan
430 | ProviderKind::ModelstudioCodingPlanAnthropic => {}
431 ProviderKind::Openrouter
432 | ProviderKind::Orcarouter
433 | ProviderKind::Novita
434 | ProviderKind::Together => {
435 if let Some(value) =
436 resolved_openrouter_wire_effort(normalized.as_str(), reasoning_options)
437 {
438 body["reasoning_effort"] = json!(value);
439 }
440 body["thinking"] = json!({ "type": "enabled" });
441 }
442 ProviderKind::XiaomiMimo => {
443 body["thinking"] = json!({ "type": "enabled" });
444 }
445 ProviderKind::Arcee | ProviderKind::Huggingface | ProviderKind::Modelscope => {
446 body["reasoning_effort"] = json!("high");
447 }
448 ProviderKind::Fireworks => {
449 body["reasoning_effort"] = json!("max");
450 }
451 ProviderKind::Vllm => {
452 body["chat_template_kwargs"] = json!({
453 "enable_thinking": true,
454 });
455 // vLLM only supports none/low/medium/high — downgrade
456 // "max" to "high" instead of sending an invalid value.
457 body["reasoning_effort"] = json!("high");
458 }
459 ProviderKind::Openai
460 | ProviderKind::WanjieArk
461 | ProviderKind::Qianfan
462 | ProviderKind::OpenaiCodex
463 | ProviderKind::Custom => {}
464 ProviderKind::Moonshot => {
465 // #3024: Kimi models accept thinking enable.
466 body["thinking"] = json!({ "type": "enabled" });
467 }
468 ProviderKind::Ollama => {
469 // #3024: Ollama think param.
470 body["think"] = json!(true);
471 }
472 ProviderKind::OllamaCloud => {
473 body["reasoning_effort"] = json!("max");
474 }
475 ProviderKind::Anthropic
476 | ProviderKind::DeepseekAnthropic
477 | ProviderKind::MinimaxAnthropic
478 | ProviderKind::Openmodel => {
479 // Thinking shaping happens in the Messages adapter, which
480 // applies each provider's supported control fields.
481 }
482 ProviderKind::NvidiaNim => {
483 body["chat_template_kwargs"] = json!({
484 "thinking": true,
485 "reasoning_effort": "max",
486 });
487 }
488 ProviderKind::Minimax => {}
489 ProviderKind::Zai => {
490 body["thinking"] = json!({
491 "type": "enabled",
492 "clear_thinking": false,
493 });
494 }
495 ProviderKind::Stepfun => {}
496 ProviderKind::Sakana => {}
497 ProviderKind::LongCat => {}
498 ProviderKind::OpencodeGo | ProviderKind::OpencodeZen => {}
499 ProviderKind::Meta => {}
500 ProviderKind::Xai => {}
501 ProviderKind::Mistral => {}
502 ProviderKind::Google => {}
503 ProviderKind::Antigravity => {}
504 },
505 _ => {}
506 }
507 }
508
508 lines RUST