-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathopenai_provider.cpp
More file actions
1753 lines (1609 loc) · 70.8 KB
/
Copy pathopenai_provider.cpp
File metadata and controls
1753 lines (1609 loc) · 70.8 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
#include "openai_provider.hpp"
#include "dsml_tool_call_recovery.hpp"
#include "session/session_history_recovery.hpp"
#include "image/image_processor.hpp"
#include "config/request_headers.hpp"
#include "session/attachment_prompt_context.hpp"
#include "session/attachment_store.hpp"
#include "utils/logger.hpp"
#include "utils/base64.hpp"
#include "utils/sha1.hpp"
#include "network/proxy_resolver.hpp"
#include <cpr/cpr.h>
#include <cpr/ssl_options.h>
#include <stdexcept>
#include <sstream>
#include <optional>
#include <map>
#include <limits>
#include <unordered_set>
#include <algorithm>
#include <chrono>
#include <cctype>
#include <utility>
#include <vector>
namespace acecode {
OpenAiCompatProvider::OpenAiCompatProvider(const std::string& base_url,
const std::string& api_key,
const std::string& model,
int stream_timeout_ms,
std::map<std::string, std::string> request_headers,
ProviderRequestOptions request_options)
: base_url_(normalize_endpoint(base_url, request_options.endpoint_mode)),
api_key_(api_key),
model_(model),
request_headers_(std::move(request_headers)),
request_options_(std::move(request_options)),
stream_timeout_ms_(stream_timeout_ms > 0
? stream_timeout_ms
: OpenAiConfig::kDefaultStreamTimeoutMs) {}
namespace {
constexpr int kStreamConnectTimeoutCapMs = 15000;
std::int64_t steady_now_ms() {
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count();
}
std::string ascii_lower(std::string value) {
std::transform(value.begin(), value.end(), value.begin(), [](unsigned char c) {
return static_cast<char>(std::tolower(c));
});
return value;
}
std::string provider_error_kind_to_string(ProviderErrorKind kind) {
switch (kind) {
case ProviderErrorKind::None: return "none";
case ProviderErrorKind::UserCancelled:return "user_cancelled";
case ProviderErrorKind::Timeout: return "timeout";
case ProviderErrorKind::Network: return "network";
case ProviderErrorKind::Http: return "http";
case ProviderErrorKind::MalformedSse: return "malformed_sse";
case ProviderErrorKind::MalformedJson:return "malformed_json";
case ProviderErrorKind::Unknown: return "unknown";
}
return "unknown";
}
std::string synthesize_tool_call_id(int index,
const std::string& name,
const std::string& arguments) {
std::string fingerprint = std::to_string(index);
fingerprint.push_back('\n');
fingerprint.append(name);
fingerprint.push_back('\n');
fingerprint.append(arguments);
return "call_ace_" + sha1_hex(fingerprint).substr(0, 24);
}
std::string json_string_or_empty(const nlohmann::json& value, const char* key) {
if (!value.is_object() || !value.contains(key) || !value[key].is_string()) {
return {};
}
return value[key].get<std::string>();
}
std::vector<ToolDef> request_tool_defs(const nlohmann::json& body) {
std::vector<ToolDef> tools;
if (!body.contains("tools") || !body["tools"].is_array()) return tools;
for (const auto& item : body["tools"]) {
if (!item.is_object() || !item.contains("function") ||
!item["function"].is_object()) {
continue;
}
const auto& function = item["function"];
const std::string name = json_string_or_empty(function, "name");
if (name.empty()) continue;
ToolDef tool;
tool.name = name;
tools.push_back(std::move(tool));
}
return tools;
}
std::optional<std::size_t> find_complete_json_prefix_end(const std::string& value) {
std::size_t i = 0;
while (i < value.size() &&
std::isspace(static_cast<unsigned char>(value[i]))) {
++i;
}
if (i >= value.size()) return std::nullopt;
const char first = value[i];
if (first != '{' && first != '[') return std::nullopt;
std::vector<char> stack;
bool in_string = false;
bool escaped = false;
for (; i < value.size(); ++i) {
const char c = value[i];
if (in_string) {
if (escaped) {
escaped = false;
} else if (c == '\\') {
escaped = true;
} else if (c == '"') {
in_string = false;
}
continue;
}
if (c == '"') {
in_string = true;
continue;
}
if (c == '{') {
stack.push_back('}');
continue;
}
if (c == '[') {
stack.push_back(']');
continue;
}
if (c == '}' || c == ']') {
if (stack.empty() || stack.back() != c) return std::nullopt;
stack.pop_back();
if (stack.empty()) return i + 1;
}
}
return std::nullopt;
}
std::string normalize_tool_call_arguments_for_request(
const std::string& arguments,
const std::string& tool_name,
const std::string& tool_call_id,
int& repaired_count) {
auto parsed = nlohmann::json::parse(arguments, nullptr, false);
if (!parsed.is_discarded()) return arguments;
if (auto prefix_end = find_complete_json_prefix_end(arguments)) {
std::string suffix = arguments.substr(*prefix_end);
const bool trailing_garbage = std::any_of(
suffix.begin(), suffix.end(), [](unsigned char c) {
return !std::isspace(c);
});
if (trailing_garbage) {
auto prefix = nlohmann::json::parse(
arguments.substr(0, *prefix_end), nullptr, false);
if (!prefix.is_discarded()) {
++repaired_count;
LOG_WARN("build_request_body: trimmed invalid trailing bytes from "
"tool_call arguments id='" + tool_call_id + "' tool='" +
tool_name + "' raw=" + log_truncate(arguments, 200));
return prefix.dump();
}
}
}
++repaired_count;
LOG_WARN("build_request_body: replaced invalid tool_call arguments with {} "
"id='" + tool_call_id + "' tool='" + tool_name +
"' raw=" + log_truncate(arguments, 200));
return "{}";
}
nlohmann::json normalize_tool_calls_for_request(const nlohmann::json& tool_calls,
int& repaired_count,
int& dropped_malformed_count) {
nlohmann::json tool_call_items;
if (tool_calls.is_array()) {
tool_call_items = tool_calls;
} else if (tool_calls.is_object()) {
tool_call_items = nlohmann::json::array({tool_calls});
} else {
return nlohmann::json::array();
}
nlohmann::json out = nlohmann::json::array();
std::unordered_set<std::string> emitted_ids;
for (const auto& raw_tc : tool_call_items) {
if (!raw_tc.is_object()) {
++dropped_malformed_count;
LOG_WARN("build_request_body: dropped malformed tool_call (not object)");
continue;
}
std::string tool_call_id;
if (raw_tc.contains("id") && raw_tc["id"].is_string()) {
tool_call_id = raw_tc["id"].get<std::string>();
}
if (tool_call_id.empty()) {
++dropped_malformed_count;
LOG_WARN("build_request_body: dropped malformed tool_call with empty id");
continue;
}
if (emitted_ids.count(tool_call_id)) {
++dropped_malformed_count;
LOG_WARN("build_request_body: dropped duplicate tool_call id='" +
tool_call_id + "'");
continue;
}
if (!raw_tc.contains("function") || !raw_tc["function"].is_object()) {
++dropped_malformed_count;
LOG_WARN("build_request_body: dropped malformed tool_call without function "
"id='" + tool_call_id + "'");
continue;
}
nlohmann::json tc = raw_tc;
if (!tc.contains("type") || !tc["type"].is_string() ||
tc["type"].get<std::string>().empty()) {
tc["type"] = "function";
++repaired_count;
LOG_WARN("build_request_body: inserted missing tool_call type=function "
"id='" + tool_call_id + "'");
}
auto& fn = tc["function"];
std::string tool_name;
if (fn.contains("name") && fn["name"].is_string()) {
tool_name = fn["name"].get<std::string>();
}
if (tool_name.empty()) {
++dropped_malformed_count;
LOG_WARN("build_request_body: dropped malformed tool_call without function.name "
"id='" + tool_call_id + "'");
continue;
}
if (fn.contains("arguments") && fn["arguments"].is_string()) {
fn["arguments"] = normalize_tool_call_arguments_for_request(
fn["arguments"].get<std::string>(),
tool_name,
tool_call_id,
repaired_count);
} else {
++repaired_count;
LOG_WARN("build_request_body: inserted missing tool_call arguments {} "
"id='" + tool_call_id + "' tool='" + tool_name + "'");
fn["arguments"] = "{}";
}
out.push_back(std::move(tc));
emitted_ids.insert(tool_call_id);
}
return out;
}
std::string system_message_content_for_request(const nlohmann::json& message) {
if (!message.is_object() || !message.contains("content")) return {};
const auto& content = message["content"];
if (content.is_null()) return {};
if (content.is_string()) return content.get<std::string>();
if (!content.is_array()) return content.dump();
std::ostringstream oss;
bool first = true;
for (const auto& part : content) {
std::string text;
if (part.is_object() && part.value("type", std::string{}) == "text" &&
part.contains("text") && part["text"].is_string()) {
text = part["text"].get<std::string>();
} else if (part.is_string()) {
text = part.get<std::string>();
} else if (!part.is_null()) {
text = part.dump();
}
if (text.empty()) continue;
if (!first) oss << "\n\n";
first = false;
oss << text;
}
return oss.str();
}
nlohmann::json coalesce_system_messages_at_front(const nlohmann::json& messages,
int& moved_count,
int& merged_count) {
std::vector<nlohmann::json> system_messages;
std::vector<nlohmann::json> non_system_messages;
bool seen_non_system = false;
for (const auto& message : messages) {
if (message.is_object() && message.value("role", std::string{}) == "system") {
if (seen_non_system) {
++moved_count;
}
system_messages.push_back(message);
continue;
}
seen_non_system = true;
non_system_messages.push_back(message);
}
if (system_messages.empty() ||
(system_messages.size() == 1 && moved_count == 0)) {
return messages;
}
std::string combined_content;
for (const auto& system_message : system_messages) {
const std::string content = system_message_content_for_request(system_message);
if (content.empty()) continue;
if (!combined_content.empty()) combined_content += "\n\n";
combined_content += content;
}
nlohmann::json normalized = nlohmann::json::array();
normalized.push_back(nlohmann::json{
{"role", "system"},
{"content", combined_content},
});
for (auto& message : non_system_messages) {
normalized.push_back(std::move(message));
}
merged_count += static_cast<int>(system_messages.size()) - 1;
return normalized;
}
bool parse_json_body(const std::string& body,
bool& body_is_json,
std::string& pretty_json) {
body_is_json = false;
pretty_json.clear();
if (body.empty()) return false;
try {
const auto parsed = nlohmann::json::parse(body);
pretty_json = parsed.dump(2);
body_is_json = true;
return true;
} catch (const nlohmann::json::parse_error&) {
return false;
}
}
std::string json_scalar_to_string(const nlohmann::json& value) {
if (value.is_string()) return value.get<std::string>();
if (value.is_number_integer()) return std::to_string(value.get<long long>());
if (value.is_number_unsigned()) return std::to_string(value.get<unsigned long long>());
if (value.is_boolean()) return value.get<bool>() ? "true" : "false";
if (value.is_null()) return {};
return value.dump();
}
std::string first_string_field(const nlohmann::json& object,
std::initializer_list<const char*> keys) {
if (!object.is_object()) return {};
for (const char* key : keys) {
auto it = object.find(key);
if (it != object.end() && it->is_string()) {
std::string value = it->get<std::string>();
if (!value.empty()) return value;
}
}
return {};
}
int parse_http_status_int(long long value) {
return value >= 100 && value <= 599 ? static_cast<int>(value) : 0;
}
int parse_http_status_text(const std::string& text) {
if (text.empty()) return 0;
std::string lower = ascii_lower(text);
for (const std::string& marker : {
std::string("error code"),
std::string("status code"),
std::string("http status"),
std::string("http "),
}) {
size_t pos = lower.find(marker);
if (pos == std::string::npos) continue;
pos += marker.size();
while (pos < lower.size() && !std::isdigit(static_cast<unsigned char>(lower[pos]))) {
++pos;
}
long long status = 0;
int digits = 0;
while (pos < lower.size() && std::isdigit(static_cast<unsigned char>(lower[pos])) && digits < 3) {
status = status * 10 + (lower[pos] - '0');
++pos;
++digits;
}
if (digits == 3) {
int parsed = parse_http_status_int(status);
if (parsed > 0) return parsed;
}
}
return 0;
}
int http_status_from_json_field(const nlohmann::json& object,
std::initializer_list<const char*> keys) {
if (!object.is_object()) return 0;
for (const char* key : keys) {
auto it = object.find(key);
if (it == object.end() || it->is_null()) continue;
if (it->is_number_integer()) {
int parsed = parse_http_status_int(it->get<long long>());
if (parsed > 0) return parsed;
}
if (it->is_number_unsigned()) {
const auto value = it->get<unsigned long long>();
if (value <= 599) {
int parsed = parse_http_status_int(static_cast<long long>(value));
if (parsed > 0) return parsed;
}
}
if (it->is_string()) {
int parsed = parse_http_status_text(it->get<std::string>());
if (parsed > 0) return parsed;
}
}
return 0;
}
bool has_stream_error_payload(const nlohmann::json& j) {
auto it = j.find("error");
if (it == j.end() || it->is_null()) return false;
if (it->is_boolean()) return it->get<bool>();
if (it->is_string()) return !it->get<std::string>().empty();
if (it->is_object() || it->is_array()) return !it->empty();
return true;
}
std::string stream_error_message_from_payload(const nlohmann::json& j) {
auto it = j.find("error");
if (it == j.end()) return {};
const auto& error = *it;
if (error.is_string()) return error.get<std::string>();
if (error.is_object()) {
std::string message = first_string_field(error, {"message", "detail", "error_description"});
std::string type = first_string_field(error, {"type", "code"});
if (!message.empty() && !type.empty()) return type + ": " + message;
if (!message.empty()) return message;
if (!type.empty()) return type;
}
return json_scalar_to_string(error);
}
int stream_error_status_from_payload(const nlohmann::json& j,
const std::string& message) {
int status = http_status_from_json_field(
j, {"status_code", "status", "http_status", "error_code"});
if (status > 0) return status;
auto it = j.find("error");
if (it != j.end() && it->is_object()) {
status = http_status_from_json_field(
*it, {"status_code", "status", "http_status", "error_code", "code"});
if (status > 0) return status;
}
return parse_http_status_text(message);
}
std::string header_value_ci(const cpr::Header& headers, const std::string& key) {
const std::string wanted = ascii_lower(key);
for (const auto& [header_key, value] : headers) {
if (ascii_lower(header_key) == wanted) return value;
}
return {};
}
std::string extract_request_id(const cpr::Header& headers) {
for (const std::string& key : {
"x-request-id",
"request-id",
"x-github-request-id",
"x-ms-request-id",
"cf-ray",
}) {
std::string value = header_value_ci(headers, key);
if (!value.empty()) return value;
}
return {};
}
bool is_retryable_http_status(int status_code, const std::string& body) {
return provider_http_error_is_retryable(status_code, body);
}
ProviderErrorKind classify_cpr_error(const cpr::Error& error) {
if (error.code == cpr::ErrorCode::OPERATION_TIMEDOUT) {
return ProviderErrorKind::Timeout;
}
const std::string message = ascii_lower(error.message);
if (message.find("timed out") != std::string::npos ||
message.find("timeout") != std::string::npos) {
return ProviderErrorKind::Timeout;
}
return ProviderErrorKind::Network;
}
std::string provider_error_prefix(ProviderErrorKind kind, int status_code) {
switch (kind) {
case ProviderErrorKind::UserCancelled:
return "Request cancelled";
case ProviderErrorKind::Timeout:
return "Request timed out";
case ProviderErrorKind::Network:
return "Connection failed";
case ProviderErrorKind::Http:
return "HTTP " + std::to_string(status_code);
case ProviderErrorKind::MalformedJson:
return "Malformed JSON in streaming response";
case ProviderErrorKind::MalformedSse:
return "Malformed or incomplete streaming response";
case ProviderErrorKind::Unknown:
return "Provider request failed";
case ProviderErrorKind::None:
return {};
}
return "Provider request failed";
}
ProviderErrorInfo make_provider_error(ProviderErrorKind kind,
int status_code,
const std::string& provider,
const std::string& model,
const std::string& request_id,
const std::string& raw_body,
const std::string& transport_message,
bool retryable) {
ProviderErrorInfo info;
info.kind = kind;
info.status_code = status_code;
info.provider = provider;
info.model = model;
info.request_id = request_id;
info.raw_body = raw_body;
info.retryable = retryable;
parse_json_body(raw_body, info.body_is_json, info.pretty_json);
if (kind == ProviderErrorKind::UserCancelled) {
info.display_message = "Request cancelled";
return info;
}
std::ostringstream display;
display << provider_error_prefix(kind, status_code);
if (!provider.empty()) display << " from " << provider;
if (!model.empty()) display << " model " << model;
if (!request_id.empty()) display << " request_id=" << request_id;
if (!transport_message.empty()) display << ": " << transport_message;
const std::string body_for_display = info.body_is_json ? info.pretty_json : raw_body;
if (!body_for_display.empty()) {
display << "\n" << body_for_display;
}
info.display_message = display.str();
return info;
}
ChatResponse make_chat_error_response(ProviderErrorInfo info) {
ChatResponse response;
response.content = "[Error] " + info.display_message;
response.finish_reason = "error";
response.provider_error = std::move(info);
return response;
}
void emit_provider_error(const StreamCallback& callback, const ProviderErrorInfo& info) {
StreamEvent evt;
evt.type = StreamEventType::Error;
evt.error = info.display_message;
evt.provider_error = info;
callback(evt);
}
void emit_retry_event(const StreamCallback& callback, ProviderErrorInfo info) {
StreamEvent evt;
evt.type = StreamEventType::Retry;
evt.provider_error = std::move(info);
evt.error = evt.provider_error.display_message;
callback(evt);
}
void emit_retry_resume_event(const StreamCallback& callback,
const ProviderErrorInfo& info) {
StreamEvent evt;
evt.type = StreamEventType::RetryResume;
evt.provider_error = info;
callback(evt);
}
int retry_after_delay_ms(const cpr::Header& headers,
std::uint64_t retry_number) {
std::optional<std::int64_t> server_delay;
const std::string retry_after = header_value_ci(headers, "retry-after");
if (!retry_after.empty()) {
server_delay = parse_retry_after_ms(retry_after);
}
return static_cast<int>(
provider_retry_delay_ms(retry_number, server_delay));
}
void push_openai_text_part(nlohmann::json& parts, const std::string& text) {
if (text.empty()) return;
parts.push_back(nlohmann::json{{"type", "text"}, {"text", text}});
}
// 判定一条附件是否应当作为 provider 图片 part 发送。以 MIME 为权威依据:
// SVG(矢量 XML)被排除,误标成 image 但 MIME 非图片的附件返回 false,从而
// 在序列化层兜底降级为文件句柄(route-attachments-by-capability D3)。
bool record_is_vision_image(const AttachmentRecord& record) {
const std::string mime =
ascii_lower(attachment_mime_for_name(record.name, record.mime_type));
if (mime == "image/svg+xml") return false;
return mime.rfind("image/", 0) == 0;
}
// 非视觉模型收到图片时的聚合 fallback 文本(tasks 1.9)。多张图合并成一段简短
// 句柄列表,并按系统是否还有可用视觉模型给出不同引导。
std::string gated_image_fallback_text(const std::vector<AttachmentRecord>& images,
bool any_vision_model_available) {
std::ostringstream oss;
oss << "[Image attachment(s) not sent: the active model cannot inspect images]";
for (const auto& record : images) {
oss << "\n- " << record.name << " (" << record.mime_type << ", "
<< record.size_bytes << " bytes";
if (!record.id.empty()) oss << ", attachment_id=" << record.id;
oss << ")";
}
if (any_vision_model_available) {
oss << "\nUse the vision_analyze tool (pass attachment_id or image_path) to "
"inspect the image(s) with a vision-capable model.";
} else {
oss << "\nNo saved model is tagged with the 'vision' capability, so the "
"image(s) cannot be analyzed. Configure a saved model with the vision "
"capability to enable image analysis.";
}
return oss.str();
}
} // namespace
nlohmann::json openai_content_for_message(const ChatMessage& msg,
bool model_has_vision,
bool any_vision_model_available) {
if (msg.content_parts.is_null() || !msg.content_parts.is_array() ||
msg.content_parts.empty()) {
return msg.content;
}
nlohmann::json parts = nlohmann::json::array();
bool saw_text_part = false;
// 被能力 gate 剥掉的图片附件,循环结束后聚合成一段句柄文本(tasks 1.9)。
std::vector<AttachmentRecord> gated_images;
for (const auto& part : msg.content_parts) {
if (!part.is_object()) continue;
const std::string type = part.value("type", std::string{});
if (type == "text") {
const std::string text = part.value("text", std::string{});
if (!text.empty()) {
saw_text_part = true;
push_openai_text_part(parts, text);
}
continue;
}
if (type == "image") {
auto record = part.contains("attachment")
? attachment_from_json(part["attachment"])
: std::optional<AttachmentRecord>{};
if (!record.has_value()) {
push_openai_text_part(parts, "[Attached image unavailable: invalid metadata]");
continue;
}
// D3 兜底:误标成 image 的非图片(含 SVG)按文件句柄处理,绝不发图片 payload。
if (!record_is_vision_image(*record)) {
push_openai_text_part(
parts, file_attachment_reference_text(*record));
continue;
}
// D2/D5 能力 gate:active 模型不能看图时,聚合成 fallback 句柄文本而非发图。
if (!model_has_vision) {
gated_images.push_back(*record);
continue;
}
std::string error;
auto bytes = read_attachment_bytes(*record, kMaxAttachmentBytes, &error);
if (!bytes.has_value()) {
push_openai_text_part(parts,
"[Attached image unavailable: " +
(error.empty() ? record->name : error) + "]");
continue;
}
std::string provider_mime = record->mime_type;
std::string provider_bytes = *bytes;
auto normalized = image::normalize_image_bytes(provider_bytes, provider_mime);
if (normalized.attempted) {
LOG_INFO("[provider] image normalization"
" name=" + record->name +
" ok=" + std::string(normalized.ok ? "1" : "0") +
" changed=" + std::string(normalized.changed ? "1" : "0") +
" original_size=" + std::to_string(bytes->size()) +
" reason=" + normalized.reason +
" error=" + normalized.error);
if (normalized.ok && normalized.changed) {
provider_bytes = std::move(normalized.bytes);
if (!normalized.mime_type.empty()) {
provider_mime = normalized.mime_type;
}
} else if (!normalized.ok) {
push_openai_text_part(parts,
"[Attached image unavailable: image normalization failed: " +
(normalized.error.empty() ? normalized.reason : normalized.error) + "]");
continue;
}
}
parts.push_back(nlohmann::json{
{"type", "image_url"},
{"image_url", {
{"url", "data:" + provider_mime + ";base64," +
base64_encode(provider_bytes)}
}},
});
continue;
}
if (type == "file") {
auto record = part.contains("attachment")
? attachment_from_json(part["attachment"])
: std::optional<AttachmentRecord>{};
push_openai_text_part(parts, record.has_value()
? file_attachment_reference_text(*record)
: std::string{"[Attached file unavailable: invalid metadata]"});
continue;
}
if (type == "browser_context") {
const auto ctx = part.contains("context") ? part["context"] : nlohmann::json::object();
push_openai_text_part(parts, "[Browser context]\n" + ctx.dump(2));
}
}
if (!gated_images.empty()) {
saw_text_part = true;
push_openai_text_part(parts,
gated_image_fallback_text(gated_images, any_vision_model_available));
}
if (!saw_text_part && !msg.content.empty()) {
parts.insert(parts.begin(), nlohmann::json{{"type", "text"}, {"text", msg.content}});
}
return parts.empty() ? nlohmann::json(msg.content) : parts;
}
nlohmann::json OpenAiCompatProvider::build_request_body(
const std::vector<ChatMessage>& messages,
const std::vector<ToolDef>& tools,
bool stream
) const {
nlohmann::json body;
body["model"] = model_;
if (stream) {
body["stream"] = true;
body["stream_options"] = {{"include_usage", true}};
}
if (request_options_.max_output_tokens.has_value()) {
body["max_tokens"] = *request_options_.max_output_tokens;
}
if (request_options_.reasoning_protocol == ReasoningWireProtocol::OpenRouter &&
request_options_.reasoning.has_value() &&
request_options_.reasoning->supported) {
const auto& reasoning = *request_options_.reasoning;
const bool enabled = reasoning.mandatory ||
reasoning.enabled.value_or(reasoning.default_enabled);
nlohmann::json wire_reasoning = nlohmann::json::object();
if (!enabled) {
wire_reasoning["effort"] = "none";
} else if (reasoning.max_tokens.has_value()) {
// OpenRouter documents effort and max_tokens as alternative controls.
// An explicit token budget is more precise and therefore wins.
wire_reasoning["max_tokens"] = *reasoning.max_tokens;
} else {
const auto effort = reasoning.effort.has_value()
? reasoning.effort
: reasoning.default_effort;
if (effort.has_value()) {
wire_reasoning["effort"] = *effort;
} else {
wire_reasoning["enabled"] = true;
}
}
body["reasoning"] = std::move(wire_reasoning);
}
// Build messages array.
// 最后一道防御:OpenAI/Ark 严格要求 role ∈ {system,user,assistant,tool}。
// 任何非法 role(例如历史遗留的 UI-only `tool_result`)在此直接丢弃并 warn,
// 防止 resume/压缩/旧 session 等路径意外污染 messages_ 时把整个请求打挂。
nlohmann::json msgs_json = nlohmann::json::array();
int dropped_invalid_role = 0;
int repaired_tool_arguments = 0;
int dropped_malformed_tool_calls = 0;
int dropped_empty_assistant_tool_messages = 0;
const auto recovered_history = recover_provider_history(messages);
for (const auto& msg : recovered_history.messages) {
const bool valid_role = (msg.role == "system" || msg.role == "user" ||
msg.role == "assistant" || msg.role == "tool");
if (!valid_role) {
++dropped_invalid_role;
LOG_WARN("build_request_body: dropping message with invalid role='" +
msg.role + "' content=" + log_truncate(msg.content, 200));
continue;
}
nlohmann::json m;
m["role"] = msg.role;
if (msg.role == "assistant" && !msg.tool_calls.is_null() && !msg.tool_calls.empty()) {
nlohmann::json normalized_tool_calls = normalize_tool_calls_for_request(
msg.tool_calls, repaired_tool_arguments, dropped_malformed_tool_calls);
if (!normalized_tool_calls.empty()) {
// Assistant message with tool calls
if (!msg.content.empty()) {
m["content"] = msg.content;
} else {
m["content"] = nullptr;
}
m["tool_calls"] = std::move(normalized_tool_calls);
} else if (msg.content.empty() && msg.reasoning_content.empty()) {
++dropped_empty_assistant_tool_messages;
LOG_WARN("build_request_body: dropped assistant message whose tool_calls "
"were all malformed and whose content was empty");
continue;
} else {
m["content"] = msg.content;
}
} else if (msg.role == "tool") {
m["content"] = msg.content;
m["tool_call_id"] = msg.tool_call_id;
} else {
m["content"] = openai_content_for_message(
msg, model_has_vision_, any_vision_model_available_);
}
// Echo reasoning_content back on assistant messages only. DeepSeek
// thinking-mode rejects the next request with HTTP 400 if the previous
// turn produced reasoning_content and we don't include it here.
// Other OpenAI-compatible servers ignore unknown fields.
if (msg.role == "assistant" && !msg.reasoning_content.empty()) {
m["reasoning_content"] = msg.reasoning_content;
}
msgs_json.push_back(m);
}
if (dropped_invalid_role > 0) {
LOG_WARN("build_request_body: total " + std::to_string(dropped_invalid_role) +
" message(s) dropped due to invalid role");
}
if (repaired_tool_arguments > 0) {
LOG_WARN("build_request_body: repaired " +
std::to_string(repaired_tool_arguments) +
" tool_call payload field(s)");
}
if (dropped_malformed_tool_calls > 0) {
LOG_WARN("build_request_body: dropped " +
std::to_string(dropped_malformed_tool_calls) +
" malformed tool_call payload(s)");
}
if (dropped_empty_assistant_tool_messages > 0) {
LOG_WARN("build_request_body: dropped " +
std::to_string(dropped_empty_assistant_tool_messages) +
" empty assistant message(s) after tool_call normalization");
}
int moved_system_messages = 0;
int merged_system_messages = 0;
msgs_json = coalesce_system_messages_at_front(
msgs_json, moved_system_messages, merged_system_messages);
if (moved_system_messages > 0 || merged_system_messages > 0) {
LOG_WARN("build_request_body: normalized system message placement "
"moved=" + std::to_string(moved_system_messages) +
" merged=" + std::to_string(merged_system_messages));
}
// Orphan tool_call 防御:OpenAI / Chat Completions 严格要求
// assistant.tool_calls[*].id 都必须有一条 role=tool, tool_call_id=<id>
// 紧跟在后面;否则整个请求 400 "No tool output found for function call …"。
// 历史 session 在以下场景会持久化出 orphan(被打断的工具调用):
// - daemon 中途被 kill / 崩溃,assistant 已写盘但 tool result 未来得及落
// - 工具执行抛异常路径里 ToolResult 没被 append
// - resume 选了一个旧 jsonl,正好截在 assistant 之后
// 一旦有 orphan,该 session 的下一条 user 消息会让 LLM 端永久作废。我们在
// 请求出口把 orphan 用占位 tool 消息补齐,让 session 自动复活;同时 WARN
// 一条供排查。msgs_ 内存与 session jsonl 都不动 — 只在序列化层补洞。
nlohmann::json patched = nlohmann::json::array();
int synthesized_stubs = 0;
int dropped_orphan_tool_messages = 0;
int dropped_unexpected_tool_messages = 0;
int dropped_duplicate_tool_messages = 0;
{
size_t n = msgs_json.size();
for (size_t i = 0; i < n; ) {
const auto& cur = msgs_json[i];
const std::string role = cur.value("role", std::string{});
if (role == "tool") {
++dropped_orphan_tool_messages;
const std::string id = cur.value("tool_call_id", std::string{});
LOG_WARN("build_request_body: dropped standalone tool message "
"tool_call_id='" + id + "'");
++i;
continue;
}
patched.push_back(cur);
if (role == "assistant" && cur.contains("tool_calls") &&
cur["tool_calls"].is_array() && !cur["tool_calls"].empty()) {
std::vector<std::string> needed_ids;
std::unordered_set<std::string> needed_set;
for (const auto& tc : cur["tool_calls"]) {
if (tc.contains("id") && tc["id"].is_string()) {
std::string id = tc["id"].get<std::string>();
if (!id.empty() && !needed_set.count(id)) {
needed_ids.push_back(id);
needed_set.insert(id);
}
}
}
std::unordered_set<std::string> seen_ids;
size_t j = i + 1;
while (j < n && msgs_json[j].value("role", std::string{}) == "tool") {
std::string tool_call_id;
if (msgs_json[j].contains("tool_call_id") &&
msgs_json[j]["tool_call_id"].is_string()) {
tool_call_id = msgs_json[j]["tool_call_id"].get<std::string>();
}
if (tool_call_id.empty() || !needed_set.count(tool_call_id)) {
++dropped_unexpected_tool_messages;
LOG_WARN("build_request_body: dropped unexpected tool message "
"tool_call_id='" + tool_call_id + "'");
} else if (seen_ids.count(tool_call_id)) {
++dropped_duplicate_tool_messages;
LOG_WARN("build_request_body: dropped duplicate tool message "
"tool_call_id='" + tool_call_id + "'");
} else {
patched.push_back(msgs_json[j]);
seen_ids.insert(tool_call_id);
}
++j;
}
for (const auto& id : needed_ids) {
if (!seen_ids.count(id)) {
nlohmann::json stub;
stub["role"] = "tool";
stub["tool_call_id"] = id;
stub["content"] =
"[Error] Tool execution was interrupted before it could "
"produce a result. No output is available for this call.";
patched.push_back(std::move(stub));
++synthesized_stubs;
}
}
i = j;
} else {
++i;
}
}
}
if (synthesized_stubs > 0) {
LOG_WARN("build_request_body: synthesized " + std::to_string(synthesized_stubs) +
" placeholder tool message(s) for orphan tool_call(s) "
"(likely from interrupted prior turns; session will continue)");
}
if (dropped_orphan_tool_messages > 0 ||
dropped_unexpected_tool_messages > 0 ||
dropped_duplicate_tool_messages > 0) {
LOG_WARN("build_request_body: dropped invalid tool message(s) "