File size: 46,505 Bytes
6a3fff8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
const models = {
  "o1-preview": "o1-preview",
  "o1-mini": "o1-preview",
  "claude-3-5-sonnet-20240620": "claude-3-5-sonnet",
  "claude-3-5-sonnet-20241022": "claude-3-5-sonnet",
  "claude-3-5-haiku-20241022": "claude-3-5-haiku",
  "claude-3-haiku-20240307": "claude-3-5-haiku",
  "gpt-4o": "gpt-4o",
  "gpt-4o-mini": "gpt-4o-mini",
  "gpt-4o-file": "gpt-4o",
  "gpt-4o-mini-file": "gpt-4o-mini",
  "claude-3-5-sonnet-file": "claude-3-5-sonnet",
  "claude-3-5-haiku-file": "claude-3-5-haiku",
  "gemini-1.5-pro-latest": "gemini-1.5-pro",
  "gemini-1.5-flash-latest": "gemini-1.5-flash",
  "genspark": "genspark",
  "deepl": "deepl", // 添加翻译模型
};

// 新增画图模型
const drawingModels = new Set([
  "dall-e-3",
  "flux",
  "flux-speed",
  "flux-pro/ultra",
  "ideogram",
  "recraft-v3",
]);

// 添加缓存相关的常量配置
const CACHE_CONFIG = {
  TTL: 30 * 60, // 缓存30分钟aa
  EXCLUDED_MODELS: ["o1-preview"], // 不缓存的模型
  MAX_CACHE_SIZE: 100, // 最大缓存条目数
};

// 简单的内存缓存实现
class MessageCache {
  constructor() {
    this.cache = new Map();
    this.keyTimestamps = new Map();
  }

  generateKey(messages, model) {
    // 生成缓存key
    const contentStr = JSON.stringify(
      messages.map((m) => ({
        role: m.role,
        content: m.content,
      }))
    );
    return `${model}:${contentStr}`;
  }

  set(key, value) {
    // 检查缓存大小
    if (this.cache.size >= CACHE_CONFIG.MAX_CACHE_SIZE) {
      // 删除最旧的缓存
      const oldestKey = [...this.keyTimestamps.entries()].sort(
        ([, a], [, b]) => a - b
      )[0][0];
      this.cache.delete(oldestKey);
      this.keyTimestamps.delete(oldestKey);
    }

    this.cache.set(key, value);
    this.keyTimestamps.set(key, Date.now());
  }

  get(key) {
    const timestamp = this.keyTimestamps.get(key);
    if (!timestamp) return null;

    // 检查是否过期
    if (Date.now() - timestamp > CACHE_CONFIG.TTL * 1000) {
      this.cache.delete(key);
      this.keyTimestamps.delete(key);
      return null;
    }

    return this.cache.get(key);
  }
}

const messageCache = new MessageCache();

class SessionPool {
  constructor() {
    this.sessions = [];
    this.currentIndex = 0;
  }
  initialize(sessionString) {
    if (!sessionString) return;
    this.sessions = sessionString
      .split(",")
      .map((s) => s.trim())
      .filter((s) => s);
    this.currentIndex = Math.floor(Math.random() * this.sessions.length);
  }
  getNext() {
    if (this.sessions.length === 0) return null;
    const session = this.sessions[this.currentIndex];
    this.currentIndex = (this.currentIndex + 1) % this.sessions.length;
    return session;
  }
  size() {
    return this.sessions.length;
  }
}

const sessionPool = new SessionPool();

const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
  "Access-Control-Allow-Headers": "Content-Type, Authorization",
};

function doubleEncode(str) {
  return encodeURIComponent(encodeURIComponent(str));
}

function createErrorResponse(message, status = 500) {
  return new Response(JSON.stringify({ error: message }), {
    status,
    headers: { ...corsHeaders, "Content-Type": "application/json" },
  });
}

async function cleanupProject(session_id, project_id) {
  try {
    const headers = {
      Cookie: `session_id=${session_id}`,
      "User-Agent": "Apifox/1.0.0 (https://apifox.com)",
      Accept: "*/*",
      Host: "www.genspark.ai",
      Connection: "keep-alive",
      "Accept-Encoding": "gzip, deflate, br", // 添加压缩支持
    };
    const response = await fetch(
      `https://www.genspark.ai/api/project/delete?project_id=${project_id}`,
      {
        method: "GET",
        headers,
      }
    );
    return response.ok;
  } catch (error) {
    console.error("Cleanup project error:", error);
    return false;
  }
}

function extractProjectId(text) {
  try {
    if (text.startsWith("data: ")) {
      const content = JSON.parse(text.slice(6));
      if (content.type === "project_start" && content.id) {
        return content.id;
      }
    }
  } catch (e) {}
  return null;
}

function processChunk(chunk, messageId, model) {
  try {
    const content = chunk.replace(/^data:\s*/, "").trim();
    if (!content || content === "[DONE]") return null;

    const parsed = JSON.parse(content);
    if (!parsed) return null;

    // 处理翻译模型的特殊返回格式
    if (model === "deepl") {
      if (parsed.field_name === "content" && parsed.field_value) {
        return JSON.stringify({
          translations: [
            {
              detected_source_language:
                parsed.session_state?.detected_source_lang || "",
              text: parsed.field_value,
            },
          ],
        });
      }
    } else if (drawingModels.has(model)) {
      // 处理画图模型的响应
      if (parsed.content) {
        return JSON.stringify({
          created: Date.now(),
          data: [
            {
              url: parsed.content,
              revised_prompt: parsed.prompt || "",
            },
          ],
        });
      }
    } else {
      if (parsed.delta) {
        return `data: ${JSON.stringify({

          id: `chatcmpl-${messageId}`,

          choices: [

            {

              index: 0,

              delta: { content: parsed.delta },

            },

          ],

          created: Math.floor(Date.now() / 1000),

          model: models[model],

          object: "chat.completion.chunk",

        })}\n\n`;
      }
      if (
        parsed.field_value &&
        parsed.field_name !== "session_state.answer_is_finished" &&
        parsed.field_name !== "content" &&
        parsed.field_name !== "session_state" &&
        !parsed.delta &&
        parsed.type !== "project_field"
      ) {
        return JSON.stringify({
          id: `chatcmpl-${messageId}`,
          object: "chat.completion",
          created: Math.floor(Date.now() / 1000),
          model,
          choices: [
            {
              index: 0,
              message: {
                role: "assistant",
                content: parsed.field_value,
              },
              finish_reason: "stop",
            },
          ],
          usage: {
            prompt_tokens: 100,
            completion_tokens: 50,
            total_tokens: parsed.field_value.length,
          },
        });
      }
    }
  } catch (e) {}
  return null;
}

async function* streamGenerator(reader) {
  let buffer = "";
  const decoder = new TextDecoder();

  try {
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      buffer += decoder.decode(value, { stream: true });
      const lines = buffer.split("\n");
      buffer = lines.pop() || "";

      for (const line of lines) {
        if (line.trim()) yield line;
      }
    }
    if (buffer.trim()) yield buffer;
  } catch (e) {
    console.error("Stream error:", e);
  }
}

async function makeRequest(

  session_id,

  requestModel,

  messages,

  target_lang_code,

  source_lang_code,

  num_images = 1,

  size = "1024x1024",

  quality = "standard",

  style = "vivid"

) {
  const headers = {
    Cookie: `session_id=${session_id}`,
    "User-Agent": "Apifox/1.0.0 (https://apifox.com)",
    "Content-Type": "application/json",
    Accept: "*/*",
    Host: "www.genspark.ai",
    Connection: "keep-alive",
  };
  let retryCount = 0;
  while (retryCount < 3) {
    try {
      let requestBody = {};
      if (requestModel === "deepl") {
        // 构建翻译模型的请求体
        requestBody = {
          type: "COPILOT_MOA_TRANSLATOR",
          current_query_string: "type=COPILOT_MOA_TRANSLATOR",
          messages,
          user_s_input: messages[messages.length - 1].content,
          action_params: {},
          extra_data: {
            models: [models[requestModel]],
            run_with_another_model: false,
            target_lang_code: target_lang_code || "zh-hans",
            source_lang_code: source_lang_code || "",
            writingContent: null,
          },
        };
      } else if (drawingModels.has(requestModel)) {
        // 构建画图模型的请求体
        requestBody = {
          type: "COPILOT_MOA_IMAGE",
          current_query_string: "type=COPILOT_MOA_IMAGE",
          messages,
          user_s_input: messages[messages.length - 1].content,
          action_params: {},
          extra_data: {
            model_configs: [],
            llm_model: "gpt-4",
            imageModelMap: {},
            writingContent: null,
          },
        };
        for (let i = 0; i < num_images; i++) {
          requestBody.extra_data.model_configs.push({
            model: requestModel === "dall-e-3" ? "dalle-3" : requestModel,
            size: size,
            quality: quality,
            style: style,
          });
        }
      } else {
        // 构建聊天模型的请求体
        requestBody = {
          type: "COPILOT_MOA_CHAT",
          current_query_string: "type=COPILOT_MOA_CHAT",
          messages,
          action_params: {},
          extra_data: {
            models: [models[requestModel] || models["claude-3-5-sonnet-20241022"]],
            run_with_another_model: false,
            writingContent: null,
          },
        };
      }

      const response = await fetch(
        "https://www.genspark.ai/api/copilot/ask",
        {
          method: "POST",
          headers,
          body: JSON.stringify(requestBody),
        }
      );
      if (!response.ok) {
        retryCount++;
        await new Promise((resolve) =>
          setTimeout(resolve, 1000 * retryCount)
        );
        continue;
      }
      return response;
    } catch (error) {
      retryCount++;
      await new Promise((resolve) =>
        setTimeout(resolve, 1000 * retryCount)
      );
      if (retryCount >= 3) throw error;
    }
  }
  throw new Error("请求失败,已重试3次");
}

async function searchModel(session_id, messages) {
  const headers = {
    Cookie: `session_id=${session_id}`,
    "User-Agent": "Apifox/1.0.0 (https://apifox.com)",
    "Content-Type": "application/json",
    Accept: "*/*",
    Host: "www.genspark.ai",
    Connection: "keep-alive",
  };
  let retryCount = 0;
  while (retryCount < 3) {
    try {
      const query = doubleEncode(messages[messages.length - 1].content);
      const response = await fetch(
        `https://www.genspark.ai/api/search/stream?query=${query}`,
        {
          method: "POST",
          headers,
        }
      );
      if (!response.ok) {
        retryCount++;
        await new Promise((resolve) =>
          setTimeout(resolve, 1000 * retryCount)
        );
        continue;
      }
      return response;
    } catch (error) {
      retryCount++;
      await new Promise((resolve) =>
        setTimeout(resolve, 1000 * retryCount)
      );
      if (retryCount >= 3) throw error;
    }
  }
  throw new Error("请求失败,已重试3次");
}

async function pollTaskId(taskId, session_id, maxRetries, retryInterval) {
  let retries = 0;
  while (retries < maxRetries) {
    try {
      const statusResponse = await fetch(
        `https://www.genspark.ai/api/spark/image_generation_task_status?task_id=${taskId}`,
        {
          headers: {
            Cookie: `session_id=${session_id}`,
            "User-Agent": "Apifox/1.0.0 (https://apifox.com)",
            Accept: "*/*",
            Host: "www.genspark.ai",
            Connection: "keep-alive",
          },
        }
      );
      if (!statusResponse.ok) {
        throw new Error(`Status check failed: ${statusResponse.status}`);
      }
      const data = await statusResponse.json();
      if (data.data.status === "SUCCESS") {
        const urls = data.data.image_urls_nowatermark;
        if (urls?.length) {
          return urls;
        }
      } else if (data.data.status === "FAILED") {
        throw new Error("Image generation failed");
      }
    } catch (error) {
      console.error(`Poll error for task ${taskId} (retry ${retries}):`, error);
    }
    await new Promise((r) => setTimeout(r, retryInterval));
    retries++;
  }
  throw new Error(`Timeout waiting for task: ${taskId}`);
}

function arrayBufferToBase64(buffer) {
  let binary = '';
  const bytes = new Uint8Array(buffer);
  const len = bytes.byteLength;
  const chunkSize = 8192; // 分块大小,可以根据需要调整

  for (let i = 0; i < len; i += chunkSize) {
    const chunk = bytes.subarray(i, i + chunkSize);
    binary += String.fromCharCode.apply(null, chunk);
  }
  return btoa(binary);
}

// 添加处理消息的函数
async function processMessages(messages, env) {
  // 对每个消息进行处理
  for (let message of messages) {
    // 检查 message.content 是否为数组
    if (Array.isArray(message.content)) {
      // 处理 content 数组中的每个条目
      for (let i = 0; i < message.content.length; i++) {
        let entry = message.content[i];
        if (entry.type === 'image_url') {
          // 处理 image_url
          let url = entry.image_url?.url;
          if (!url) {
            throw new Error('image_url.url is required');
          }

          let base64ImageData;
          if (url.startsWith('data:image')) {
            // 已经是 base64 编码
            base64ImageData = url;
          } else {
            // 从 URL 获取图片并编码为 base64
            base64ImageData = await fetchImageAsDataURL(url, env);
          }
          // 用 base64 数据 URL 替换
          entry.image_url.url = base64ImageData;
        }
      }
    }
    // 否则,message.content 是字符串,无需处理
  }
}

// 添加获取图片并编码为 base64 的函数
async function fetchImageAsDataURL(url, env) {
  // 检查是否在 KV 缓存中
  let cacheKey = `image:${url}`;
  let cachedData = await env.kv.get(cacheKey);
  if (cachedData) {
    return cachedData;
  }
  // 获取图片
  let response = await fetch(url);
  if (!response.ok) {
    throw new Error(`Failed to fetch image from ${url}`);
  }
  let arrayBuffer = await response.arrayBuffer();
  let base64Data = arrayBufferToBase64(arrayBuffer);
  // 获取内容类型
  let contentType = response.headers.get('Content-Type') || 'image/jpeg';
  // 构建数据 URL
  let dataURL = `data:${contentType};base64,${base64Data}`;
  // 存储到 KV 缓存
  await env.kv.put(cacheKey, dataURL, { expirationTtl: CACHE_CONFIG.TTL });
  return dataURL;
}

// 提取最后的用户输入文本
function extractLastUserInput(messages) {
  // 从后向前遍历 messages
  for (let i = messages.length - 1; i >= 0; i--) {
    let message = messages[i];
    if (message.role === 'user') {
      if (Array.isArray(message.content)) {
        // 处理 content 数组
        for (let j = message.content.length - 1; j >= 0; j--) {
          let entry = message.content[j];
          if (entry.type === 'text' && entry.text) {
            return entry.text;
          }
        }
      } else if (typeof message.content === 'string') {
        // content 是字符串
        return message.content;
      }
    }
  }
  return '';
}

export default {
  async fetch(request, env, ctx) {
    if (request.method === "OPTIONS") {
      return new Response(null, { headers: corsHeaders });
    }

    const url = new URL(request.url);
    if (url.pathname === "/health") {
      return new Response(JSON.stringify({ status: "ok" }), {
        headers: { ...corsHeaders, "Content-Type": "application/json" },
      });
    }

    if (url.pathname === "/v1/models" && request.method === "GET") {
      return new Response(
        JSON.stringify({
          object: "list",
          data: Object.keys(models).map((model) => ({
            id: model,
            object: "model",
            created: 1706745938,
            owned_by: "genspark",
          })),
        }),
        { headers: { ...corsHeaders, "Content-Type": "application/json" } }
      );
    }

    // 添加对 /translate 接口的支持
    if (
      (url.pathname === "/v1/chat/completions" ||
        url.pathname === "/translate") &&
      request.method === "POST"
    ) {
      try {
        let requestData = await request.json();
        let {
          messages,
          prompt,
          stream = false,
          model = "deepl",
          target_lang_code,
          source_lang_code,
        } = requestData;

        // 如果是 /translate 接口,调整请求数据
        if (url.pathname === "/translate") {
          const { text, source_lang, target_lang } = requestData;
          messages = [{ role: "user", content: text }];
          model = "deepl";
          target_lang_code = target_lang || "zh-hans";
          source_lang_code = source_lang || "";
        }

        // 如果没有 messages,且有 prompt,创建 messages
        if (!messages && prompt) {
          messages = [{ role: "user", content: prompt }];
        }

        // 提取 num_images, size, response_format
        const {
          num_images = 1,
          size = "1024x1024",
          response_format = "url",
          quality = "standard",
          style = "vivid",
        } = requestData;

        const authHeader = request.headers.get("authorization");

        if (sessionPool.size() === 0) {
          const sessionString = authHeader?.replace("Bearer ", "");
          sessionPool.initialize(sessionString);
          if (sessionPool.size() === 0) {
            return createErrorResponse("未提供有效的 session_id", 401);
          }
        }
        const session_id = sessionPool.getNext();
        if (!session_id) {
          return createErrorResponse("无可用的会话ID", 500);
        }

        // 添加缓存处理
        const cacheKey = messageCache.generateKey(messages, model);
        let cachedResponse = null;
        if (!CACHE_CONFIG.EXCLUDED_MODELS.includes(model)) {
          cachedResponse = messageCache.get(cacheKey);
        }
        if (cachedResponse) {
          return new Response(cachedResponse, {
            headers: { ...corsHeaders, "Content-Type": "application/json" },
          });
        }

        // 处理 messages,处理图片
        await processMessages(messages, env);
        const user_s_input = extractLastUserInput(messages);

        if (drawingModels.has(model)) {
          // 处理画图请求
          // 构建请求体
          const requestBody = {
            type: "COPILOT_MOA_IMAGE",
            current_query_string: "type=COPILOT_MOA_IMAGE",
            messages,
            user_s_input: user_s_input,
            action_params: {},
            extra_data: {
              model_configs: [],
              llm_model: "gpt-4",
              imageModelMap: {},
              writingContent: null,
            },
          };
          for (let i = 0; i < num_images; i++) {
            requestBody.extra_data.model_configs.push({
              model: model === "dall-e-3" ? "dalle-3" : model,
              size: size,
              quality: quality,
              style: style,
            });
          }
          const headers = {
            Cookie: `session_id=${session_id}`,
            "User-Agent": "Apifox/1.0.0 (https://apifox.com)",
            "Content-Type": "application/json",
            Accept: "*/*",
            Host: "www.genspark.ai",
            Connection: "keep-alive",
          };
          if (stream === true || stream === "true") {
            // Handle streaming response
            const { readable, writable } = new TransformStream();
            const writer = writable.getWriter();

            ctx.waitUntil(
              (async () => {
                try {
                  const response = await fetch(
                    "https://www.genspark.ai/api/copilot/ask",
                    {
                      method: "POST",
                      headers,
                      body: JSON.stringify(requestBody),
                    }
                  );

                  if (!response.ok) {
                    await writer.write(
                      new TextEncoder().encode(
                        `data: ${JSON.stringify({

                          error: "上游服务请求失败",

                        })}\n\n`
                      )
                    );
                    await writer.close();
                    return;
                  }

                  const reader = response.body.getReader();
                  let taskIds = [];

                  // Read the response from upstream and extract task IDs
                  let responseText = "";
                  for await (const line of streamGenerator(reader)) {
                    responseText += line + "\n";
                    if (line.includes("task_id")) {
                      try {
                        const contentLine = line.replace("data: ", "");
                        const { content: innerContent } = JSON.parse(contentLine);
                        if (innerContent) {
                          const { generated_images } = JSON.parse(innerContent);
                          if (generated_images) {
                            for (const img of generated_images) {
                              if (img.task_id) {
                                taskIds.push(img.task_id);
                              }
                            }
                          }
                        }
                      } catch (e) {}
                    }
                  }

                  if (!taskIds.length) {
                    await writer.write(
                      new TextEncoder().encode(
                        `data: ${JSON.stringify({

                          error: "获取任务ID失败",

                        })}\n\n`
                      )
                    );
                    await writer.close();
                    return;
                  }

                  // Now we can poll the task IDs and send images to the client
                  const maxRetries = 30;
                  const retryInterval = 2000;

                  for (const taskId of taskIds) {
                    let retries = 0;
                    let imageSent = false;
                    while (retries < maxRetries && !imageSent) {
                      try {
                        const statusResponse = await fetch(
                          `https://www.genspark.ai/api/spark/image_generation_task_status?task_id=${taskId}`,
                          {
                            headers,
                          }
                        );

                        if (!statusResponse.ok) {
                          throw new Error(
                            `Status check failed: ${statusResponse.status}`
                          );
                        }

                        const data = await statusResponse.json();
                        if (data.data.status === "SUCCESS") {
                          const urls = data.data.image_urls_nowatermark;
                          if (urls?.length) {
                            // Send the image URLs to the client
                            for (const url of urls) {
                              const data = {
                                id: `chatcmpl-${crypto.randomUUID()}`,
                                object: "chat.completion.chunk",
                                created: Math.floor(Date.now() / 1000),
                                model: model,
                                choices: [
                                  {
                                    delta: { content: `![Image](${url})\n` },
                                    index: 0,
                                    finish_reason: null,
                                  },
                                ],
                              };
                              await writer.write(
                                new TextEncoder().encode(
                                  `data: ${JSON.stringify(data)}\n\n`
                                )
                              );
                            }
                            imageSent = true;
                            break;
                          }
                        } else if (data.data.status === "FAILED") {
                          throw new Error("Image generation failed");
                        }
                        // No else, we just wait and retry
                      } catch (error) {
                        console.error(
                          `Poll error for task ${taskId} (retry ${retries}):`,
                          error
                        );
                      }
                      await new Promise((r) => setTimeout(r, retryInterval));
                      retries++;
                    }
                    if (!imageSent) {
                      const errorData = {
                        id: `chatcmpl-${crypto.randomUUID()}`,
                        object: "chat.completion.chunk",
                        created: Math.floor(Date.now() / 1000),
                        model: model,
                        choices: [
                          {
                            delta: {
                              content: `![Image](Image generation failed for task ${taskId})\n`,
                            },
                            index: 0,
                            finish_reason: null,
                          },
                        ],
                      };
                      await writer.write(
                        new TextEncoder().encode(
                          `data: ${JSON.stringify(errorData)}\n\n`
                        )
                      );
                    }
                  }

                  // Send the completion signal
                  await writer.write(new TextEncoder().encode("data: [DONE]\n\n"));
                } catch (error) {
                  console.error("Stream error:", error);
                  await writer.abort(error);
                } finally {
                  await writer.close();
                }
              })()
            );

            return new Response(readable, {
              headers: {
                ...corsHeaders,
                "Content-Type": "text/event-stream",
                "Cache-Control": "no-cache",
                Connection: "keep-alive",
              },
            });
          } else {
            // 非流式处理
            // 发送请求获取任务ID
            const response = await fetch(
              "https://www.genspark.ai/api/copilot/ask",
              {
                method: "POST",
                headers,
                body: JSON.stringify(requestBody),
              }
            );
            if (!response.ok) {
              return createErrorResponse("上游服务请求失败", response.status);
            }
            // 解析响应获取 task_ids
            const text = await response.text();
            const taskIds = [];
            const lines = text.split("\n");
            for (const line of lines) {
              if (line.includes("task_id")) {
                try {
                  const content = line.replace("data: ", "");
                  if (!content) continue;
                  const { content: innerContent } = JSON.parse(content);
                  if (!innerContent) continue;
                  const { generated_images } = JSON.parse(innerContent);
                  if (!generated_images) continue;
                  for (const img of generated_images) {
                    if (img.task_id) {
                      taskIds.push(img.task_id);
                    }
                  }
                } catch (e) {}
              }
            }
            if (!taskIds.length) {
              return createErrorResponse("获取任务ID失败");
            }
            // 并行轮询任务结果
            const maxRetries = 30;
            const retryInterval = 2000;

            const taskPromises = taskIds.map((taskId) =>
              pollTaskId(taskId, session_id, maxRetries, retryInterval)
            );
            let imageUrls = [];
            try {
              const results = await Promise.all(taskPromises);
              results.forEach((urls) => {
                imageUrls.push(...urls);
              });
            } catch (error) {
              console.error("Polling error:", error);
              return createErrorResponse(error.message);
            }

            // 处理 response_format
            if (response_format === "b64_json") {
              // 使用 KV 缓存图像数据
              const imageDatas = await Promise.all(
                imageUrls.map(async (url) => {
                  const cachedData = await env.kv.get(url);
                  if (cachedData) {
                    return { b64_json: cachedData };
                  } else {
                    const imageResponse = await fetch(url);
                    const imageArrayBuffer = await imageResponse.arrayBuffer();
                    const base64Data = arrayBufferToBase64(imageArrayBuffer);
                    // 存储到 KV
                    await env.kv.put(url, base64Data, {
                      expirationTtl: CACHE_CONFIG.TTL,
                    });
                    return { b64_json: base64Data };
                  }
                })
              );

              // 构建聊天回复
              const imageMarkdowns = imageDatas
                .map(
                  (imgData, idx) =>
                    `![Image](data:image/png;base64,${imgData.b64_json})`
                )
                .join("\n");

              const messageId = crypto.randomUUID();

              const result = {
                id: `chatcmpl-${messageId}`,
                object: "chat.completion",
                created: Math.floor(Date.now() / 1000),
                model: model,
                choices: [
                  {
                    index: 0,
                    message: {
                      role: "assistant",
                      content: imageMarkdowns,
                    },
                    finish_reason: "stop",
                  },
                ],
                usage: {
                  prompt_tokens: 0,
                  completion_tokens: 0,
                  total_tokens: 0,
                },
              };

              // 缓存结果
              if (!CACHE_CONFIG.EXCLUDED_MODELS.includes(model)) {
                messageCache.set(cacheKey, JSON.stringify(result));
              }

              return new Response(JSON.stringify(result), {
                headers: {
                  ...corsHeaders,
                  "Content-Type": "application/json",
                },
              });
            } else {
              // 默认返回 URL,构建聊天回复
              const imageMarkdowns = imageUrls
                .map((url) => `![Image](${url})`)
                .join("\n");

              const messageId = crypto.randomUUID();

              const result = {
                id: `chatcmpl-${messageId}`,
                object: "chat.completion",
                created: Math.floor(Date.now() / 1000),
                model: model,
                choices: [
                  {
                    index: 0,
                    message: {
                      role: "assistant",
                      content: imageMarkdowns,
                    },
                    finish_reason: "stop",
                  },
                ],
                usage: {
                  prompt_tokens: 0,
                  completion_tokens: 0,
                  total_tokens: 0,
                },
              };

              // 缓存结果
              if (!CACHE_CONFIG.EXCLUDED_MODELS.includes(model)) {
                messageCache.set(cacheKey, JSON.stringify(result));
              }

              return new Response(JSON.stringify(result), {
                headers: {
                  ...corsHeaders,
                  "Content-Type": "application/json",
                },
              });
            }
          }
        }

        // 以下是处理非画图模型的逻辑

        let response;
        if (model === "genspark") {
          response = await searchModel(session_id, messages);
        } else {
          response = await makeRequest(
            session_id,
            model,
            messages,
            target_lang_code,
            source_lang_code
          );
        }

        if (!response.ok) {
          return createErrorResponse("上游服务请求失败", response.status);
        }

        const messageId = crypto.randomUUID();
        let project_id = null;

        if (stream === true || stream === "true") {
          const { readable, writable } = new TransformStream();
          const writer = writable.getWriter();
          ctx.waitUntil(
            (async () => {
              try {
                const reader = response.body.getReader();
                for await (const line of streamGenerator(reader)) {
                  if (!project_id) {
                    project_id = extractProjectId(line);
                  }
                  const processed = processChunk(line, messageId, model);
                  if (processed) {
                    await writer.write(new TextEncoder().encode(processed));
                  }
                }
                await writer.write(new TextEncoder().encode("data: [DONE]\n\n"));
              } catch (error) {
                console.error("Stream error:", error);
              } finally {
                await writer.close();
                if (project_id) {
                  await cleanupProject(session_id, project_id);
                }
              }
            })()
          );
          return new Response(readable, {
            headers: {
              ...corsHeaders,
              "Content-Type": "text/event-stream",
              "Cache-Control": "no-cache",
              Connection: "keep-alive",
            },
          });
        }

        const chunks = [];
        const reader = response.body.getReader();
        try {
          while (true) {
            const { done, value } = await reader.read();
            if (done) break;
            const text = new TextDecoder().decode(value);
            chunks.push(text);
            if (!project_id) {
              const lines = text.split("\n");
              for (const line of lines) {
                project_id = extractProjectId(line);
                if (project_id) break;
              }
            }
          }
        } finally {
          reader.releaseLock();
          if (project_id) {
            ctx.waitUntil(cleanupProject(session_id, project_id));
          }
        }

        const fullResponse = chunks.join("");
        for (const line of fullResponse.split("\n")) {
          if (line.startsWith("data: ")) {
            try {
              const content = JSON.parse(line.slice(6));
              if (model === "deepl") {
                // 处理翻译模型的响应
                if (content.field_name === "content" && content.field_value) {
                  const result = JSON.stringify({
                    code: 200,
                    data: {
                      translations: [
                        {
                          detected_source_language:
                            content.session_state?.detected_source_lang || "",
                          text: content.field_value,
                        },
                      ],
                    },
                    msg: "ok",
                  });
                  // 缓存结果
                  if (!CACHE_CONFIG.EXCLUDED_MODELS.includes(model)) {
                    messageCache.set(cacheKey, result);
                  }
                  return new Response(result, {
                    headers: { ...corsHeaders, "Content-Type": "application/json" },
                  });
                }
              } else {
                // 处理其他模型的响应
                if (
                  content.field_value &&
                  content.field_name !== "session_state.answer_is_finished" &&
                  content.field_name !== "content" &&
                  content.field_name !== "session_state" &&
                  !content.delta &&
                  content.type !== "project_field"
                ) {
                  const result = JSON.stringify({
                    id: `chatcmpl-${messageId}`,
                    object: "chat.completion",
                    created: Math.floor(Date.now() / 1000),
                    model,
                    choices: [
                      {
                        index: 0,
                        message: {
                          role: "assistant",
                          content: content.field_value,
                        },
                        finish_reason: "stop",
                      },
                    ],
                    usage: {
                      prompt_tokens: 0,
                      completion_tokens: 0,
                      total_tokens: content.field_value.length,
                    },
                  });
                  // 缓存结果
                  if (!CACHE_CONFIG.EXCLUDED_MODELS.includes(model)) {
                    messageCache.set(cacheKey, result);
                  }
                  return new Response(result, {
                    headers: { ...corsHeaders, "Content-Type": "application/json" },
                  });
                }
              }
            } catch (e) {}
          }
        }
        return createErrorResponse("无效的响应数据");
      } catch (error) {
        console.error("Request processing error:", error);
        return createErrorResponse("请求处理失败");
      }
    }

    // 添加新的画图路由
    if (
      url.pathname === "/v1/images/generations" &&
      request.method === "POST"
    ) {
      try {
        const requestData = await request.json();
        // 参数验证
        if (!requestData.prompt && !requestData.messages) {
          return new Response(
            JSON.stringify({ error: "Prompt is required" }),
            {
              status: 400,
              headers: { ...corsHeaders, "Content-Type": "application/json" },
            }
          );
        }
        // 获取随机session_id
        const authHeader = request.headers.get("authorization");
        if (sessionPool.size() === 0) {
          const sessionString = authHeader?.replace("Bearer ", "");
          sessionPool.initialize(sessionString);
          if (sessionPool.size() === 0) {
            return createErrorResponse("未提供有效的 session_id", 401);
          }
        }
        const session_id = sessionPool.getNext();
        if (!session_id) {
          return createErrorResponse("无可用的会话ID", 500);
        }
        // 提取 response_format
        const {
          response_format = "url",
          num_images = 1,
          size = "1024x1024",
          quality = "standard",
          style = "auto",
          image,
          model = "dall-e-3",
          aspect_ratio=auto,
          hd=true,
          reflection_enabled=false,
        } = requestData;
        // 构建请求体
        let messages = [];

        if (requestData.messages) {
          messages = requestData.messages;
          // 处理 messages,处理图片
          await processMessages(messages, env);
        } else {
          // 构建带有 prompt 和 image 的 messages
          if (image) {
            // image 可以是 base64 编码的图像数据
            let base64ImageData = image;
            if (!base64ImageData.startsWith('data:image')) {
              // 假设是 base64 编码的数据,包装为数据 URL
              base64ImageData = `data:image/jpeg;base64,${image}`;
            }
            messages.push({
              role: 'user',
              content: [
                { type: 'image_url', image_url: { url: base64ImageData } },
                { type: 'text', text: requestData.prompt },
              ],
            });
          } else {
            // 没有图片,仅使用提示词
            messages.push({ role: 'user', content: requestData.prompt });
          }
        }

        await processMessages(messages, env);
        const user_s_input = extractLastUserInput(messages);

        const requestBody = {
          type: "COPILOT_MOA_IMAGE",
          current_query_string: "type=COPILOT_MOA_IMAGE",
          messages: messages,
          user_s_input: user_s_input,
          action_params: {},
          extra_data: {
            model_configs: [],
            llm_model: "gpt-4o",
            imageModelMap: {},
            writingContent: null,
          },
        };
        for (let i = 0; i < num_images; i++) {
          requestBody.extra_data.model_configs.push({
            model: model === "dall-e-3" ? "dalle-3" : model,
            aspect_ratio,
            use_personalized_models:false,
            fashion_profile_id:null,
            hd,
            reflection_enabled,
            style: style
          });
        }
        // 发送请求获取任务ID
        const response = await fetch(
          "https://www.genspark.ai/api/copilot/ask",
          {
            method: "POST",
            headers: {
              Cookie: `session_id=${session_id}`,
              "User-Agent": "Apifox/1.0.0 (https://apifox.com)",
              "Content-Type": "application/json",
              Accept: "*/*",
              Host: "www.genspark.ai",
              Connection: "keep-alive",
            },
            body: JSON.stringify(requestBody),
          }
        );
        if (!response.ok) {
          return createErrorResponse("上游服务请求失败", response.status);
        }
        // 解析响应获取task_id
        const text = await response.text();
        const taskIds = [];
        const lines = text.split("\n");
        for (const line of lines) {
          if (line.includes("task_id")) {
            try {
              const content = line.replace("data: ", "");
              if (!content) continue;
              const { content: innerContent } = JSON.parse(content);
              if (!innerContent) continue;
              const { generated_images } = JSON.parse(innerContent);
              if (!generated_images) continue;
              for (const img of generated_images) {
                if (img.task_id) {
                  taskIds.push(img.task_id);
                }
              }
            } catch (e) {}
          }
        }
        if (!taskIds.length) {
          return createErrorResponse("获取任务ID失败");
        }
        // 并行轮询任务结果
        const maxRetries = 300;
        const retryInterval = 2000;

        const taskPromises = taskIds.map((taskId) =>
          pollTaskId(taskId, session_id, maxRetries, retryInterval)
        );
        let imageUrls = [];
        try {
          const results = await Promise.all(taskPromises);
          results.forEach((urls) => {
            imageUrls.push(...urls);
          });
        } catch (error) {
          console.error("Polling error:", error);
          return createErrorResponse(error.message);
        }

        if (response_format === "b64_json") {
          // 使用 KV 缓存图像数据
          const imageDatas = await Promise.all(
            imageUrls.map(async (url) => {
              const cachedData = await env.kv.get(url);
              if (cachedData) {
                return { b64_json: cachedData };
              } else {
                const imageResponse = await fetch(url);
                const imageArrayBuffer = await imageResponse.arrayBuffer();
                const base64Data = arrayBufferToBase64(imageArrayBuffer);
                // 存储到 KV
                await env.kv.put(url, base64Data, { expirationTtl: CACHE_CONFIG.TTL });
                return { b64_json: base64Data };
              }
            })
          );

          return new Response(
            JSON.stringify({
              created: Date.now(),
              data: imageDatas,
            }),
            { headers: { ...corsHeaders, "Content-Type": "application/json" } }
          );
        } else {
          // 默认返回 URL
          return new Response(
            JSON.stringify({
              created: Date.now(),
              data: imageUrls.map((url) => ({
                url,
                revised_prompt: requestData.prompt,
              })),
            }),
            { headers: { ...corsHeaders, "Content-Type": "application/json" } }
          );
        }
      } catch (error) {
        console.error("Request processing error:", error);
        return createErrorResponse("请求处理失败");
      }
    }


    return new Response("Not Found", {
      status: 404,
      headers: corsHeaders,
    });
  },
};