-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathworker.js
More file actions
685 lines (625 loc) · 22.5 KB
/
worker.js
File metadata and controls
685 lines (625 loc) · 22.5 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
//需要对特定微信鉴权的,请在[]中填写对应微信ID
//类似:const WXID_ARRAY = ['wxid_abcdefg','lambous','yourxxx','abdcedf']
//[]内不添加微信ID则表示不进行鉴权
const WXID_ARRAY = [];
//360 API Key
const APIKEY360 = "";
// 定义各种AI类
class Gemini {
constructor(requestModel, requestAuthorization, requestMessages) {
//如果需要,先部署Netlify反向代理
//填写反代域名,类似:https://xxx.netlify.app,需要填"https://"
this.proxyUrl = '';
this.model = requestModel;
this.authorization = requestAuthorization ? requestAuthorization.replace('Bearer ', '') : '';
if (this.model === "gemini") {
this.model = 'gemini-pro';
}
if (this.proxyUrl !== '') {
this.url = `${this.proxyUrl}/v1beta/models/${this.model}:generateContent?key=${this.authorization}`;
} else {
this.url = `https://generativelanguage.googleapis.com/v1beta/models/${this.model}:generateContent?key=${this.authorization}`;
}
this.formatHeaders();
try {
this.formatBody(requestMessages);
} catch (error) {
console.error('Error formatting body:', error);
}
}
formatHeaders() {
// 检查是否已经存在 headers,如果存在则不重新初始化
if (!this.headers) {
this.headers = {'Content-Type': 'application/json'};
}
}
formatBody(requestMessages) {
try {
// 确保this.body是对象类型,否则进行初始化
if (typeof this.body !== 'object' || this.body === null) {
this.body = {};
}
let formattedMessages = [];
requestMessages.forEach((item, index) => {
if (index === 0) {
formattedMessages.push({
'role': 'user',
'parts': [{
'text': item.content,
}],
}, {
'role': 'model',
'parts': [{
'text': '好的',
}],
});
} else if (index === 1 && item.role === 'assistant') {
// 忽略掉第二条消息
} else {
formattedMessages.push({
'role': (item.role === 'assistant') ? 'model' : 'user',
'parts': [{
'text': item.content,
}],
});
}
});
this.messages = formattedMessages;
// 将格式化后的 messages 转换为自己格式的 body
this.body = {
'contents': this.messages,
"safetySettings": [{
"category": "HARM_CATEGORY_HARASSMENT",
"threshold": "BLOCK_NONE"
}, {
"category": "HARM_CATEGORY_HATE_SPEECH",
"threshold": "BLOCK_NONE"
}, {
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
"threshold": "BLOCK_NONE"
}, {
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
"threshold": "BLOCK_NONE"
}
],
};
} catch (error) {
console.error('Error formatting messages:', error);
throw error;
}
}
handleResponse(responseData) {
// 判断是否存在 responseData.candidates
if (responseData.candidates && responseData.candidates.length > 0) {
// 检查是否存在 responseData.candidates[0].content.parts[0].text
if (responseData.candidates[0].content && responseData.candidates[0].content.parts &&
responseData.candidates[0].content.parts.length > 0) {
// 返回 Gemini API 的响应文本
return responseData.candidates[0].content.parts[0].text;
} else {
// 返回错误信息,指示无法获取有效的响应文本
return `${this.model} API 返回未知错误: 无法获取有效的响应文本`;
}
} else if (responseData.error) {
// 处理错误逻辑
const errorMessage = responseData.error.message || '未知错误';
return `${this.model} API 错误: ${errorMessage}`;
} else {
// 返回错误信息,指示无法获取有效的响应
return `${this.model} API 返回未知错误: 无法获取有效的响应`;
}
}
}
class ChatGPT {
constructor(requestModel, requestAuthorization, requestMessages) {
this.model = requestModel;
this.authorization = requestAuthorization;
this.url = 'https://api.openai.com/v1/chat/completions';
this.formatHeaders();
try {
this.formatBody(requestMessages);
} catch (error) {
console.error('Error formatting body:', error);
throw error;
}
}
formatHeaders() {
// 检查是否已经存在 headers,如果存在则不重新初始化
if (!this.headers) {
this.headers = {
'Content-Type': 'application/json',
'Authorization': this.authorization,
};
}
}
formatBody(requestMessages) {
try {
// 确保this.body是对象类型,否则进行初始化
if (typeof this.body !== 'object' || this.body === null) {
this.body = {};
}
// 将格式化后的 messages 转换为自己格式的 body
this.body = {
'model': this.model,
'messages': requestMessages,
};
} catch (error) {
console.error('Error formatting messages:', error);
throw error;
}
}
handleResponse(responseData) {
// 判断是否有错误信息
if (responseData.error) {
// 处理错误逻辑
const errorMessage = responseData.error.message || '未知错误';
return `${this.model}: ${errorMessage}`;
}
// 检查响应结构是否符合预期
if (responseData.choices && responseData.choices.length > 0 && responseData.choices[0].message && responseData.choices[0].message.content) {
return responseData.choices[0].message.content;
} else {
// 响应结构不符合预期,返回错误信息
return `${this.model}: 无法解析响应数据`;
}
}
}
class DeepSeek {
constructor(requestModel, requestAuthorization, requestMessages) {
this.model = requestModel;
this.authorization = requestAuthorization;
this.url = 'https://api.deepseek.com/chat/completions';
this.formatHeaders();
try {
this.formatBody(requestMessages);
} catch (error) {
console.error('Error formatting body:', error);
throw error;
}
}
formatHeaders() {
// 检查是否已经存在 headers,如果存在则不重新初始化
if (!this.headers) {
this.headers = {
'Content-Type': 'application/json',
'Authorization': this.authorization,
};
}
}
formatBody(requestMessages) {
try {
// 确保this.body是对象类型,否则进行初始化
if (typeof this.body !== 'object' || this.body === null) {
this.body = {};
}
// 将格式化后的 messages 转换为自己格式的 body
this.body = {
'model': this.model,
'messages': requestMessages,
};
} catch (error) {
console.error('Error formatting messages:', error);
throw error;
}
}
handleResponse(responseData) {
// 判断是否有错误信息
if (responseData.error) {
// 处理错误逻辑
const errorMessage = responseData.error.message || '未知错误';
return `${this.model}: ${errorMessage}`;
}
// 检查响应结构是否符合预期
if (responseData.choices && responseData.choices.length > 0 && responseData.choices[0].message && responseData.choices[0].message.content) {
return responseData.choices[0].message.content;
} else {
// 响应结构不符合预期,返回错误信息
return `${this.model}: 无法解析响应数据`;
}
}
}
class Claude3 {
constructor(requestModel, requestAuthorization, requestMessages) {
this.model = requestModel;
this.authorization = requestAuthorization ? requestAuthorization.replace('Bearer ', '') : '';
this.url = 'https://api.anthropic.com/v1/messages';
this.formatHeaders();
try {
this.formatBody(requestMessages);
} catch (error) {
console.error('Error formatting body:', error);
}
}
formatHeaders() {
// 检查是否已经存在 headers,如果存在则不重新初始化
if (!this.headers) {
this.headers = {
'x-api-key': this.authorization,
'anthropic-version': '2023-06-01',
'Content-Type': 'application/json'
};
}
}
formatBody(requestMessages) {
try {
// 确保this.body是对象类型,否则进行初始化
if (typeof this.body !== 'object' || this.body === null) {
this.body = {};
}
let formattedMessages = [];
requestMessages.forEach((item, index) => {
if (index === 0 && item.role === 'system') {
let itemContent = item.content.trim();
this.system = itemContent;
//Claude3的Message没有"system" role
} else if (index === 1 && item.role === 'assistant') {
// Claude3的Message开头必须是user role
} else {
formattedMessages.push({
'role': item.role,
'content': item.content,
});
}
});
this.messages = formattedMessages;
// 将格式化后的 messages 转换为自己格式的 body
this.body = {
'model': this.model,
'max_tokens': 1024,
'messages': this.messages,
};
// 检查 this.system 是否为空,如果不为空,则添加到 body 对象中
if (this.system !== undefined && this.system !== null && this.system !== '') {
this.body['system'] = this.system;
}
} catch (error) {
console.error('Error formatting messages:', error);
throw error;
}
}
handleResponse(responseData) {
// 判断是否有错误信息
if (responseData.error) {
// 处理错误逻辑
const errorMessage = responseData.error.message || '未知错误';
return `${this.model}: ${errorMessage}`;
}
// 检查响应结构是否符合预期
if (responseData.content && responseData.content.length > 0 && responseData.content[0].text) {
return responseData.content[0].text;
} else {
// 响应结构不符合预期,返回错误信息
return `${this.model}: 无法解析响应数据`;
}
}
}
class GPT360 {
constructor(requestModel, requestAuthorization, requestMessages) {
this.model = requestModel;
this.authorization = requestAuthorization;
this.url = 'https://api.360.cn/v1/chat/completions';
this.text2img = false;
this.formatHeaders();
try {
// 获取最后一条消息
const lastMessage = requestMessages[requestMessages.length - 1].content.trim();
// 判断是否需要文生图模式
if (lastMessage.startsWith('画')) {
this.url = 'https://api.360.cn/v1/images/text2img';
this.model = '360CV_S0_V5';
this.text2img = true;
this.formatBodyText2Img(lastMessage);
} else {
this.formatBody(requestMessages);
}
} catch (error) {
console.error('Error formatting body:', error);
throw error;
}
}
formatHeaders() {
// 检查是否已经存在 headers,如果存在则不重新初始化
if (!this.headers) {
this.headers = {
'Content-Type': 'application/json',
'Authorization': this.authorization,
};
}
}
formatBody(requestMessages) {
try {
// 确保this.body是对象类型,否则进行初始化
if (typeof this.body !== 'object' || this.body === null) {
this.body = {};
}
// 将格式化后的 messages 转换为自己格式的 body
this.body = {
'model': this.model,
'messages': requestMessages,
'stream': false,
"tools":[
{
"type":"web_search",
"web_search":{
"search_mode":"auto",
"search_query":requestMessages[requestMessages.length - 1].content.trim()
}
}
]
};
} catch (error) {
console.error('Error formatting messages:', error);
throw error;
}
}
formatBodyText2Img(lastMessage) {
try {
// 确保this.body是对象类型,否则进行初始化
if (typeof this.body !== 'object' || this.body === null) {
this.body = {};
}
// 将提取的 lastMessage 转换为文生图格式的 body
this.body = {
"model": "360CV_S0_V5",
"style": "realistic",
"prompt": lastMessage.substring(1),
"negative_prompt": "",
"guidance_scale": 15,
"height": 1920,
"width": 1080,
"num_inference_steps": 50,
"samples": 1,
"enhance_prompt": true
};
} catch (error) {
console.error('Error formatting messages:', error);
throw error;
}
}
handleResponse(responseData) {
// 判断是否有错误信息
if (responseData.error) {
// 处理错误逻辑
const errorMessage = responseData.error.message || '未知错误';
return `${this.model}: ${errorMessage}`;
}
if (!this.text2img) {
// 文本聊天模式
if (responseData.choices && responseData.choices.length > 0 && responseData.choices[0].message && responseData.choices[0].message.content) {
return responseData.choices[0].message.content;
} else {
return `${this.model}: 无法解析响应数据`;
}
} else {
// 文生图模式
if (responseData.status === 'success' && responseData.output) {
if (responseData.output.length > 0){
return responseData.output[0];
} else {
return '鉴于关键词过滤原因,无法根据您的关键词生图';
}
} else {
return `${this.model}: 无法解析响应数据`;
}
}
}
}
class Kimi {
constructor(requestModel, requestAuthorization, requestMessages) {
this.model = requestModel;
this.authorization = requestAuthorization;
this.url = 'https://api.moonshot.cn/v1/chat/completions';
this.formatHeaders();
try {
this.formatBody(requestMessages);
} catch (error) {
console.error('Error formatting body:', error);
throw error;
}
}
formatHeaders() {
// 检查是否已经存在 headers,如果存在则不重新初始化
if (!this.headers) {
this.headers = {
'Content-Type': 'application/json',
'Authorization': this.authorization,
};
}
}
formatBody(requestMessages) {
try {
// 确保this.body是对象类型,否则进行初始化
if (typeof this.body !== 'object' || this.body === null) {
this.body = {};
}
// 将格式化后的 messages 转换为自己格式的 body
this.body = {
'model': this.model,
'messages': requestMessages,
'temperature': 0.3,
};
} catch (error) {
console.error('Error formatting messages:', error);
throw error;
}
}
handleResponse(responseData) {
// 判断是否有错误信息
if (responseData.error) {
// 处理错误逻辑
const errorMessage = responseData.error.message || '未知错误';
return `${this.model}: ${errorMessage}`;
}
// 检查响应结构是否符合预期
if (responseData.choices && responseData.choices.length > 0 && responseData.choices[0].message && responseData.choices[0].message.content) {
return responseData.choices[0].message.content;
} else {
// 响应结构不符合预期,返回错误信息
return `${this.model}: 无法解析响应数据`;
}
}
}
class Qwen {
constructor(requestModel, requestAuthorization, requestMessages) {
this.model = requestModel;
this.authorization = requestAuthorization;
this.url = 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation';
this.formatHeaders();
this.formatBody(requestMessages);
}
formatHeaders() {
// 检查是否已经存在 headers,如果存在则不重新初始化
if (!this.headers) {
this.headers = {
'Content-Type': 'application/json',
'Authorization': this.authorization,
};
}
}
formatBody(requestMessages) {
try {
// 确保this.body是对象类型,否则进行初始化
if (typeof this.body !== 'object' || this.body === null) {
this.body = {};
}
let formattedMessages = [];
requestMessages.forEach((item, index) => {
if (index === 0 && item.role === 'system') {
let itemContent = item.content.trim();
if (itemContent === "") {
itemContent = '你是通义千问';
}
formattedMessages.push({
'role': 'system',
'content': itemContent,
});
} else if (index === 1 && item.role === 'assistant') {
// 忽略掉第二条消息
} else {
formattedMessages.push({
'role': item.role,
'content': item.content,
});
}
});
this.messages = formattedMessages;
// 将格式化后的 messages 转换为自己格式的 body
this.body = {
'model': this.model,
'input': {
'messages': this.messages,
},
'parameters': {},
};
} catch (error) {
console.error('Error formatting messages:', error);
throw error;
}
}
handleResponse(responseData) {
// 判断是否有错误信息
if (responseData.code) {
// 处理错误逻辑
const errorCode = responseData.code;
const errorMessage = responseData.message || '未知错误';
return `${this.model}: ${errorCode} - ${errorMessage}`;
}
if (responseData.errorType) {
// 处理错误逻辑
const errorType = responseData.errorType;
const errorMessage2 = responseData.errorMessage || '未知错误';
return `${this.model}: ${errorType} - ${errorMessage2}`;
}
// 检查是否存在 responseData.output.text
if (responseData.output && responseData.output.text) {
// 返回 Qwen API 的响应
return responseData.output.text;
} else {
// 返回错误信息,指示无法获取有效的响应文本
return `${this.model}: 无法获取有效的响应文本`;
}
}
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
// 全局范围定义 supportedModels(支持的模型),格式:'模型名称':对应的AI类
const supportedModels = {
'gpt-3.5-turbo': ChatGPT,
'gpt-4': ChatGPT,
'GPT-4o': ChatGPT,
'gemini-pro': Gemini,
'gemini': Gemini,
'gemini-1.5-pro-latest': Gemini,
'gemini-1.5-flash': Gemini,
'gemini-2.0-flash-exp': Gemini,
'qwen-turbo': Qwen,
'qwen-max': Qwen,
'moonshot-v1-8k': Kimi,
'moonshot-v1-32k': Kimi,
'claude-3-opus-20240229': Claude3,
'360gpt-pro': GPT360,
'deepseek-chat': DeepSeek,
'deepseek-reasoner': DeepSeek
};
//把回应给WeChat Assistant信息格式化为微信助手可以识别的Json
function respondJsonMessage(message) {
const jsonMessage = {
choices: [{
message: {
role: 'assistant',
content: message,
},
}
],
};
return new Response(JSON.stringify(jsonMessage), {
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
});
}
async function handleRequest(request) {
try {
//Only for WeChat Assistant
const wxid = request.headers.get('wxid');
if (!wxid) {
throw new Error('您的请求不兼容于本服务');
}
//WeChat ID authorization
if (WXID_ARRAY.length > 0 && !WXID_ARRAY.includes(wxid)) {
return respondJsonMessage('当您看到这个信息,说明您需要联系本服务提供者进行使用授权');
}
let requestAuthorization = request.headers.get('authorization');
if (!requestAuthorization) {
throw new Error('请提供API鉴权码');
}
const requestBody = await request.json();
let requestModel = requestBody.model.toLowerCase().trim();
const requestMessages = requestBody.messages;
const lastMessage = requestMessages[requestMessages.length - 1].content.trim();
// 判断是否需要文生图模式
if (APIKEY360.length > 0 && lastMessage.startsWith("画")) {
requestModel = "360gpt-pro";
requestAuthorization = APIKEY360;
}
let response;
const ModelClass = supportedModels[requestModel];
if (ModelClass) {
const modelInstance = new ModelClass(requestModel, requestAuthorization, requestMessages);
const fetchResponse = await fetch(modelInstance.url, {
method: 'POST',
headers: modelInstance.headers,
body: JSON.stringify(modelInstance.body)
});
const responseData = await fetchResponse.json();
response = await modelInstance.handleResponse(responseData);
return respondJsonMessage(response);
} else {
return respondJsonMessage('不支持的 chat_model 类型');
}
} catch (error) {
console.error('Error:', error.toString()); // 记录错误信息
return respondJsonMessage(`出错了: ${error.toString()}`);
}
}