-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathqwen.js
More file actions
2338 lines (2129 loc) · 111 KB
/
qwen.js
File metadata and controls
2338 lines (2129 loc) · 111 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
// =================================================
// Qwen + Gemini 智能识别系统 (Qwen v2 API)
// 支持:对话、图片识别、图片生成、图片编辑
// 更新日期:2025-10-01
// =================================================
/**
* 生成 UUID v4
*/
function generateUUID() {
return crypto.randomUUID();
}
/**
* SHA256 加密
*/
async function sha256Encrypt(text) {
const encoder = new TextEncoder();
const data = encoder.encode(text);
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}
/**
* 图片缓存管理器
*/
class ImageCacheManager {
constructor() {
this.cache = new Map();
this.maxSize = 100;
}
cacheExists(signature) {
return this.cache.has(signature);
}
getCache(signature) {
return this.cache.get(signature);
}
addCache(signature, url) {
if (this.cache.size >= this.maxSize) {
const firstKey = this.cache.keys().next().value;
this.cache.delete(firstKey);
}
this.cache.set(signature, { url, timestamp: Date.now() });
}
}
const imageCacheManager = new ImageCacheManager();
/**
* 判断聊天类型
*/
function isChatType(model) {
if (!model) return 't2t';
if (model.includes('-search')) return 'search';
if (model.includes('-image-edit')) return 'image_edit';
if (model.includes('-image')) return 't2i';
if (model.includes('-video')) return 't2v';
if (model.includes('-deep-research')) return 'deep_research';
return 't2t';
}
/**
* 解析模型名称
*/
function parserModel(model) {
if (!model) return 'qwen3-235b-a22b';
try {
model = String(model);
model = model.replace('-search', '');
model = model.replace('-thinking', '');
model = model.replace('-edit', '');
model = model.replace('-video', '');
model = model.replace('-deep-research', '');
model = model.replace('-image', '');
return model;
} catch (e) {
return 'qwen3-235b-a22b';
}
}
/**
* 判断是否启用思考模式
*/
function isThinkingEnabled(model, enable_thinking, thinking_budget) {
const thinking_config = {
"output_schema": "phase",
"thinking_enabled": false,
"thinking_budget": 81920
};
if (!model) return thinking_config;
if (model.includes('-thinking') || enable_thinking) {
thinking_config.thinking_enabled = true;
}
if (thinking_budget && Number(thinking_budget) > 0 && Number(thinking_budget) < 38912) {
thinking_config.budget = Number(thinking_budget);
}
return thinking_config;
}
/**
* 获取简化的文件类型
*/
function getSimpleFileType(mimeType) {
if (!mimeType) return 'file';
const mainType = mimeType.split('/')[0].toLowerCase();
const supportedTypes = ['image', 'video', 'audio', 'document'];
return supportedTypes.includes(mainType) ? mainType : 'file';
}
// =================================================
// 1. Authentication & Configuration
// =================================================
async function handleLogin(request) {
if (request.method !== 'POST') {
return new Response('Method Not Allowed', { status: 405 });
}
if (typeof PASSWORD === 'undefined') {
return new Response('Server configuration error: The PASSWORD secret is not set in the Worker environment.', { status: 500 });
}
const formData = await request.formData();
const password = formData.get('password');
if (password === PASSWORD) {
const sessionCookie = `auth_session=ok; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=86400`; // 24-hour session
return new Response(null, {
status: 302,
headers: { 'Set-Cookie': sessionCookie, 'Location': '/' },
});
} else {
return new Response(null, {
status: 302,
headers: { 'Location': '/?error=1' },
});
}
}
async function checkAuth(request) {
if (typeof API_KEY !== 'undefined' && API_KEY) {
const authHeader = request.headers.get('Authorization') || '';
if (authHeader === `Bearer ${API_KEY}`) {
return null;
}
}
const url = new URL(request.url);
const cookie = request.headers.get('Cookie') || '';
if (cookie.includes('auth_session=ok')) {
return null;
}
const isApiCall = url.pathname.startsWith('/api/') || url.pathname.startsWith('/recognize') || url.pathname.startsWith('/proxy/upload');
if (isApiCall) {
return new Response(JSON.stringify({ error: 'Unauthorized. Provide API Key in Authorization header or log in.' }), {
status: 401,
headers: { 'Content-Type': 'application/json' },
});
}
return new Response(getLoginPage(url), {
status: 401,
headers: { 'Content-Type': 'text/html' },
});
}
function getLoginPage(url) {
const error = url.searchParams.get('error') ? '<p style="color: red; text-align: center;">密码错误,请重试!</p>' : '';
return `<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>请输入密码</title><style>body { font-family: -apple-system, sans-serif; display: flex; align-items: center; justify-content: center; height: 100vh; background: #f0f2f5; margin: 0; } .login-box { background: white; padding: 40px; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); width: 320px; } h1 { text-align: center; color: #333; margin-top: 0; } input[type="password"] { width: 100%; padding: 12px; margin-top: 10px; margin-bottom: 20px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; } button { width: 100%; padding: 12px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; } button:hover { background: #0056b3; }</style></head><body><div class="login-box"><h1>身份验证</h1>${error}<form action="/login" method="post"><input type="password" name="password" placeholder="请输入访问密码" required autofocus><button type="submit">进入</button></form></div></body></html>`;
}
async function getQwenCookie() {
if (typeof SETTINGS_KV === 'undefined') {
throw new Error('Server configuration error: The SETTINGS_KV namespace is not bound to this Worker.');
}
const cookie = await SETTINGS_KV.get('QWEN_COOKIE');
if (!cookie) {
throw new Error('Qwen cookie not set in Worker settings. Please save it via the UI.');
}
return cookie;
}
// NEW: Helper to get Gemini API Key from environment variables
async function getGeminiApiKey() {
if (typeof GEMINI_API_KEY === 'undefined' || !GEMINI_API_KEY) {
throw new Error('Server configuration error: The GEMINI_API_KEY secret is not set in the Worker environment.');
}
return GEMINI_API_KEY;
}
// =================================================
// 1.5. Qwen v2 图片上传到 OSS
// =================================================
/**
* 请求 STS Token
*/
async function requestStsToken(filename, filesize, filetypeSimple, authToken) {
const requestId = generateUUID();
const bearerToken = authToken.startsWith('Bearer ') ? authToken : `Bearer ${authToken}`;
const response = await fetch('https://chat.qwen.ai/api/v1/files/getstsToken', {
method: 'POST',
headers: {
'Authorization': bearerToken,
'Content-Type': 'application/json',
'x-request-id': requestId,
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
},
body: JSON.stringify({
filename,
filesize,
filetype: filetypeSimple
})
});
if (!response.ok) {
throw new Error(`获取STS Token失败: ${response.status}`);
}
const stsData = await response.json();
return {
credentials: {
access_key_id: stsData.access_key_id,
access_key_secret: stsData.access_key_secret,
security_token: stsData.security_token
},
file_info: {
url: stsData.file_url,
path: stsData.file_path,
bucket: stsData.bucketname,
endpoint: stsData.region + '.aliyuncs.com',
id: stsData.file_id
}
};
}
/**
* 上传到 OSS
*/
async function uploadToOss(fileBuffer, credentials, fileInfo, mimeType) {
const date = new Date().toUTCString();
const contentType = mimeType || 'application/octet-stream';
// 构建签名字符串
const stringToSign = `PUT\n\n${contentType}\n${date}\nx-oss-security-token:${credentials.security_token}\n/${fileInfo.bucket}/${fileInfo.path}`;
// 使用 HMAC-SHA1 签名
const encoder = new TextEncoder();
const key = await crypto.subtle.importKey(
'raw',
encoder.encode(credentials.access_key_secret),
{ name: 'HMAC', hash: 'SHA-1' },
false,
['sign']
);
const signature = await crypto.subtle.sign(
'HMAC',
key,
encoder.encode(stringToSign)
);
const signatureBase64 = btoa(String.fromCharCode(...new Uint8Array(signature)));
const authorization = `OSS ${credentials.access_key_id}:${signatureBase64}`;
const response = await fetch(`https://${fileInfo.bucket}.${fileInfo.endpoint}/${fileInfo.path}`, {
method: 'PUT',
headers: {
'Content-Type': contentType,
'Date': date,
'Authorization': authorization,
'x-oss-security-token': credentials.security_token
},
body: fileBuffer
});
if (!response.ok) {
throw new Error(`OSS上传失败: ${response.status}`);
}
return { success: true };
}
/**
* 完整的文件上传流程
*/
async function uploadFileToQwenOss(fileBuffer, originalFilename, authToken) {
const filesize = fileBuffer.byteLength || fileBuffer.length;
// 从文件名获取 MIME 类型
const ext = originalFilename.split('.').pop().toLowerCase();
const mimeTypes = {
'png': 'image/png',
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'gif': 'image/gif',
'webp': 'image/webp',
'bmp': 'image/bmp'
};
const mimeType = mimeTypes[ext] || 'application/octet-stream';
const filetypeSimple = getSimpleFileType(mimeType);
// 获取 STS Token
const { credentials, file_info } = await requestStsToken(
originalFilename,
filesize,
filetypeSimple,
authToken
);
// 上传到 OSS
await uploadToOss(fileBuffer, credentials, file_info, mimeType);
return {
status: 200,
file_url: file_info.url,
file_id: file_info.id,
message: '文件上传成功'
};
}
// =================================================
// 1.6. Qwen v2 消息解析
// =================================================
/**
* 解析消息格式,处理图片上传
*/
async function parserMessages(messages, thinking_config, chat_type, authToken) {
try {
const feature_config = thinking_config;
for (let message of messages) {
if (message.role === 'user' || message.role === 'assistant') {
message.chat_type = "t2t";
message.extra = {};
message.feature_config = {
"output_schema": "phase",
"thinking_enabled": false,
};
if (!Array.isArray(message.content)) continue;
const newContent = [];
for (let item of message.content) {
if (item.type === 'image' || item.type === 'image_url') {
let base64 = null;
if (item.type === 'image_url') {
base64 = item.image_url.url;
}
if (base64) {
const regex = /data:(.+);base64,/;
const fileType = base64.match(regex);
const fileExtension = fileType && fileType[1] ? fileType[1].split('/')[1] || 'png' : 'png';
const filename = `${generateUUID()}.${fileExtension}`;
const pureBase64 = base64.replace(regex, '');
const signature = await sha256Encrypt(pureBase64);
try {
// 将 base64 转换为 ArrayBuffer
const binaryString = atob(pureBase64);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
const buffer = bytes.buffer;
// 检查缓存
if (imageCacheManager.cacheExists(signature)) {
delete item.image_url;
item.type = 'image';
item.image = imageCacheManager.getCache(signature).url;
newContent.push(item);
} else {
const uploadResult = await uploadFileToQwenOss(buffer, filename, authToken);
if (uploadResult && uploadResult.status === 200) {
delete item.image_url;
item.type = 'image';
item.image = uploadResult.file_url;
imageCacheManager.addCache(signature, uploadResult.file_url);
newContent.push(item);
}
}
} catch (error) {
console.error('图片上传失败:', error);
}
}
} else if (item.type === 'text') {
item.chat_type = 't2t';
item.feature_config = {
"output_schema": "phase",
"thinking_enabled": false,
};
if (newContent.length >= 2) {
messages.push({
"role": "user",
"content": item.text,
"chat_type": "t2t",
"extra": {},
"feature_config": {
"output_schema": "phase",
"thinking_enabled": false,
}
});
} else {
newContent.push(item);
}
}
}
if (newContent.length > 0) {
message.content = newContent;
}
} else {
// 处理 system 消息
if (Array.isArray(message.content)) {
let system_prompt = '';
for (let item of message.content) {
if (item.type === 'text') {
system_prompt += item.text;
}
}
if (system_prompt) {
message.content = system_prompt;
}
}
}
}
messages[messages.length - 1].feature_config = feature_config;
messages[messages.length - 1].chat_type = chat_type;
return messages;
} catch (e) {
console.error('消息解析失败:', e);
return [{
"role": "user",
"content": "直接返回字符串: '聊天历史处理有误...'",
"chat_type": "t2t",
"extra": {},
"feature_config": {
"output_schema": "phase",
"enabled": false,
}
}];
}
}
/**
* 生成 chat_id
* 注意:chat_type 硬编码为 "t2i",这是 Qwen2api 的标准做法
*/
async function generateChatID(token, model) {
try {
const response = await fetch('https://chat.qwen.ai/api/v2/chats/new', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
},
body: JSON.stringify({
"title": "New Chat",
"models": [model],
"chat_mode": "local",
"chat_type": "t2i", // 硬编码为 t2i,与 Qwen2api 保持一致
"timestamp": Date.now()
})
});
if (!response.ok) {
const errorText = await response.text();
console.error('生成chat_id失败 - HTTP错误:', response.status, errorText);
return null;
}
const data = await response.json();
return data?.data?.id || null;
} catch (error) {
console.error('生成chat_id失败:', error);
return null;
}
}
/**
* 发送聊天请求
*/
async function sendChatRequest(body, token) {
try {
const chat_id = await generateChatID(token, body.model);
if (!chat_id) {
throw new Error('生成chat_id失败');
}
const response = await fetch(`https://chat.qwen.ai/api/v2/chat/completions?chat_id=${chat_id}`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
},
body: JSON.stringify({
...body,
chat_id: chat_id
})
});
return response;
} catch (error) {
console.error('发送聊天请求失败:', error);
throw error;
}
}
// =================================================
// 2. Main Request Handler
// =================================================
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
const url = new URL(request.url);
try {
if (url.pathname === '/login') {
return await handleLogin(request);
}
if (url.pathname !== '/favicon.ico' && url.pathname !== '/api-docs') {
const authResponse = await checkAuth(request);
if (authResponse) {
return authResponse;
}
}
if (request.method === 'OPTIONS') {
return new Response(null, {
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization, x-recognition-model, x-custom-prompt',
},
});
}
switch (url.pathname) {
// 新增:Qwen v2 对话接口
case '/v1/chat/completions':
return await handleChatCompletions(request);
case '/api/settings':
if (request.method === 'GET') {
const cookie = await SETTINGS_KV.get('QWEN_COOKIE') || '';
return new Response(JSON.stringify({ cookie }), { headers: { 'Content-Type': 'application/json' } });
}
if (request.method === 'POST') {
const requestData = await request.json();
// 处理Cookie保存
if (requestData.cookie !== undefined) {
await SETTINGS_KV.put('QWEN_COOKIE', requestData.cookie);
return new Response(JSON.stringify({ success: true }), { headers: { 'Content-Type': 'application/json' } });
}
// 处理历史记录获取
if (requestData.action === 'get_history' && requestData.key) {
try {
const history = await SETTINGS_KV.get(requestData.key);
return new Response(JSON.stringify({
success: true,
history: history ? JSON.parse(history) : []
}), { headers: { 'Content-Type': 'application/json' } });
} catch (error) {
return new Response(JSON.stringify({
success: false,
error: '获取历史记录失败',
history: []
}), { headers: { 'Content-Type': 'application/json' } });
}
}
// 处理历史记录保存
if (requestData.action === 'save_history' && requestData.key && requestData.history) {
try {
await SETTINGS_KV.put(requestData.key, JSON.stringify(requestData.history));
return new Response(JSON.stringify({ success: true }), { headers: { 'Content-Type': 'application/json' } });
} catch (error) {
return new Response(JSON.stringify({
success: false,
error: '保存历史记录失败'
}), { headers: { 'Content-Type': 'application/json' } });
}
}
return new Response(JSON.stringify({ success: false, error: '无效的请求参数' }), {
status: 400,
headers: { 'Content-Type': 'application/json' }
});
}
break;
case '/api/recognize/url':
return await handleImageUrlRecognition(request);
case '/api/recognize/base64':
return await handleBase64Recognition(request);
case '/recognize':
return await handleFileRecognition(request);
case '/proxy/upload':
return await handleProxyUpload(request);
case '/api-docs':
return new Response(getApiDocsHTML(), { headers: { 'Content-Type': 'text/html; charset=utf-8' } });
case '/':
return new Response(getHTML(), { headers: { 'Content-Type': 'text/html; charset=utf-8' } });
}
return new Response('Not Found', { status: 404 });
} catch (e) {
console.error('[handleRequest] 错误:', e);
return new Response(JSON.stringify({
error: e.message,
stack: e.stack
}), {
status: 500,
headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }
});
}
}
// =================================================
// 3. API Handlers
// =================================================
// MODIFIED: This function now routes to Qwen or Gemini based on a header
async function handleImageUrlRecognition(request) {
try {
const model = request.headers.get('x-recognition-model') || '0';
const { imageUrl } = await request.json();
if (!imageUrl) return new Response(JSON.stringify({ error: 'Missing imageUrl' }), { status: 400 });
let customPrompt = '';
try {
const encodedPrompt = request.headers.get('x-custom-prompt');
if (encodedPrompt) customPrompt = decodeURIComponent(atob(encodedPrompt));
} catch (e) {}
if (model === '1') { // Gemini
const imageResponse = await fetch(imageUrl);
if (!imageResponse.ok) throw new Error(`Failed to fetch image from URL: ${imageResponse.statusText}`);
const imageBlob = await imageResponse.blob();
const buffer = await imageBlob.arrayBuffer();
// Convert buffer to base64
let binary = '';
const bytes = new Uint8Array(buffer);
for (let i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
const base64 = btoa(binary);
const defaultPrompt = 'Describe the image. If it is a math formula, output in LaTeX. If it is a captcha, output only the characters.';
const prompt = customPrompt || defaultPrompt;
const result = await recognizeWithGemini(base64, prompt);
return new Response(JSON.stringify({ success: true, result: result, type: 'text' }), { headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' } });
} else { // Qwen v2
const cookie = await getQwenCookie();
const tokenMatch = cookie.match(/token=([^;]+)/);
if (!tokenMatch) throw new Error('Invalid cookie format in KV: missing token');
const token = tokenMatch[1];
// 下载图片 - 添加浏览器请求头以避免 403 错误
const imageResponse = await fetch(imageUrl, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Referer': new URL(imageUrl).origin,
'Accept': 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
'Cache-Control': 'no-cache'
}
});
if (!imageResponse.ok) {
throw new Error(`Failed to fetch image: ${imageResponse.status} ${imageResponse.statusText}`);
}
const arrayBuffer = await imageResponse.arrayBuffer();
// 上传到 OSS
const uploadResult = await uploadFileToQwenOss(arrayBuffer, 'image.png', token);
if (!uploadResult || uploadResult.status !== 200) {
throw new Error('File upload to Qwen OSS failed');
}
// 使用上传后的 URL 进行识别
return await recognizeImage(token, uploadResult.file_url, request);
}
} catch (error) {
console.error('[handleImageUrlRecognition] 错误:', error);
return new Response(JSON.stringify({
error: error.message,
stack: error.stack
}), {
status: 500,
headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }
});
}
}
// MODIFIED: This function now routes to Qwen or Gemini based on a header
async function handleBase64Recognition(request) {
try {
const model = request.headers.get('x-recognition-model') || '0';
const { base64Image } = await request.json();
if (!base64Image) return new Response(JSON.stringify({ error: 'Missing base64Image' }), { status: 400 });
let customPrompt = '';
try {
const encodedPrompt = request.headers.get('x-custom-prompt');
if (encodedPrompt) customPrompt = decodeURIComponent(atob(encodedPrompt));
} catch (e) {}
if (model === '1') { // Gemini
const defaultPrompt = 'Describe the image. If it is a math formula, output in LaTeX. If it is a captcha, output only the characters.';
const prompt = customPrompt || defaultPrompt;
const result = await recognizeWithGemini(base64Image, prompt);
return new Response(JSON.stringify({ success: true, result: result, type: 'text' }), { headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' } });
} else { // Qwen v2
const cookie = await getQwenCookie();
const tokenMatch = cookie.match(/token=([^;]+)/);
if (!tokenMatch) throw new Error('Invalid cookie format in KV: missing token');
const token = tokenMatch[1];
// 将 base64 转换为 ArrayBuffer
const imageData = base64Image.startsWith('data:') ? base64Image : 'data:image/png;base64,' + base64Image;
const pureBase64 = imageData.replace(/^data:image\/\w+;base64,/, '');
const binaryString = atob(pureBase64);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
const arrayBuffer = bytes.buffer;
// 上传到 OSS
const uploadResult = await uploadFileToQwenOss(arrayBuffer, 'image.png', token);
if (!uploadResult || uploadResult.status !== 200) {
throw new Error('File upload to Qwen OSS failed');
}
// 使用上传后的 URL 进行识别
return await recognizeImage(token, uploadResult.file_url, request);
}
} catch (error) {
console.error('[handleBase64Recognition] 错误:', error);
return new Response(JSON.stringify({
error: error.message,
stack: error.stack
}), {
status: 500,
headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }
});
}
}
async function handleFileRecognition(request) {
try {
const { imageId } = await request.json();
if (!imageId) return new Response(JSON.stringify({ error: 'Missing imageId' }), { status: 400 });
const cookie = await getQwenCookie();
const tokenMatch = cookie.match(/token=([^;]+)/);
if (!tokenMatch) throw new Error('Invalid cookie format: missing token');
const token = tokenMatch[1];
// imageId 现在应该是 OSS URL
return await recognizeImage(token, imageId, request);
} catch (error) {
console.error('[handleFileRecognition] 错误:', error);
return new Response(JSON.stringify({
error: error.message,
stack: error.stack
}), {
status: 500,
headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }
});
}
}
async function handleProxyUpload(request) {
try {
const formData = await request.formData();
const file = formData.get('file');
if (!file) {
return new Response(JSON.stringify({ error: 'No file uploaded' }), { status: 400 });
}
const cookie = await getQwenCookie();
const tokenMatch = cookie.match(/token=([^;]+)/);
if (!tokenMatch) throw new Error('Invalid cookie format: missing token');
const token = tokenMatch[1];
// 读取文件内容
const arrayBuffer = await file.arrayBuffer();
// 上传到 OSS
const uploadResult = await uploadFileToQwenOss(arrayBuffer, file.name, token);
return new Response(JSON.stringify({
success: true,
id: uploadResult.file_url, // 返回 URL 作为 ID
url: uploadResult.file_url
}), {
headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }
});
} catch (error) {
console.error('文件上传失败:', error);
return new Response(JSON.stringify({ error: error.message }), {
status: 500,
headers: { 'Content-Type': 'application/json' }
});
}
}
// =================================================
// 2.5. Qwen v2 对话处理函数
// =================================================
/**
* 处理 /v1/chat/completions 请求
*/
async function handleChatCompletions(request) {
try {
const body = await request.json();
const { model, messages, stream, enable_thinking, thinking_budget } = body;
// 获取 Qwen Cookie
const cookie = await getQwenCookie();
const tokenMatch = cookie.match(/token=([^;]+)/);
if (!tokenMatch) {
throw new Error('Invalid cookie format: missing token');
}
const token = tokenMatch[1];
// 解析模型和聊天类型
const parsedModel = parserModel(model);
const chatType = isChatType(model);
const thinkingConfig = isThinkingEnabled(model, enable_thinking, thinking_budget);
// 解析消息
const parsedMessages = await parserMessages(messages, thinkingConfig, chatType, token);
// 构建请求体
const requestBody = {
model: parsedModel,
messages: parsedMessages,
stream: stream !== false,
session_id: generateUUID(),
id: generateUUID()
};
// 发送请求
const response = await sendChatRequest(requestBody, token);
// 检查响应的 Content-Type
const contentType = response.headers.get('content-type') || '';
const isStreamResponse = contentType.includes('text/event-stream') || contentType.includes('stream');
if (stream !== false && isStreamResponse) {
// 流式响应
return new Response(response.body, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin': '*'
}
});
} else {
// 非流式响应或需要转换流式响应为非流式
if (isStreamResponse) {
// 如果 API 返回流式但用户要求非流式,需要解析流式数据
const reader = response.body.getReader();
const decoder = new TextDecoder();
let fullContent = '';
let responseMetadata = null;
let buffer = '';
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) {
const trimmedLine = line.trim();
if (!trimmedLine) continue;
if (trimmedLine.startsWith('data: ')) {
const data = trimmedLine.slice(6);
if (data === '[DONE]') continue;
try {
const parsed = JSON.parse(data);
// 保存元数据(第一次遇到时)
if (!responseMetadata) {
responseMetadata = {
success: parsed.success,
request_id: parsed.request_id,
data: {
chat_id: parsed.data?.chat_id,
parent_id: parsed.data?.parent_id,
message_id: parsed.data?.message_id
}
};
}
// 提取内容
let deltaContent = parsed.data?.choices?.[0]?.delta?.content ||
parsed.choices?.[0]?.delta?.content || '';
if (deltaContent) {
// 只累加增量内容
if (chatType === 't2i' || chatType === 't2v') {
if (!fullContent) {
fullContent = deltaContent;
}
} else {
fullContent += deltaContent;
}
} else {
// 如果没有 deltaContent,再尝试获取一次完整的 message.content
// 这可以作为一种兼容和回退机制
let messageContent = parsed.data?.choices?.[0]?.message?.content ||
parsed.choices?.[0]?.message?.content || '';
if (messageContent && !fullContent) { // 关键:仅在 fullContent 为空时才赋值
fullContent = messageContent;
}
}
} catch (e) {
console.error('解析流式数据失败:', e, '数据:', data.substring(0, 100));
}
} else if (trimmedLine.startsWith('response.created:')) {
// 处理 response.created 事件
try {
const data = trimmedLine.slice(17).trim();
const parsed = JSON.parse(data);
if (!responseMetadata) {
responseMetadata = {
success: true,
data: parsed
};
}
} catch (e) {
console.error('解析 response.created 失败:', e);
}
}
}
}
// 构建非流式响应
const finalResponse = responseMetadata || { success: true, data: {} };
// 确保有 choices 数组
if (!finalResponse.data.choices) {
finalResponse.data.choices = [{
message: {
role: 'assistant',
content: fullContent || '生成完成'
}
}];
} else {
// 更新现有的 choices
finalResponse.data.choices[0] = {
...finalResponse.data.choices[0],
message: {
role: 'assistant',
content: fullContent || '生成完成'
}
};
delete finalResponse.data.choices[0].delta;
}
return new Response(JSON.stringify(finalResponse), {
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
}
});
} else {
// 真正的非流式响应
const data = await response.json();
return new Response(JSON.stringify(data), {
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
}
});
}
}
} catch (error) {
console.error('Chat completions error:', error);
return new Response(JSON.stringify({