forked from Hmbown/Codewhale
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat.rs
More file actions
7780 lines (7302 loc) · 291 KB
/
Copy pathchat.rs
File metadata and controls
7780 lines (7302 loc) · 291 KB
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
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Chat Completions API helpers for DeepSeek's OpenAI-compatible endpoint.
//!
//! This is the production code path. Streaming (`create_message_stream`),
//! request building (`build_chat_messages*`), and SSE parsing
//! (`parse_sse_chunk_with_reasoning_style`) all live here.
use std::collections::HashMap;
use std::io::Write;
use std::pin::Pin;
use std::time::Duration;
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use tokio::time::timeout as tokio_timeout;
use crate::config::{
TOGETHER_INKLING_MODEL, is_exact_direct_moonshot_k3_route, is_exact_kimi_code_k3_route,
is_exact_xai_grok_4_6_route, is_exact_zai_chat_route, is_exact_zai_tiered_effort_route,
is_kimi_code_membership_model, minimax_m3_route_uses_max_completion_tokens,
moonshot_base_url_is_exact_kimi_code, wire_model_for_provider_route,
};
// The bounded response-header wait (`stream_open_timeout`) and its env
// override live in the shared stream-entry seam; every streaming adapter
// (Chat Completions / Anthropic Messages / Responses) uses the same policy.
use super::stream_entry::stream_open_timeout;
fn stream_idle_timeout_message(
idle: Duration,
bytes_received: usize,
stream_age: Duration,
since_last_chunk: Duration,
) -> String {
// Shared seam: Chat Completions / Anthropic / Responses keep one message shape.
super::stream_entry::idle_timeout_message(idle, bytes_received, stream_age, since_last_chunk)
}
use crate::config::ApiProvider;
use crate::llm_client::StreamEventBox;
use crate::llm_client::sanitize_http_error_body;
use crate::logging;
use codewhale_models::{
ContentBlock, ContentBlockStart, Delta, Message, MessageDelta, MessageRequest, MessageResponse,
StreamEvent, SystemPrompt, Tool, ToolCaller, Usage, is_openai_gpt_56_api_model,
model_is_openai_reasoning_family, model_supports_reasoning,
};
use super::prepared::WireDialect;
use super::role_placement::{RolePlacement, role_placement};
use super::wire::{extract_sse_data_value, flush_sse_line, take_sse_line};
use super::{
DeepSeekClient, ERROR_BODY_MAX_BYTES, SSE_BACKPRESSURE_HIGH_WATERMARK,
SSE_BACKPRESSURE_SLEEP_MS, SSE_MAX_LINES_PER_CHUNK, acquire_stream_buffer,
apply_reasoning_effort, bounded_error_text, from_api_tool_name, parse_usage,
release_stream_buffer, system_to_instructions, to_api_tool_name,
};
use codewhale_models::Role;
fn apply_provider_token_limit(
body: &mut Value,
provider: ApiProvider,
base_url: &str,
model: &str,
max_tokens: u32,
) {
let use_max_completion_tokens = provider == ApiProvider::XiaomiMimo
|| (provider == ApiProvider::Openai && model_is_openai_reasoning_family(model))
|| minimax_m3_route_uses_max_completion_tokens(provider, base_url, model)
|| is_exact_direct_moonshot_k3_route(provider, base_url, model);
if !use_max_completion_tokens {
return;
}
if let Some(object) = body.as_object_mut() {
object.remove("max_tokens");
}
body["max_completion_tokens"] = json!(max_tokens);
}
fn apply_openai_reasoning_effort(
body: &mut Value,
provider: ApiProvider,
model: &str,
effort: Option<&str>,
) {
let model_lower = model.trim().to_ascii_lowercase();
let is_gpt_56 =
provider == ApiProvider::Openai && is_openai_gpt_56_api_model(model_lower.as_str());
let is_openai_reasoning =
provider == ApiProvider::Openai && model_is_openai_reasoning_family(model);
let is_muse_spark = provider == ApiProvider::Meta
&& (model_lower == "muse-spark" || model_lower.starts_with("muse-spark-"));
if !is_openai_reasoning && !is_muse_spark {
return;
}
let Some(effort) =
effort.and_then(|value| openai_compatible_reasoning_effort(value, is_gpt_56, !is_gpt_56))
else {
return;
};
body["reasoning_effort"] = json!(effort);
}
fn apply_xai_grok_4_6_reasoning_effort(
body: &mut Value,
provider: ApiProvider,
base_url: &str,
model: &str,
effort: Option<&str>,
) {
if !(is_exact_xai_grok_4_6_route(provider, base_url, model)
|| (provider == ApiProvider::Xai
&& codewhale_config::provider::is_exact_xai_platform_route(
codewhale_config::ProviderKind::Xai,
base_url,
)
&& model
.trim()
.eq_ignore_ascii_case(crate::config::XAI_GROK_4_5_MODEL)))
{
return;
}
let Some(effort) = effort else {
return;
};
let model = model.trim().to_ascii_lowercase();
let supports_xhigh = model == crate::config::XAI_GROK_4_6_MODEL;
let supports_effort = supports_xhigh || model == crate::config::XAI_GROK_4_5_MODEL;
if !supports_effort {
return;
}
let wire_effort = match effort.trim().to_ascii_lowercase().as_str() {
"auto" | "automatic" | "" => return,
"off" | "disabled" | "none" | "false" | "high" => "high",
"minimal" | "minimum" | "low" | "light" => "low",
"medium" | "mid" => "medium",
"xhigh" | "max" | "maximum" | "highest" | "ultra" | "ultracode" => {
if supports_xhigh {
"xhigh"
} else {
"high"
}
}
_ => return,
};
body["reasoning_effort"] = json!(wire_effort);
}
fn apply_inkling_reasoning_effort(
body: &mut Value,
provider: ApiProvider,
model: &str,
effort: Option<&str>,
) {
if provider != ApiProvider::Together
|| !model.trim().eq_ignore_ascii_case(TOGETHER_INKLING_MODEL)
{
return;
}
// Inkling's official chat template accepts OpenAI's top-level
// `reasoning_effort` field with this exact vocabulary. It does not use
// Together's generic `thinking` extension or the `xhigh` wire value.
if let Some(object) = body.as_object_mut() {
object.remove("thinking");
}
let Some(effort) = effort else {
return;
};
let wire_effort = match effort.trim().to_ascii_lowercase().as_str() {
"off" | "disabled" | "none" | "false" => "none",
"minimal" => "minimal",
"low" => "low",
"medium" | "mid" | "" => "medium",
"high" => "high",
"max" | "xhigh" | "highest" | "ultra" | "ultracode" => "max",
_ => return,
};
body["reasoning_effort"] = json!(wire_effort);
}
/// Apply Kimi Code K3's route-specific nested thinking effort after the
/// generic Moonshot shaping. Other Moonshot and Kimi-compatible routes accept
/// only the generic enabled/disabled form, so the exact endpoint and bare
/// model identifier are both part of this guard.
fn apply_kimi_code_k3_reasoning_effort(
body: &mut Value,
provider: ApiProvider,
base_url: &str,
model: &str,
effort: Option<&str>,
) {
if !is_exact_kimi_code_k3_route(provider, base_url, model) {
return;
}
let Some(effort) = effort else {
return;
};
let thinking = match effort.trim().to_ascii_lowercase().as_str() {
"off" | "none" | "disabled" | "false" | "low" | "minimum" | "minimal" | "light" => {
json!({ "type": "enabled", "effort": "low" })
}
"medium" | "high" => json!({ "type": "enabled", "effort": "high" }),
"xhigh" | "ultra" | "max" => json!({ "type": "enabled", "effort": "max" }),
_ => return,
};
// K3 uses the nested `thinking.effort` dialect. Do not leave an
// OpenAI-style effort value behind if another shaping layer was added
// before this route-specific override.
if let Some(object) = body.as_object_mut() {
object.remove("reasoning_effort");
}
body["thinking"] = thinking;
}
/// Apply Moonshot's direct K3 reasoning dialect.
///
/// The pay-as-you-go K3 endpoint is always-thinking and accepts only the
/// top-level `reasoning_effort` values low/high/max. In particular, a generic
/// Moonshot `thinking: {type: disabled}` payload is not truthful for this
/// route. Treat a legacy raw `off` as the lowest supported tier defensively;
/// route-aware callers normalize it before it reaches this layer.
fn apply_direct_moonshot_k3_reasoning_effort(
body: &mut Value,
provider: ApiProvider,
base_url: &str,
model: &str,
effort: Option<&str>,
) {
if !is_exact_direct_moonshot_k3_route(provider, base_url, model) {
return;
}
if let Some(object) = body.as_object_mut() {
object.remove("thinking");
object.remove("reasoning_effort");
}
let Some(effort) = effort else {
return;
};
let wire_effort = match effort.trim().to_ascii_lowercase().as_str() {
"off" | "none" | "disabled" | "false" | "low" | "minimum" | "minimal" | "light" => "low",
"medium" | "mid" | "high" | "" => "high",
"xhigh" | "ultra" | "max" | "highest" | "ultracode" => "max",
// `auto` and unknown legacy values leave the field omitted so the
// direct API owns its documented default (`max`).
_ => return,
};
body["reasoning_effort"] = json!(wire_effort);
}
/// Keep Z.ai controls on exact first-party routes only. The tiered-effort GLM
/// models (5.2, and 5.3 which inherits its reasoning options) receive the
/// documented top-level effort, GLM-5.1 and GLM-5-Turbo keep only the generic
/// thinking toggle, and compatible gateways receive neither field because their
/// request dialect is not known from provider/model selection alone.
fn apply_zai_route_reasoning_controls(
body: &mut Value,
provider: ApiProvider,
base_url: &str,
model: &str,
effort: Option<&str>,
) {
if provider != ApiProvider::Zai {
return;
}
if let Some(object) = body.as_object_mut() {
object.remove("reasoning_effort");
if !is_exact_zai_chat_route(provider, base_url) {
// A compatible gateway owns its own request dialect. Provider/model
// selection alone is not evidence that Z.ai's `thinking` object is
// supported there, so fail closed instead of leaking it.
object.remove("thinking");
return;
}
}
if !crate::config::is_exact_known_zai_reasoning_route(provider, base_url, model) {
if let Some(object) = body.as_object_mut() {
object.remove("thinking");
}
return;
}
if !is_exact_zai_tiered_effort_route(provider, base_url, model) {
// Exact first-party GLM-5-Turbo and GLM-5.1 keep only the generic
// enabled/disabled thinking control.
return;
}
match effort
.map(|value| value.trim().to_ascii_lowercase())
.as_deref()
{
Some("high") => body["reasoning_effort"] = json!("high"),
Some("xhigh") | Some("max") | Some("highest") | Some("ultra") | Some("ultracode") => {
body["reasoning_effort"] = json!("max");
}
// Off, lower tiers, omitted effort, and unknown legacy values retain
// only the generic Z.ai thinking control.
_ => {}
}
}
/// Add MiniMax's Chat-only reasoning controls only when endpoint and model
/// prove the exact first-party M3 route. A provider label alone is not enough
/// to send MiniMax-specific fields to a compatible gateway or unknown model.
fn apply_minimax_route_reasoning_controls(
body: &mut Value,
provider: ApiProvider,
base_url: &str,
model: &str,
effort: Option<&str>,
) {
if provider != ApiProvider::Minimax {
return;
}
if let Some(object) = body.as_object_mut() {
object.remove("reasoning_split");
object.remove("thinking");
}
if !crate::config::is_exact_minimax_m3_route(provider, base_url, model) {
return;
}
body["reasoning_split"] = json!(true);
match effort
.map(|value| value.trim().to_ascii_lowercase())
.as_deref()
{
Some("off" | "disabled" | "none" | "false") => {
body["thinking"] = json!({ "type": "disabled" });
}
Some(
"low" | "minimal" | "medium" | "mid" | "high" | "xhigh" | "max" | "highest" | "ultra"
| "ultracode" | "",
) => {
body["thinking"] = json!({ "type": "adaptive" });
}
_ => {}
}
}
/// Model Studio's OpenAI-compatible API uses its own top-level reasoning
/// controls. Keep them on verified Alibaba Chat Completions routes: a custom
/// `base_url` points the same provider identity at an arbitrary gateway, and
/// that gateway must not be handed Alibaba's dialect.
///
/// This is the *sole* writer of Model Studio reasoning fields —
/// `apply_reasoning_effort` deliberately writes nothing for the `Modelstudio*`
/// identities — so the strip below runs for all four variants, including the
/// two Anthropic-dialect ones. Those normally reach the Messages adapter
/// instead, but `wire = "openai"` can route them here, and an unmatched
/// `enable_thinking` left in the body would then go out unguarded.
fn apply_modelstudio_route_reasoning_controls(
body: &mut Value,
provider: ApiProvider,
base_url: &str,
model: &str,
effort: Option<&str>,
) {
if !matches!(
provider,
ApiProvider::ModelstudioTokenPlan
| ApiProvider::ModelstudioTokenPlanAnthropic
| ApiProvider::ModelstudioCodingPlan
| ApiProvider::ModelstudioCodingPlanAnthropic
) {
return;
}
if let Some(object) = body.as_object_mut() {
object.remove("thinking");
object.remove("enable_thinking");
object.remove("preserve_thinking");
object.remove("reasoning_effort");
}
if !is_exact_modelstudio_chat_route(provider, base_url) {
return;
}
let thinking_only = modelstudio_model_is_thinking_only(model);
if !thinking_only && !modelstudio_model_is_hybrid(model) {
return;
}
let thinking_enabled = !modelstudio_effort_disables_thinking(effort);
// Thinking-only models emit `reasoning_content` but reject an
// enable/disable control. Hybrid models use `enable_thinking`.
if !thinking_only {
body["enable_thinking"] = json!(thinking_enabled);
}
if modelstudio_model_supports_preserve_thinking(model) {
// Model Studio otherwise drops assistant `reasoning_content` from the
// next turn's context. This applies even when the provider default
// leaves thinking enabled and no explicit UI effort was selected.
body["preserve_thinking"] = json!(thinking_only || thinking_enabled);
}
if !thinking_only
&& thinking_enabled
&& let Some(effort) = effort.and_then(modelstudio_reasoning_effort_for_model)
&& modelstudio_model_supports_reasoning_effort(model)
{
body["reasoning_effort"] = json!(effort);
}
}
/// Fail-closed host guard: only Alibaba's own OpenAI-compatible Chat
/// Completions URL shapes count. Anything else (a proxy, a self-hosted
/// gateway, a typo) gets the Model Studio fields stripped and nothing added.
fn is_exact_modelstudio_chat_route(provider: ApiProvider, base_url: &str) -> bool {
let trimmed = base_url.trim().trim_end_matches('/').to_ascii_lowercase();
let Some((host, path)) = trimmed
.strip_prefix("https://")
.and_then(|rest| rest.split_once('/'))
else {
return false;
};
// Includes Token Plan's default and workspace-scoped
// `{workspace}.<region>.maas.aliyuncs.com/compatible-mode/v1` hosts.
let token_plan_chat = host.ends_with(".maas.aliyuncs.com") && path == "compatible-mode/v1";
let coding_plan_chat = host == "coding-intl.dashscope.aliyuncs.com" && path == "v1";
// Alibaba's classic pay-as-you-go DashScope endpoints serve the same
// models and the same dialect; leaving them off the allowlist silently
// stripped every reasoning control on a genuine Alibaba host
// (2026-08-04 review). The intl spelling matches the repo's own
// provider defaults.
let classic_dashscope_chat = matches!(
host,
"dashscope.aliyuncs.com" | "dashscope-intl.aliyuncs.com"
) && path == "compatible-mode/v1";
match provider {
// The primary Model Studio provider selects Coding Plan through
// `mode = "coding-plan"`, which resolves this base URL without
// changing the provider enum. Legacy Coding Plan identities remain
// supported as well, so recognize either official Chat route for the
// complete Model Studio OpenAI family. The `*Anthropic` identities
// speak the Messages dialect and are never verified here.
ApiProvider::ModelstudioTokenPlan | ApiProvider::ModelstudioCodingPlan => {
token_plan_chat || coding_plan_chat || classic_dashscope_chat
}
_ => false,
}
}
fn is_exact_modelstudio_thinking_only_route(
provider: ApiProvider,
base_url: &str,
model: &str,
) -> bool {
is_exact_modelstudio_chat_route(provider, base_url) && modelstudio_model_is_thinking_only(model)
}
fn modelstudio_effort_disables_thinking(effort: Option<&str>) -> bool {
effort.is_some_and(|value| {
matches!(
value.trim().to_ascii_lowercase().as_str(),
"off" | "disabled" | "none" | "false"
)
})
}
/// Models with no enable/disable control at all. `models_dev.bundled.json`
/// lists `qwen3.8-max` as `thinking: always_on` and gives `qwen3.8-max-preview`
/// effort/budget options with no `toggle`, so sending `enable_thinking` to
/// either is at best ignored and at worst a 400.
fn modelstudio_model_is_thinking_only(model: &str) -> bool {
let model = model.trim().to_ascii_lowercase();
matches!(
model.as_str(),
"qwen3.8-max"
| "qwen3.8-max-preview"
// Kimi K2.7 Code is always-thinking. Keep both Alibaba-hosted and
// Moonshot-supplied exact IDs separate from hybrid Kimi variants
// so we never send the unsupported enable_thinking switch.
| "kimi-k2.7-code"
| "kimi/kimi-k2.7-code"
| "kimi/kimi-k2.7-code-highspeed"
)
}
fn modelstudio_model_is_hybrid(model: &str) -> bool {
let model = model.trim().to_ascii_lowercase();
model.starts_with("qwen3.7-")
|| model.starts_with("qwen3.6-")
|| model.starts_with("qwen3.5-")
|| model.starts_with("qwen3-")
|| model.starts_with("deepseek-v4")
|| model.starts_with("deepseek-v3.2")
|| model.starts_with("deepseek-v3.1")
|| model.starts_with("kimi-k2.6")
|| matches!(model.as_str(), "kimi/kimi-k2.6")
|| model.starts_with("kimi-k2.5")
|| model.starts_with("glm-")
}
fn modelstudio_model_supports_preserve_thinking(model: &str) -> bool {
let model = model.trim().to_ascii_lowercase();
matches!(
model.as_str(),
"qwen3.7-max"
| "qwen3.7-max-us"
| "qwen3.7-max-2026-05-17"
| "qwen3.7-max-2026-05-20"
| "qwen3.7-max-2026-06-08"
| "qwen3.7-max-preview"
| "qwen3.7-plus"
| "qwen3.7-plus-us"
| "qwen3.7-plus-2026-05-26"
| "qwen3.6-max-preview"
| "qwen3.6-plus"
| "qwen3.6-plus-2026-04-02"
| "qwen3.6-flash"
| "qwen3.6-flash-2026-04-16"
| "kimi-k2.6"
| "kimi-k2.7-code"
| "kimi/kimi-k2.6"
| "kimi/kimi-k2.7-code"
| "kimi/kimi-k2.7-code-highspeed"
)
}
fn modelstudio_model_supports_reasoning_effort(model: &str) -> bool {
let model = model.trim().to_ascii_lowercase();
model.starts_with("deepseek-v4") || matches!(model.as_str(), "glm-5.2" | "glm-5.1" | "glm-5")
}
fn modelstudio_reasoning_effort_for_model(effort: &str) -> Option<&'static str> {
match effort.trim().to_ascii_lowercase().as_str() {
// Model Studio documents low and medium as aliases for high.
"minimal" | "low" | "medium" | "mid" | "high" | "" => Some("high"),
"xhigh" | "max" | "highest" | "ultra" | "ultracode" => Some("max"),
_ => None,
}
}
/// Final reasoning-control pass shared by streaming and non-streaming Chat
/// Completions requests. Route-specific shapers run after the generic provider
/// layer so they can remove fields that are invalid for their exact endpoint.
pub(super) fn apply_route_reasoning_controls(
body: &mut Value,
provider: ApiProvider,
base_url: &str,
model: &str,
effort: Option<&str>,
) {
apply_reasoning_effort(body, effort, provider);
apply_modelstudio_route_reasoning_controls(body, provider, base_url, model, effort);
apply_minimax_route_reasoning_controls(body, provider, base_url, model, effort);
apply_inkling_reasoning_effort(body, provider, model, effort);
apply_openai_reasoning_effort(body, provider, model, effort);
apply_xai_grok_4_6_reasoning_effort(body, provider, base_url, model, effort);
apply_direct_moonshot_k3_reasoning_effort(body, provider, base_url, model, effort);
apply_kimi_code_k3_reasoning_effort(body, provider, base_url, model, effort);
apply_zai_route_reasoning_controls(body, provider, base_url, model, effort);
apply_mistral_route_reasoning_controls(body, provider, base_url, model, effort);
apply_google_thinking_level(body, provider, base_url, model, effort);
}
/// Mistral's polymorphic reasoning-content contract is only proven on its
/// first-party Chat Completions endpoints. A configured `mistral` provider may
/// point at an arbitrary OpenAI-compatible gateway, so provider identity alone
/// is not enough to opt that route into Mistral's request or response dialect.
fn is_exact_mistral_chat_route(provider: ApiProvider, base_url: &str) -> bool {
if provider != ApiProvider::Mistral {
return false;
}
let trimmed = base_url.trim().trim_end_matches('/').to_ascii_lowercase();
let Some((host, path)) = trimmed
.strip_prefix("https://")
.and_then(|rest| rest.split_once('/'))
else {
return false;
};
matches!(
host,
"api.mistral.ai" | "api.eu.mistral.ai" | "api.us.mistral.ai"
) && path == "v1"
}
/// Google's OpenAI-compatibility route, identified by the **resolved base
/// URL** rather than by provider identity. Thought signatures are captured
/// from tool-call `extra_content.google.thought_signature` and replayed on
/// the assistant tool-call messages of later turns; thinking models fail
/// closed when a replayed call has no signature.
///
/// The endpoint carries the signature contract, not the config row that
/// happens to name it: a manually configured `kind="openai-compatible"`
/// provider ([`ApiProvider::Custom`]) pointed at this exact host and path is
/// byte-for-byte the same endpoint as the built-in `google` row, so it must
/// preserve and replay signatures the same way. The converse still holds —
/// a `google` row pointed at some other gateway is not this route and never
/// carries Google-only fields off-endpoint.
fn is_google_openai_compat_chat_route(base_url: &str) -> bool {
let trimmed = base_url.trim().trim_end_matches('/').to_ascii_lowercase();
let Some((host, path)) = trimmed
.strip_prefix("https://")
.and_then(|rest| rest.split_once('/'))
else {
return false;
};
host == "generativelanguage.googleapis.com" && path == "v1beta/openai"
}
/// Gemini models whose thinking makes thought signatures load-bearing on
/// the OpenAI-compat route. Gemini 2.5 Flash-Lite ships with thinking off
/// by default, so a missing signature there degrades with a warning
/// instead of failing the turn.
fn google_model_requires_thought_signatures(model: &str) -> bool {
let model = model.trim().to_ascii_lowercase();
// Google names the same model both ways on this endpoint, and a route
// configured as `models/gemini-3-pro` matched none of the prefixes below:
// the model that most needs a signature looked like one that needs none,
// so the fail-closed check waved it through and Google rejected the replay
// instead (#6018).
let model = model.strip_prefix("models/").unwrap_or(&model);
if model.starts_with("gemini-3") {
return true;
}
if model.starts_with("gemini-2.5-pro") {
return true;
}
model.starts_with("gemini-2.5-flash") && !model.starts_with("gemini-2.5-flash-lite")
}
/// Thinking level for the OpenAI-compat route rides the documented
/// `google.thinking_config.thinking_level` body field (low/high; Gemini 3
/// cannot disable thinking).
fn apply_google_thinking_level(
body: &mut serde_json::Value,
_provider: ApiProvider,
base_url: &str,
_model: &str,
effort: Option<&str>,
) {
if !is_google_openai_compat_chat_route(base_url) || effort.is_none() {
return;
}
let level = match effort
.unwrap_or_default()
.trim()
.to_ascii_lowercase()
.as_str()
{
"off" | "disabled" | "none" | "false" | "" | "low" | "minimal" | "medium" | "mid" => "low",
_ => "high",
};
body["google"]["thinking_config"]["thinking_level"] = json!(level);
}
/// Fail closed before transport when Google's OpenAI-compat route would
/// replay tool calls without the thought signatures Google's thinking models
/// require. The error names the model and the tool call and tells the
/// operator how to recover instead of letting Google reject or corrupt the
/// tool loop.
///
/// Models whose thinking is off by default (Gemini 2.5 Flash-Lite) degrade
/// instead of failing — but never silently: the unsigned replay is reported
/// through the same warning path the reasoning-replay sanitizer uses, so a
/// later tool-turn failure has a receipt. Only tool-call identifiers and the
/// model id are logged; signature bytes never are.
fn validate_google_thought_signature_replay(
base_url: &str,
model: &str,
messages: &[Value],
) -> Result<()> {
if !is_google_openai_compat_chat_route(base_url) {
return Ok(());
}
let requires_signatures = google_model_requires_thought_signatures(model);
let mut unsigned_call_ids: Vec<&str> = Vec::new();
for message in messages {
let Some(tool_calls) = message.get("tool_calls").and_then(Value::as_array) else {
continue;
};
for call in tool_calls {
let missing = call
.pointer("/extra_content/google/thought_signature")
.and_then(Value::as_str)
.is_none();
if missing {
let id = call.get("id").and_then(Value::as_str).unwrap_or("?");
if requires_signatures {
anyhow::bail!(
"Gemini model `{model}` requires a thought signature to replay tool call \
`{id}`, but none was captured (the turn predates signature capture, or \
the provider omitted it). Start a new session before using tools on \
this route."
);
}
unsigned_call_ids.push(id);
}
}
}
if !unsigned_call_ids.is_empty() {
// Bounded: identifiers only, and only the first few of them.
let sample = unsigned_call_ids
.iter()
.take(3)
.copied()
.collect::<Vec<_>>()
.join(", ");
tracing::warn!(
model = %model,
unsigned_tool_calls = unsigned_call_ids.len(),
sample_tool_call_ids = %sample,
"replaying tool calls without Google thought signatures on the Gemini \
OpenAI-compatible route; later signed tool turns may be rejected"
);
}
Ok(())
}
/// Captured Google signatures ride on tool calls as
/// `extra_content.google.thought_signature`. Only Google's OpenAI-compat
/// endpoint may carry them on the wire; every other route gets them stripped
/// so a route switch never leaks Google-only fields to a foreign gateway.
///
/// Returns how many tool calls lost a signature, so the caller can report a
/// route switch that silently drops signed history instead of dropping it
/// without a receipt. Never returns or logs the signature bytes.
fn strip_google_tool_call_extra_content(messages: &mut [Value]) -> usize {
let mut stripped = 0usize;
for message in messages {
let Some(tool_calls) = message.get_mut("tool_calls").and_then(Value::as_array_mut) else {
continue;
};
for call in tool_calls {
if let Some(extra) = call.get_mut("extra_content")
&& let Some(obj) = extra.as_object_mut()
{
if obj.remove("google").is_some() {
stripped += 1;
}
if obj.is_empty() {
call.as_object_mut().map(|c| c.remove("extra_content"));
}
}
}
}
stripped
}
fn mistral_model_has_adjustable_reasoning(model: &str) -> bool {
let model = model.trim().to_ascii_lowercase();
model.starts_with("mistral-medium") || model.starts_with("mistral-small")
}
fn mistral_model_has_native_reasoning(model: &str) -> bool {
model.trim().to_ascii_lowercase().starts_with("magistral")
}
fn mistral_model_supports_reasoning(model: &str) -> bool {
mistral_model_has_adjustable_reasoning(model) || mistral_model_has_native_reasoning(model)
}
fn mistral_reasoning_effort_wire_value(effort: &str) -> Option<&'static str> {
match effort.trim().to_ascii_lowercase().as_str() {
"off" | "disabled" | "none" | "false" => Some("none"),
"high" | "xhigh" | "max" | "highest" | "ultra" | "ultracode" => Some("high"),
_ => None,
}
}
/// Rewrite assistant messages that carry `reasoning_content` back into the
/// polymorphic `content: [{type: thinking, thinking: [{type: text, text: ...}],
/// closed: bool}, {type: text, text: ...}]` shape that Mistral la Plateforme
/// emits and accepts on replay. Mistral tolerates plain-string history in a
/// thinking-capable conversation, but replaying the original thinking trace
/// keeps multi-turn reasoning quality high per the official docs
/// (docs.mistral.ai/capabilities/reasoning). Non-assistant messages and
/// assistant messages without stored thinking are left untouched.
fn reshape_mistral_messages_for_reasoning_replay(messages: &mut [Value]) {
for message in messages.iter_mut() {
let Some(object) = message.as_object_mut() else {
continue;
};
if object.get("role").and_then(Value::as_str) != Some("assistant") {
continue;
}
let Some(reasoning) = object.remove("reasoning_content") else {
continue;
};
let reasoning_text = reasoning
.as_str()
.map(str::to_string)
.filter(|s| !s.trim().is_empty());
let Some(reasoning_text) = reasoning_text else {
continue;
};
let text_content = object
.get("content")
.and_then(Value::as_str)
.map(str::to_string);
let mut blocks = vec![json!({
"type": "thinking",
"thinking": [{"type": "text", "text": reasoning_text}],
"closed": true,
})];
if let Some(text) = text_content.filter(|s| !s.trim().is_empty()) {
blocks.push(json!({"type": "text", "text": text}));
}
object.insert("content".to_string(), Value::Array(blocks));
}
}
/// Extract thinking and text content from a Mistral polymorphic `content`
/// value. Mistral la Plateforme returns `content` as either a plain string
/// (default) or an array of typed blocks (`{type: "thinking", thinking:
/// [{type: "text", text: "..."}], closed: bool}` and `{type: "text", text:
/// "..."}`). This helper flattens the thinking sub-array into a single
/// string and returns any inline text separately. It ignores plain-string
/// `content` (returns `(None, None)`) so the shared string fallback still
/// runs for non-reasoning responses.
fn extract_mistral_polymorphic_content(value: &Value) -> (Option<String>, Option<String>) {
let Some(array) = value.get("content").and_then(Value::as_array) else {
return (None, None);
};
let mut thinking = String::new();
let mut text = String::new();
for block in array {
let Some(kind) = block.get("type").and_then(Value::as_str) else {
continue;
};
match kind {
"thinking" => {
if let Some(inner) = block.get("thinking").and_then(Value::as_array) {
for sub in inner {
if let Some(sub_text) = sub
.get("text")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
{
thinking.push_str(sub_text);
}
}
} else if let Some(inline) = block
.get("thinking")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
{
thinking.push_str(inline);
}
}
"text" => {
if let Some(sub_text) = block
.get("text")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
{
text.push_str(sub_text);
}
}
_ => {}
}
}
let thinking = (!thinking.is_empty()).then_some(thinking);
let text = (!text.is_empty()).then_some(text);
(thinking, text)
}
fn apply_mistral_route_reasoning_controls(
body: &mut Value,
provider: ApiProvider,
base_url: &str,
model: &str,
effort: Option<&str>,
) {
if provider != ApiProvider::Mistral {
return;
}
if let Some(object) = body.as_object_mut() {
object.remove("thinking");
object.remove("reasoning_effort");
}
if !is_exact_mistral_chat_route(provider, base_url)
|| !mistral_model_has_adjustable_reasoning(model)
{
return;
}
let Some(effort) = effort else {
return;
};
if let Some(wire) = mistral_reasoning_effort_wire_value(effort) {
body["reasoning_effort"] = json!(wire);
}
}
/// The direct K3 Chat Completions schema exposes fixed sampling behavior and
/// omits `temperature` and `top_p`. Strip legacy/generic values only from the
/// exact first-party route so compatible gateways keep their own contract.
/// Source: <https://platform.kimi.ai/docs/guide/kimi-k3-quickstart> (verified 2026-07-20).
fn apply_direct_moonshot_k3_fixed_sampling(
body: &mut Value,
provider: ApiProvider,
base_url: &str,
model: &str,
) {
if !is_exact_direct_moonshot_k3_route(provider, base_url, model) {
return;
}
if let Some(object) = body.as_object_mut() {
object.remove("temperature");
object.remove("top_p");
}
}
/// Kimi Code's documented membership models own their sampling behavior.
/// Strip generic controls only on the exact first-party membership route;
/// custom gateways and unknown model ids retain their own wire contract.
/// Source: <https://www.kimi.com/code/docs/en/third-party-tools/codex.html>
/// (verified 2026-08-26).
fn apply_kimi_code_fixed_sampling(
body: &mut Value,
provider: ApiProvider,
base_url: &str,
model: &str,
) {
if provider != ApiProvider::Moonshot
|| !moonshot_base_url_is_exact_kimi_code(base_url)
|| !is_kimi_code_membership_model(model)
{
return;
}
if let Some(object) = body.as_object_mut() {
object.remove("temperature");
object.remove("top_p");
}
}
fn openai_compatible_reasoning_effort(
effort: &str,
supports_max: bool,
supports_minimal: bool,
) -> Option<&'static str> {
match effort.trim().to_ascii_lowercase().as_str() {
"off" | "disabled" | "none" | "false" => Some("none"),
"minimal" if supports_minimal => Some("minimal"),
"minimal" => Some("low"),
"low" => Some("low"),
"medium" | "mid" | "" => Some("medium"),
"high" => Some("high"),
"xhigh" => Some("xhigh"),
"max" | "highest" | "ultra" | "ultracode" if supports_max => Some("max"),
"max" | "highest" | "ultra" | "ultracode" => Some("xhigh"),
_ => None,
}
}
fn mirror_minimax_reasoning_details_for_messages(messages: &mut [Value]) {
for message in messages {
if message.get("role").and_then(Value::as_str) != Some("assistant") {
continue;
}
if message.get("reasoning_details").is_some() {
continue;
}
let Some(reasoning) = message
.get("reasoning_content")
.and_then(Value::as_str)
.filter(|reasoning| !reasoning.trim().is_empty())
.map(str::to_string)
else {
continue;
};
message["reasoning_details"] = json!([
{
"type": "text",
"text": reasoning,
}
]);
}
}
fn mirror_minimax_reasoning_details_for_body(body: &mut Value, provider: ApiProvider) {
if provider != ApiProvider::Minimax {
return;
}
let Some(messages) = body.get_mut("messages").and_then(Value::as_array_mut) else {
return;
};
mirror_minimax_reasoning_details_for_messages(messages);
}
/// Sanitize every Moonshot chat tool in place, dropping only the tools whose
/// parameters cannot pass MFJS compatibility validation.
///
/// Per-tool degradation: a single incompatible tool (e.g. a third-party MCP
/// server whose schema uses keywords outside the MFJS whitelist) is excluded
/// from this request with a warning instead of failing the whole request
/// before transport. The tool name is safe to log — it is already visible in
/// the UI — while the error's `Display` deliberately carries no schema values.
///
/// Returns the names of the dropped tools, in catalog order.
fn sanitize_moonshot_chat_tools(chat_tools: &mut Vec<Value>) -> Vec<String> {
let mut dropped = Vec::new();
chat_tools.retain_mut(|tool| {