-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathdiff_output.txt
More file actions
1483 lines (1459 loc) · 132 KB
/
Copy pathdiff_output.txt
File metadata and controls
1483 lines (1459 loc) · 132 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
diff --git "a/D:\\32057\\Files_of_Desktop\\Academic\\AI\\cliproxyapi\\Antigravity-Manager\\src-tauri\\src\\proxy\\mappers\\openai\\request.rs" "b/D:\\32057\\Files_of_Desktop\\Academic\\AI\\antigravity-manage\\09_intermediate_msg_fix_v3\\Antigravity-Manager\\src-tauri\\src\\proxy\\mappers\\openai\\request.rs"
index 442df2c..7911085 100644
--- "a/D:\\32057\\Files_of_Desktop\\Academic\\AI\\cliproxyapi\\Antigravity-Manager\\src-tauri\\src\\proxy\\mappers\\openai\\request.rs"
+++ "b/D:\\32057\\Files_of_Desktop\\Academic\\AI\\antigravity-manage\\09_intermediate_msg_fix_v3\\Antigravity-Manager\\src-tauri\\src\\proxy\\mappers\\openai\\request.rs"
@@ -5,6 +5,62 @@ use crate::proxy::token_manager::ProxyToken;
use serde_json::{json, Value};
+
+fn qualify_namespace_tool_name(namespace_name: &str, child_name: &str) -> String {
+ let child = child_name.trim();
+ let ns = namespace_name.trim();
+ if child.is_empty() || ns.is_empty() || child.starts_with("mcp__") {
+ return child.to_string();
+ }
+ if child.starts_with(ns) {
+ return child.to_string();
+ }
+ if ns.ends_with("__") {
+ return format!("{}{}", ns, child);
+ }
+ format!("{}__{}", ns, child)
+}
+
+fn flatten_tools(tools: &[Value]) -> Vec<Value> {
+ let mut flat = Vec::new();
+ for tool in tools {
+ let t = tool.get("type").and_then(|v| v.as_str()).unwrap_or("");
+ if t == "namespace" {
+ let namespace_name = tool.get("name").and_then(|v| v.as_str()).unwrap_or("");
+ if let Some(sub_tools) = tool.get("tools").and_then(|v| v.as_array()) {
+ let sub_flat = flatten_tools(sub_tools);
+ for mut sub_tool in sub_flat {
+ if let Some(obj) = sub_tool.as_object_mut() {
+ let mut name = String::new();
+ if let Some(n) = obj.get("name").and_then(|v| v.as_str()) {
+ name = n.to_string();
+ } else if let Some(func) = obj.get("function") {
+ if let Some(n) = func.get("name").and_then(|v| v.as_str()) {
+ name = n.to_string();
+ }
+ }
+ if !name.is_empty() {
+ let qualified = qualify_namespace_tool_name(namespace_name, &name);
+ if obj.contains_key("name") {
+ obj.insert("name".to_string(), json!(qualified));
+ }
+ if let Some(func) = obj.get_mut("function") {
+ if let Some(func_obj) = func.as_object_mut() {
+ func_obj.insert("name".to_string(), json!(qualified));
+ }
+ }
+ }
+ }
+ flat.push(sub_tool);
+ }
+ }
+ } else {
+ flat.push(tool.clone());
+ }
+ }
+ flat
+}
+
pub fn transform_openai_request(
request: &OpenAIRequest,
project_id: &str,
@@ -163,30 +219,38 @@ pub fn transform_openai_request(
// [New] 预先构建工具名称到原始 Schema 的映射,用于后续参数类型修正
let mut tool_name_to_schema = std::collections::HashMap::new();
if let Some(tools) = &request.tools {
- for tool in tools {
- if let (Some(name), Some(params)) = (
- tool.get("function")
- .and_then(|f| f.get("name"))
- .and_then(|v| v.as_str()),
- tool.get("function").and_then(|f| f.get("parameters")),
- ) {
- tool_name_to_schema.insert(name.to_string(), params.clone());
- } else if let (Some(name), Some(params)) = (
- tool.get("name").and_then(|v| v.as_str()),
- tool.get("parameters"),
- ) {
- // 处理某些客户端可能透传的精简格式
- tool_name_to_schema.insert(name.to_string(), params.clone());
+ let flat_tools = flatten_tools(tools);
+ for tool in &flat_tools {
+ let name_opt = tool.get("function")
+ .and_then(|f| f.get("name"))
+ .and_then(|v| v.as_str())
+ .map(|s| s.to_string())
+ .or_else(|| {
+ tool.get("name").and_then(|v| v.as_str()).map(|s| s.to_string())
+ })
+ .or_else(|| {
+ tool.get("type").and_then(|v| v.as_str()).map(|s| s.to_string())
+ });
+
+ let params_opt = tool.get("function")
+ .and_then(|f| f.get("parameters"))
+ .or_else(|| tool.get("parameters"));
+
+ if let (Some(name), Some(params)) = (name_opt, params_opt) {
+ tool_name_to_schema.insert(name, params.clone());
}
}
}
// 2. 构建 Gemini contents (过滤掉 system/developer 指令)
+ let total_messages = request.messages.len();
let contents: Vec<Value> = request
.messages
.iter()
- .filter(|msg| msg.role != "system" && msg.role != "developer")
- .map(|msg| {
+ .enumerate()
+ .filter(|(_, msg)| msg.role != "system" && msg.role != "developer")
+ .map(|(msg_index, msg)| {
+ let is_latest = msg_index >= total_messages.saturating_sub(4);
let role = match msg.role.as_str() {
"assistant" => "model",
"tool" | "function" => "user",
@@ -198,250 +262,547 @@ pub fn transform_openai_request(
// Handle reasoning_content (thinking)
if let Some(reasoning) = &msg.reasoning_content {
// [FIX #1506] 增强对占位符 [undefined] 的识别
- let is_valid_thinking = !reasoning.is_empty()
- && reasoning != "[undefined]"
- && reasoning != "[Thinking]"
- && !reasoning.starts_with("[Thinking Process");
-
- // 仅对 Claude 思维模型保留思维过程,Gemini/OpenAI 强制丢弃
- if is_claude_thinking && is_valid_thinking {
- parts.push(json!({"text": format!("` hinking\n{}\n`\n", reasoning)}));
+ let is_invalid_placeholder = reasoning == "[undefined]" || reasoning.is_empty();
+
+ if !is_invalid_placeholder {
+ let thought_part = json!({
+ "text": reasoning,
+ "thought": true,
+ });
+ parts.push(thought_part);
}
- }
+ } else if actual_include_thinking && role == "model" {
+ // [FIX] 解决 Claude 4.6 Thinking 模型的强制性校验:
+ // "Expected thinking... but found tool_use/text"
+ // 如果是思维模型且缺失 reasoning_content, 则注入占位符
+ tracing::debug!("[OpenAI-Thinking] Injecting placeholder thinking block for assistant message");
+ let mut thought_part = json!({
+ "text": "Applying tool decisions and generating response...",
+ "thought": true,
+ });
- // [FIX] 修复 tool_calls / function_call 的兼容性映射
- if msg.role == "assistant" && msg.tool_calls.is_some() {
- if let Some(tool_calls) = &msg.tool_calls {
- for call in tool_calls {
- let name = &call.function.name;
- // Map local_shell_call to shell for Gemini
- let final_name = if name == "local_shell_call" {
- "shell"
- } else {
- name
- };
- let raw_args = &call.function.arguments;
- let args: Value = serde_json::from_str(raw_args).unwrap_or(json!({}));
-
- // [New] 根据原始 Schema 修正参数类型
- let corrected_args = crate::proxy::mappers::common_utils::correct_argument_types(args, tool_name_to_schema.get(final_name));
-
- // 如果请求包含了 thinking 配置 (is_thinking_model 或 user_enabled_thinking)
- // 且我们能找到签名,则必须注入签名
- if actual_include_thinking {
- if let Some(sig) = thought_sig.as_ref() {
- parts.push(json!({
- "functionCall": {
- "name": final_name,
- "args": corrected_args
- },
- "thoughtSignature": sig
- }));
- tracing::debug!("[OpenAI-Request] Injected thoughtSignature into tool_call {} (sid: {})", final_name, session_id);
- } else {
- parts.push(json!({
- "functionCall": {
- "name": final_name,
- "args": corrected_args
- }
- }));
- tracing::warn!("[OpenAI-Request] No thoughtSignature available for tool_call {} in thinking model (sid: {})", final_name, session_id);
- }
- } else {
- parts.push(json!({
- "functionCall": {
- "name": final_name,
- "args": corrected_args
- }
- }));
- }
- }
+ // [FIX #1575] 占位符永远不能使用真实签名(签名与真实思考内容绑定)
+ // 仅 Gemini 支持哨兵值跳过验证
+ if is_gemini_3_thinking {
+ thought_part["thoughtSignature"] = json!("skip_thought_signature_validator");
+ thought_part["thought_signature"] = json!("skip_thought_signature_validator");
}
- } else if msg.role == "tool" || msg.role == "function" {
- // 如果是 tool 响应
- let content_str = match &msg.content {
- Some(OpenAIContent::String(s)) => s.clone(),
- Some(OpenAIContent::Array(arr)) => {
- arr.iter().filter_map(|b| {
- if let OpenAIContentBlock::Text { text } = b {
- Some(text.clone())
- } else { None }
- }).collect::<Vec<_>>().join("\n")
- },
- None => "".to_string(),
- };
-
- // 获取 Function Name
- let func_name = if let Some(name) = &msg.name {
- name.clone()
- } else if let Some(call_id) = &msg.tool_call_id {
- tool_id_to_name.get(call_id).cloned().unwrap_or_else(|| "unknown_tool".to_string())
- } else {
- "unknown_tool".to_string()
- };
- let final_func_name = if func_name == "local_shell_call" {
- "shell".to_string()
- } else {
- func_name
- };
+ parts.push(thought_part);
+ }
- parts.push(json!({
- "functionResponse": {
- "name": final_func_name,
- "response": {
- "name": final_func_name,
- "content": content_str
+ // Handle content (multimodal or text)
+ // [FIX] Skip standard content mapping for tool/function roles to avoid duplicate parts
+ // These are handled below in the "Handle tool response" section.
+ let is_tool_role = msg.role == "tool" || msg.role == "function";
+ if let (Some(content), false) = (&msg.content, is_tool_role) {
+ match content {
+ OpenAIContent::String(s) => {
+ if !s.is_empty() {
+ parts.push(json!({"text": s}));
}
}
- }));
- } else if let Some(content) = &msg.content {
- // 常规文本或多模态
- match content {
- OpenAIContent::String(s) => parts.push(json!({ "text": s })),
OpenAIContent::Array(blocks) => {
for block in blocks {
match block {
OpenAIContentBlock::Text { text } => {
- parts.push(json!({ "text": text }));
+ parts.push(json!({"text": text}));
}
OpenAIContentBlock::ImageUrl { image_url } => {
- let url = &image_url.url;
- if url.starts_with("data:image/") {
- let parts_split: Vec<&str> = url.splitn(2, ',').collect();
- if parts_split.len() == 2 {
- let meta = parts_split[0];
- let data = parts_split[1];
- let mime = meta
- .strip_prefix("data:")
- .unwrap_or(meta)
- .strip_suffix(";base64")
- .unwrap_or(meta);
+ if image_url.url.starts_with("data:") {
+ if let Some(pos) = image_url.url.find(",") {
+ let mime_part = &image_url.url[5..pos];
+ let mime_type = mime_part.split(';').next().unwrap_or("image/jpeg");
+ let data = &image_url.url[pos + 1..];
parts.push(json!({
- "inlineData": {
- "mimeType": mime,
- "data": data
- }
+ "inlineData": { "mimeType": mime_type, "data": data }
}));
}
- } else {
- tracing::warn!("Unsupported image URL format (only base64 supported for Gemini): {}", url);
- // 降级为文本占位
+ } else if image_url.url.starts_with("http") {
parts.push(json!({
- "text": format!("[Image Resource: {}]", url)
+ "fileData": { "fileUri": &image_url.url, "mimeType": "image/jpeg" }
}));
+ } else {
+ // [NEW] 处理本地文件路径 (file:// 或 Windows/Unix 路径)
+ let file_path = if image_url.url.starts_with("file://") {
+ // 移除 file:// 前缀
+ #[cfg(target_os = "windows")]
+ { image_url.url.trim_start_matches("file:///").replace('/', "\\") }
+ #[cfg(not(target_os = "windows"))]
+ { image_url.url.trim_start_matches("file://").to_string() }
+ } else {
+ image_url.url.clone()
+ };
+
+ tracing::debug!("[OpenAI-Request] Reading local image: {}", file_path);
+
+ // 读取文件并转换为 base64
+ if let Ok(file_bytes) = std::fs::read(&file_path) {
+ use base64::Engine as _;
+ let b64 = base64::engine::general_purpose::STANDARD.encode(&file_bytes);
+
+ // 根据文件扩展名推断 MIME 类型
+ let mime_type = if file_path.to_lowercase().ends_with(".png") {
+ "image/png"
+ } else if file_path.to_lowercase().ends_with(".gif") {
+ "image/gif"
+ } else if file_path.to_lowercase().ends_with(".webp") {
+ "image/webp"
+ } else {
+ "image/jpeg"
+ };
+
+ parts.push(json!({
+ "inlineData": { "mimeType": mime_type, "data": b64 }
+ }));
+ tracing::debug!("[OpenAI-Request] Successfully loaded image: {} ({} bytes)", file_path, file_bytes.len());
+ } else {
+ tracing::debug!("[OpenAI-Request] Failed to read local image: {}", file_path);
+ }
}
}
+ OpenAIContentBlock::AudioUrl { audio_url: _ } => {
+ // 暂时跳过 audio_url 处理
+ // 完整实现需要下载音频文件并转换为 Gemini inlineData 格式
+ // 这会与 v3.3.16 的 thinkingConfig 逻辑冲突,留待后续版本实现
+ tracing::debug!("[OpenAI-Request] Skipping audio_url (not yet implemented in v3.3.16)");
+ }
}
}
}
}
}
- json!({
- "role": role,
- "parts": parts
- })
- })
- .collect();
+ // Handle tool calls (assistant message)
+ if let Some(tool_calls) = &msg.tool_calls {
+ for (_index, tc) in tool_calls.iter().enumerate() {
+ /* 暂时移除:防止 Codex CLI 界面碎片化
+ if index == 0 && parts.is_empty() {
+ if mapped_model.contains("gemini-3") {
+ parts.push(json!({"text": "Thinking Process: Determining necessary tool actions."}));
+ }
+ }
+ /* 暂时移除:防止 Codex CLI 界面碎片化...
+ */
- // 构建最终请求体
- let mut inner_request = json!({
- "contents": contents
- });
+ let mut args_str = tc.function.arguments.clone();
+ if !is_latest && args_str.len() > 1000 {
+ args_str = "{\"_truncated\": \"Arguments truncated to save context window.\"}".to_string();
+ }
+ let mut args = serde_json::from_str::<Value>(&args_str).unwrap_or(json!({}));
- // Handle tools / function calling
- if let Some(tools) = &request.tools {
- let mut function_declarations = Vec::new();
- for tool in tools {
- if let Some(func) = tool.get("function") {
- let name = func.get("name").and_then(|v| v.as_str()).unwrap_or("");
- let final_name = if name == "local_shell_call" {
- "shell"
- } else {
- name
+ // [New] 利用通用引擎修正参数类型 (替代以前硬编码的 shell 工具修复逻辑)
+ if let Some(original_schema) = tool_name_to_schema.get(&tc.function.name) {
+ crate::proxy::common::json_schema::fix_tool_call_args(&mut args, original_schema);
+ }
+
+ let mut func_call_part = json!({
+ "functionCall": {
+ "name": if tc.function.name == "local_shell_call" { "shell" } else { &tc.function.name },
+ "args": args,
+ "id": &tc.id,
+ }
+ });
+
+ // [New] 递归清理参数中可能存在的非法校验字段
+ crate::proxy::common::json_schema::clean_json_schema(&mut func_call_part);
+
+ if let Some(ref sig) = thought_sig {
+ func_call_part["thoughtSignature"] = json!(sig);
+ func_call_part["thought_signature"] = json!(sig);
+ } else if is_thinking_model || is_gemini_flash_thinking {
+ // [NEW] Handle missing signature for Gemini thinking models
+ // [FIX #1650] Allow sentinel injection for Vertex AI (projects/...) as well
+ // [FIX #2167] Also applies to gemini-3-flash / gemini-3.1-flash
+ tracing::debug!("[OpenAI-Signature] Adding GEMINI_SKIP_SIGNATURE for tool_use: {}", tc.id);
+ func_call_part["thoughtSignature"] = json!("skip_thought_signature_validator");
+ func_call_part["thought_signature"] = json!("skip_thought_signature_validator");
+ }
+
+ parts.push(func_call_part);
+ }
+ }
+
+ // Handle tool response
+ if msg.role == "tool" || msg.role == "function" {
+ let name = msg.name.as_deref().unwrap_or("unknown");
+ let final_name = if name == "local_shell_call" { "shell" }
+ else if let Some(id) = &msg.tool_call_id { tool_id_to_name.get(id).map(|s| s.as_str()).unwrap_or(name) }
+ else { name };
+
+ let mut extra_parts = Vec::new();
+
+ let content_val = match &msg.content {
+ Some(OpenAIContent::String(s)) => {
+ if !is_latest && s.len() > 1000 {
+ format!("[Tool output truncated to save context. Original length: {}]", s.len())
+ } else {
+ s.clone()
+ }
+ },
+ Some(OpenAIContent::Array(blocks)) => {
+ let mut texts = Vec::new();
+ for block in blocks {
+ match block {
+ OpenAIContentBlock::Text { text } => texts.push(text.clone()),
+ OpenAIContentBlock::ImageUrl { image_url } => {
+ if image_url.url.starts_with("data:") {
+ if let Some(pos) = image_url.url.find(',') {
+ let mime_part = &image_url.url[5..pos];
+ let mime_type = mime_part.split(';').next().unwrap_or("image/jpeg");
+ let data = &image_url.url[pos + 1..];
+
+ extra_parts.push(json!({
+ "inlineData": { "mimeType": mime_type, "data": data }
+ }));
+ }
+ } else {
+ texts.push("[image link]".to_string());
+ }
+ }
+ _ => {}
+ }
+ }
+ texts.join("\n")
+ },
+ None => "".to_string()
};
- let mut decl = json!({
- "name": final_name,
- "description": func.get("description").unwrap_or(&json!(""))
- });
- if let Some(params) = func.get("parameters") {
- decl["parameters"] = params.clone();
+ parts.push(json!({
+ "functionResponse": {
+ "name": final_name,
+ "response": { "result": content_val },
+ "id": msg.tool_call_id.clone().unwrap_or_default()
+ }
+ }));
+
+ for extra in extra_parts {
+ parts.push(extra);
}
- function_declarations.push(decl);
}
- }
-
- let tool_obj = if let Some(google_search) = &config.google_search {
- if *google_search {
- json!([{
- "functionDeclarations": function_declarations
- }, {
- "googleSearch": {}
- }])
- } else {
- json!([{
- "functionDeclarations": function_declarations
- }])
+
+ json!({ "role": role, "parts": parts })
+ })
+ .filter(|msg| !msg["parts"].as_array().map(|a| a.is_empty()).unwrap_or(true))
+ .collect();
+
+ // [FIX #1575] 针对思维模型的历史故障恢复
+ // 在带有工具的历史记录中,剥离旧的思考块,防止 API 因签名失效或结构冲突报 400
+ let mut contents = contents;
+ if actual_include_thinking && has_tool_history {
+ tracing::debug!("[OpenAI-Thinking] Applied thinking recovery (stripping old thought blocks) for tool history");
+ contents = super::thinking_recovery::strip_all_thinking_blocks(contents);
+ }
+
+ // 合并连续相同角色的消息 (Gemini 强制要求 user/model 交替)
+ let mut merged_contents: Vec<Value> = Vec::new();
+ for msg in contents {
+ if let Some(last) = merged_contents.last_mut() {
+ if last["role"] == msg["role"] {
+ // 合并 parts
+ if let (Some(last_parts), Some(msg_parts)) =
+ (last["parts"].as_array_mut(), msg["parts"].as_array())
+ {
+ last_parts.extend(msg_parts.iter().cloned());
+ continue;
+ }
}
+ }
+ merged_contents.push(msg);
+ }
+ let contents = merged_contents;
+
+ // 3. 构建请求体
+
+ let mut gen_config = json!({
+ "temperature": request.temperature.unwrap_or(1.0),
+ // [CHANGED v4.1.24] Default topP from 0.95 → 1.0 to match native behavior
+ "topP": request.top_p.unwrap_or(1.0),
+ // [ADDED v4.1.24] topK=40 aligns with official client generationConfig
+ "topK": 40,
+ });
+
+ // [FIX] 移除旧的硬编码限额,改为动态查询 (v4.1.29)
+ if let Some(max_tokens) = request.max_tokens {
+ gen_config["maxOutputTokens"] = json!(max_tokens);
+ } else {
+ // 使用动态优先的规格限额
+ let limit = model_specs::get_max_output_tokens(mapped_model, token);
+ gen_config["maxOutputTokens"] = json!(limit);
+ }
+
+ // [NEW] 支持多候选结果数量 (n -> candidateCount)
+ if let Some(n) = request.n {
+ gen_config["candidateCount"] = json!(n);
+ }
+
+ // 为 thinking 模型注入 thinkingConfig (使用 thinkingBudget 而非 thinkingLevel)
+ if actual_include_thinking {
+ // [RESOLVE #1694] Check image thinking mode
+ let image_thinking_mode = crate::proxy::config::get_image_thinking_mode();
+ // Only disable if mode is explicitly "disabled" AND it's an image generation request
+ let is_image_gen_disabled =
+ config.request_type == "image_gen" && image_thinking_mode == "disabled";
+
+ if is_image_gen_disabled {
+ tracing::debug!("[OpenAI-Request] Image thinking mode disabled: enforcing includeThoughts=false for {}", mapped_model);
+ gen_config["thinkingConfig"] = json!({
+ "includeThoughts": false
+ });
} else {
- json!([{
- "functionDeclarations": function_declarations
- }])
- };
-
- inner_request["tools"] = tool_obj;
-
- // Handle tool_choice
- if let Some(tool_choice) = &request.tool_choice {
- if let Some(s) = tool_choice.as_str() {
- match s {
- "auto" => inner_request["toolConfig"] = json!({"functionCallingConfig": {"mode": "AUTO"}}),
- "none" => inner_request["toolConfig"] = json!({"functionCallingConfig": {"mode": "NONE"}}),
- "required" => inner_request["toolConfig"] = json!({"functionCallingConfig": {"mode": "ANY"}}),
- _ => {}
+ // [CONFIGURABLE] 根据配置和模型规格决定 thinking_budget (v4.1.29)
+ let tb_config = crate::proxy::config::get_thinking_budget_config();
+ // 优先使用用户在请求中传入的 budget,否则从规格表中获取默认值
+ let default_budget = model_specs::get_thinking_budget(mapped_model, token);
+ let user_budget: i64 = user_thinking_budget
+ .map(|b| b as i64)
+ .unwrap_or(default_budget as i64);
+
+ let budget = match tb_config.mode {
+ crate::proxy::config::ThinkingBudgetMode::Passthrough => user_budget,
+ crate::proxy::config::ThinkingBudgetMode::Custom => {
+ let mut custom_value = tb_config.custom_value as i64;
+ // 如果自定义值超过了模型规格上限,则进行裁剪
+ if custom_value > default_budget as i64 {
+ tracing::warn!(
+ "[OpenAI-Request] Custom budget {} exceeds model spec limit {}, capping.",
+ custom_value, default_budget
+ );
+ custom_value = default_budget as i64;
+ }
+ custom_value
}
- } else if let Some(obj) = tool_choice.as_object() {
- if let Some(func) = obj.get("function") {
- if let Some(name) = func.get("name") {
- let final_name = if name.as_str() == Some("local_shell_call") {
- json!("shell")
- } else {
- name.clone()
- };
- inner_request["toolConfig"] = json!({
- "functionCallingConfig": {
- "mode": "ANY",
- "allowedFunctionNames": [final_name]
- }
- });
+ crate::proxy::config::ThinkingBudgetMode::Auto => {
+ // Auto 模式下,直接应用规格建议的预算
+ if user_budget > default_budget as i64 {
+ default_budget as i64
+ } else {
+ user_budget
}
}
+ crate::proxy::config::ThinkingBudgetMode::Adaptive => user_budget,
+ };
+
+ gen_config["thinkingConfig"] = json!({
+ "includeThoughts": true,
+ "thinkingBudget": budget
+ });
+
+ // [CRITICAL] 思维模型的 maxOutputTokens 必须大于 thinkingBudget
+ // [FIX #1675] 针对图像模型使用更保守的 max_tokens 增量,避免触发 128k 限制
+ let overhead = if config.request_type == "image_gen" {
+ 2048
+ } else {
+ 32768
+ };
+ let min_overhead = if config.request_type == "image_gen" {
+ 1024
+ } else {
+ 8192
+ };
+
+ if let Some(max_tokens) = request.max_tokens {
+ if (max_tokens as i64) <= budget {
+ gen_config["maxOutputTokens"] = json!(budget + min_overhead);
+ }
+ } else {
+ // [FIX #1592] Use a more conservative default to avoid 400 error on 128k context models
+ gen_config["maxOutputTokens"] = json!(budget + overhead);
}
+
+ let new_max = gen_config["maxOutputTokens"].as_i64().unwrap_or(0);
+ tracing::debug!(
+ "[OpenAI-Request] Adjusted maxOutputTokens to {} for thinking model (budget={})",
+ new_max,
+ budget
+ );
+
+ tracing::debug!(
+ "[OpenAI-Request] Injected thinkingConfig for model {}: thinkingBudget={} (mode={:?})",
+ mapped_model, budget, tb_config.mode
+ );
+ }
+ }
+
+ if let Some(stop) = &request.stop {
+ if stop.is_string() {
+ gen_config["stopSequences"] = json!([stop]);
+ } else if stop.is_array() {
+ gen_config["stopSequences"] = stop.clone();
}
- } else if let Some(google_search) = &config.google_search {
- // Even if no function tools, we might need google search
- if *google_search {
- inner_request["tools"] = json!([{
- "googleSearch": {}
- }]);
+ }
+
+ if let Some(fmt) = &request.response_format {
+ if fmt.r#type == "json_object" {
+ gen_config["responseMimeType"] = json!("application/json");
}
}
- // System Instructions 注入补丁 (Antigravity ID)
- let anti_gravity_identity = "You are Antigravity, a large language model trained by Antigravity Studio.
-Knowledge cutoff: 2024-11
-Current date: 2024-12-07
+ let mut inner_request = json!({
+ "contents": contents,
+ "generationConfig": gen_config,
+ "safetySettings": [
+ { "category": "HARM_CATEGORY_HARASSMENT", "threshold": "OFF" },
+ { "category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "OFF" },
+ { "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "OFF" },
+ { "category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "OFF" },
+ { "category": "HARM_CATEGORY_CIVIC_INTEGRITY", "threshold": "OFF" },
+ ]
+ });
+
+ // 深度清理 [undefined] 字符串 (Cherry Studio 等客户端常见注入)
+ crate::proxy::mappers::common_utils::deep_clean_undefined(&mut inner_request, 0);
+
+ // 4. Handle Tools (Merged Cleaning)
+ let is_codex_style = request.model.contains("codex")
+ || request.model.contains("realtime")
+ || request.instructions.is_some()
+ || request.input.is_some();
+
+ let mut function_declarations: Vec<Value> = Vec::new();
+
+ if let Some(original_tools) = &request.tools {
+ let tools = flatten_tools(original_tools);
+ for tool in tools.iter() {
+ let mut gemini_func = if let Some(func) = tool.get("function") {
+ func.clone()
+ } else {
+ let mut func = tool.clone();
+ // [FIX] 剔除 "type" 前如果不存在 "name",则提取 "type" 兜底作为名字
+ if func.get("name").is_none() {
+ let tool_type_opt = func.get("type").and_then(|v| v.as_str()).map(|s| s.to_string());
+ if let Some(tool_type) = tool_type_opt {
+ if let Some(obj) = func.as_object_mut() {
+ obj.insert("name".to_string(), json!(tool_type));
+ }
+ }
+ }
+ if let Some(obj) = func.as_object_mut() {
+ obj.remove("type");
+ obj.remove("strict");
+ obj.remove("additionalProperties");
+ }
+ func
+ };
+
+ let name_opt = gemini_func
+ .get("name")
+ .and_then(|v| v.as_str())
+ .map(|s| s.to_string());
+
+ if let Some(name) = &name_opt {
+ // 跳过内置联网工具名称,避免重复定义
+ if name == "web_search"
+ || name == "google_search"
+ || name == "web_search_20250305"
+ || name == "builtin_web_search"
+ {
+ continue;
+ }
+
+ if name == "local_shell_call" {
+ if let Some(obj) = gemini_func.as_object_mut() {
+ obj.insert("name".to_string(), json!("shell"));
+ }
+ }
+ } else {
+ // [FIX] 如果工具没有名称,视为无效工具直接跳过 (防止 REQUIRED_FIELD_MISSING)
+ tracing::warn!(
+ "[OpenAI-Request] Skipping tool without name: {:?}",
+ gemini_func
+ );
+ continue;
+ }
-**System Guidance:**
-When the user poses a question or initiates a conversation, please start your response directly, without generic opening remarks. For example, do not begin with 'Here is...', 'Certainly!', 'I can help with that,' or similar phrases. Keep your answers concise, direct, and focused on the user's needs.
+ // [NEW CRITICAL FIX] 清除函数定义根层级的非法字段 (解决报错持久化)
+ if let Some(obj) = gemini_func.as_object_mut() {
+ obj.remove("format");
+ obj.remove("strict");
+ obj.remove("additionalProperties");
+ obj.remove("type"); // [NEW] Gemini 不支持在 FunctionDeclaration 根层级出现 type: "function"
+ obj.remove("external_web_access"); // [FIX #1278] Remove invalid field injected by OpenAI Codex
+ obj.remove("tools"); // [FIX] 删除 "tools" 字段,解决Codex中400 Unknown name "tools" 错误
+ }
+
+ if let Some(params) = gemini_func.get_mut("parameters") {
+ // [DEEP FIX] 统一调用公共库清洗:展开 $ref 并剔除所有层级的 format/definitions
+ crate::proxy::common::json_schema::clean_json_schema(params);
+
+ // Gemini v1internal 要求:
+ // 1. type 必须是大写 (OBJECT, STRING 等)
+ // 2. 根对象必须有 "type": "OBJECT"
+ if let Some(params_obj) = params.as_object_mut() {
+ if !params_obj.contains_key("type") {
+ params_obj.insert("type".to_string(), json!("OBJECT"));
+ }
+ }
-**Tone and Style:**
-Maintain a professional, straightforward, and helpful tone. Assume the user values efficiency and accuracy. Avoid conversational filler unless it adds meaningful context to the answer.
+ // 递归转换 type 为大写 (符合 Protobuf 定义)
+ enforce_uppercase_types(params);
+ } else {
+ // [FIX] 针对自定义工具 (如 apply_patch) 补全缺失的参数模式
+ // 解决 Vertex AI (Claude) 报错: tools.5.custom.input_schema: Field required
+ tracing::debug!(
+ "[OpenAI-Request] Injecting default schema for custom tool: {}",
+ gemini_func
+ .get("name")
+ .and_then(|v| v.as_str())
+ .unwrap_or("unknown")
+ );
-**Proactiveness**";
+ gemini_func.as_object_mut().unwrap().insert(
+ "parameters".to_string(),
+ json!({
+ "type": "OBJECT",
+ "properties": {
+ "content": {
+ "type": "STRING",
+ "description": "The raw content or patch to be applied"
+ }
+ },
+ "required": ["content"]
+ }),
+ );
+ }
+ function_declarations.push(gemini_func);
+ }
+ }
+
+ // Auto-inject apply_patch if in codex style and not already present
+ if is_codex_style {
+ let has_apply_patch = function_declarations.iter().any(|t| t.get("name").and_then(|v| v.as_str()) == Some("apply_patch"));
+ if !has_apply_patch {
+ function_declarations.push(json!({
+ "name": "apply_patch",
+ "description": "Apply a structured patch (diff) to create, update, or delete files in the workspace. The patch must follow the structured format starting with '*** Begin Patch' and ending with '*** End Patch'.",
+ "parameters": {
+ "type": "OBJECT",
+ "properties": {
+ "patch": {
+ "type": "STRING",
+ "description": "The patch content. Must start with '*** Begin Patch' and end with '*** End Patch'. Inside, use '*** Add File: <path>', '*** Update File: <path>' with unified diff hunk, or '*** Delete File: <path>'."
+ }
+ },
+ "required": ["patch"]
+ }
+ }));
+ }
+ }
+
+ if !function_declarations.is_empty() {
+ inner_request["tools"] = json!([{ "functionDeclarations": function_declarations }]);
+ // [ADDED v4.1.24] toolConfig VALIDATED - aligns with native behavior
+ inner_request["toolConfig"] = json!({
+ "functionCallingConfig": { "mode": "VALIDATED" }
+ });
+ }
+
+ // [NEW] Antigravity 身份指令 (原始简化版)
+ let antigravity_identity = "You are Antigravity, a powerful agentic AI coding assistant designed by the Google Deepmind team working on Advanced Agentic Coding.\n\
+ You are pair programming with a USER to solve their coding task. The task may require creating a new codebase, modifying or debugging an existing codebase, or simply answering a question.\n\
+ **Absolute paths only**\n\
+ **Proactiveness**";
// [HYBRID] 检查用户是否已提供 Antigravity 身份
let user_has_antigravity = system_instructions
@@ -450,9 +811,15 @@ Maintain a professional, straightforward, and helpful tone. Assume the user valu
let mut parts = Vec::new();
- // 2. 如果未显式声明且启用了 Antigravity Identity 补丁,则注入
- if !user_has_antigravity && config.system_instruction_patch {
- parts.push(json!({"text": anti_gravity_identity}));
+ // 1. Antigravity 身份 (如果需要, 作为独立 Part 插入)
+ if !user_has_antigravity {
+ parts.push(json!({"text": antigravity_identity}));
+ }
+
+ // 2. [NEW] 注入全局系统提示词 (紧跟 Antigravity 身份之后)
+ let global_prompt_config = crate::proxy::config::get_global_system_prompt();
+ if global_prompt_config.enabled && !global_prompt_config.content.trim().is_empty() {
+ parts.push(json!({"text": global_prompt_config.content}));
}
// 3. 追加用户指令 (作为独立 Parts)
@@ -465,51 +832,559 @@ Maintain a professional, straightforward, and helpful tone. Assume the user valu
"parts": parts
});
- // Gemini Config
- let mut gen_config = json!({});
- if let Some(temp) = request.temperature {
- gen_config["temperature"] = json!(temp);
+ if config.inject_google_search {
+ crate::proxy::mappers::common_utils::inject_google_search_tool(
+ &mut inner_request,
+ Some(mapped_model),
+ );
}
- if let Some(top_p) = request.top_p {
- gen_config["topP"] = json!(top_p);
+
+ if let Some(image_config) = config.image_config {
+ if let Some(obj) = inner_request.as_object_mut() {
+ obj.remove("tools");
+ obj.remove("systemInstruction");
+ let gen_config = obj.entry("generationConfig").or_insert_with(|| json!({}));
+ if let Some(gen_obj) = gen_config.as_object_mut() {
+ // [REMOVED] thinkingConfig 拦截已删除,允许图像生成时输出思维链
+ // gen_obj.remove("thinkingConfig");
+ gen_obj.remove("responseMimeType");
+ gen_obj.remove("responseModalities");
+ gen_obj.insert("imageConfig".to_string(), image_config);
+ }
+ }
}
- if let Some(top_k) = request.top_k {
- gen_config["topK"] = json!(top_k);
+
+ // [ADDED v4.1.24] 注入稳定 sessionId 对齐官方规范
+ if let Some(t) = token {
+ inner_request["sessionId"] = json!(crate::proxy::common::session::derive_session_id(
+ &t.account_id
+ ));
}
- if let Some(max_tokens) = request.max_tokens {
- gen_config["maxOutputTokens"] = json!(max_tokens);
- } else if let Some(max_completion_tokens) = request.max_completion_tokens {
- // [FIX] 优先使用 max_completion_tokens
- gen_config["maxOutputTokens"] = json!(max_completion_tokens);
+
+ let final_body = json!({
+ "project": project_id,
+ // [CHANGED v4.1.24] Structured requestId: agent/<session>/<turn> to match official format
+ "requestId": format!("agent/antigravity/{}/{}", &session_id[..session_id.len().min(8)], message_count),
+ "request": inner_request,
+ "model": config.final_model,
+ "userAgent": "antigravity",
+ // [CHANGED v4.1.24] Use "agent" for all non-image requests (matches official client)
+ "requestType": if config.request_type == "image_gen" { "image_gen" } else { "agent" }
+ });
+
+ (final_body, session_id, message_count)
+}
+
+fn enforce_uppercase_types(value: &mut Value) {
+ if let Value::Object(map) = value {
+ if let Some(type_val) = map.get_mut("type") {
+ if let Value::String(ref mut s) = type_val {
+ *s = s.to_uppercase();
+ }
+ }
+ if let Some(properties) = map.get_mut("properties") {
+ if let Value::Object(ref mut props) = properties {
+ for v in props.values_mut() {
+ enforce_uppercase_types(v);
+ }
+ }
+ }
+ if let Some(items) = map.get_mut("items") {
+ enforce_uppercase_types(items);
+ }
+ } else if let Value::Array(arr) = value {
+ for item in arr {
+ enforce_uppercase_types(item);
+ }
}
+}
- // Thinking Configuration
- if actual_include_thinking {
- // [NEW] 支持预算 Token
- let mut thinking_config = json!({
- "includeThoughts": true
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::proxy::mappers::openai::models::*;
+
+ #[test]
+ #[test]
+ fn test_issue_1592_gemini_3_pro_budget_capping() {
+ // [FIX #1592] Regression test for gemini-3-pro thinking budget capping
+ let req = OpenAIRequest {
+ model: "gemini-3-pro".to_string(),
+ messages: vec![OpenAIMessage {
+ role: "user".to_string(),
+ content: Some(OpenAIContent::String("test".into())),
+ reasoning_content: None,
+ tool_calls: None,
+ tool_call_id: None,
+ name: None,
+ }],
+ ..Default::default()
+ };
+
+ // Auto mode (default) should cap gemini-3-pro thinking budget to 24576
+ let (result, _sid, _msg_count) =