forked from TBXark/ChatGPT-Telegram-Workers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
2863 lines (2824 loc) · 87.9 KB
/
index.js
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
class ConfigMerger {
static parseArray(raw) {
raw = raw.trim();
if (raw === "") {
return [];
}
if (raw.startsWith("[") && raw.endsWith("]")) {
try {
return JSON.parse(raw);
} catch (e) {
console.error(e);
}
}
return raw.split(",");
}
static trim(source, lock) {
const config = { ...source };
const keysSet = new Set(source?.DEFINE_KEYS || []);
for (const key of lock) {
keysSet.delete(key);
}
keysSet.add("DEFINE_KEYS");
for (const key of Object.keys(config)) {
if (!keysSet.has(key)) {
delete config[key];
}
}
return config;
}
static merge(target, source, exclude) {
const sourceKeys = new Set(Object.keys(source));
for (const key of Object.keys(target)) {
if (!sourceKeys.has(key)) {
continue;
}
if (exclude && exclude.includes(key)) {
continue;
}
const t = target[key] !== null && target[key] !== void 0 ? typeof target[key] : "string";
if (typeof source[key] !== "string") {
target[key] = source[key];
continue;
}
switch (t) {
case "number":
target[key] = Number.parseInt(source[key], 10);
break;
case "boolean":
target[key] = (source[key] || "false") === "true";
break;
case "string":
target[key] = source[key];
break;
case "object":
if (Array.isArray(target[key])) {
target[key] = ConfigMerger.parseArray(source[key]);
} else {
try {
target[key] = JSON.parse(source[key]);
} catch (e) {
console.error(e);
}
}
break;
default:
target[key] = source[key];
break;
}
}
}
}
const zhHans = { "env": { "system_init_message": "你是一个得力的助手" }, "command": { "help": { "summary": "当前支持以下命令:\n", "help": "获取命令帮助", "new": "发起新的对话", "start": "获取你的ID, 并发起新的对话", "img": "生成一张图片, 命令完整格式为 `/img 图片描述`, 例如`/img 月光下的沙滩`", "version": "获取当前版本号, 判断是否需要更新", "setenv": "设置用户配置,命令完整格式为 /setenv KEY=VALUE", "setenvs": '批量设置用户配置, 命令完整格式为 /setenvs {"KEY1": "VALUE1", "KEY2": "VALUE2"}', "delenv": "删除用户配置,命令完整格式为 /delenv KEY", "clearenv": "清除所有用户配置", "system": "查看当前一些系统信息", "redo": "重做上一次的对话, /redo 加修改过的内容 或者 直接 /redo", "echo": "回显消息" }, "new": { "new_chat_start": "新的对话已经开始" } } };
const zhHant = { "env": { "system_init_message": "你是一個得力的助手" }, "command": { "help": { "summary": "當前支持的命令如下:\n", "help": "獲取命令幫助", "new": "開始一個新對話", "start": "獲取您的ID並開始一個新對話", "img": "生成圖片,完整命令格式為`/img 圖片描述`,例如`/img 海灘月光`", "version": "獲取當前版本號確認是否需要更新", "setenv": "設置用戶配置,完整命令格式為/setenv KEY=VALUE", "setenvs": '批量設置用户配置, 命令完整格式為 /setenvs {"KEY1": "VALUE1", "KEY2": "VALUE2"}', "delenv": "刪除用戶配置,完整命令格式為/delenv KEY", "clearenv": "清除所有用戶配置", "system": "查看一些系統信息", "redo": "重做上一次的對話 /redo 加修改過的內容 或者 直接 /redo", "echo": "回显消息" }, "new": { "new_chat_start": "開始一個新對話" } } };
const pt = { "env": { "system_init_message": "Você é um assistente útil" }, "command": { "help": { "summary": "Os seguintes comandos são suportados atualmente:\n", "help": "Obter ajuda sobre comandos", "new": "Iniciar uma nova conversa", "start": "Obter seu ID e iniciar uma nova conversa", "img": "Gerar uma imagem, o formato completo do comando é `/img descrição da imagem`, por exemplo `/img praia ao luar`", "version": "Obter o número da versão atual para determinar se é necessário atualizar", "setenv": "Definir configuração do usuário, o formato completo do comando é /setenv CHAVE=VALOR", "setenvs": 'Definir configurações do usuário em lote, o formato completo do comando é /setenvs {"CHAVE1": "VALOR1", "CHAVE2": "VALOR2"}', "delenv": "Excluir configuração do usuário, o formato completo do comando é /delenv CHAVE", "clearenv": "Limpar todas as configurações do usuário", "system": "Ver algumas informações do sistema", "redo": "Refazer a última conversa, /redo com conteúdo modificado ou diretamente /redo", "echo": "Repetir a mensagem" }, "new": { "new_chat_start": "Uma nova conversa foi iniciada" } } };
const en = { "env": { "system_init_message": "You are a helpful assistant" }, "command": { "help": { "summary": "The following commands are currently supported:\n", "help": "Get command help", "new": "Start a new conversation", "start": "Get your ID and start a new conversation", "img": "Generate an image, the complete command format is `/img image description`, for example `/img beach at moonlight`", "version": "Get the current version number to determine whether to update", "setenv": "Set user configuration, the complete command format is /setenv KEY=VALUE", "setenvs": 'Batch set user configurations, the full format of the command is /setenvs {"KEY1": "VALUE1", "KEY2": "VALUE2"}', "delenv": "Delete user configuration, the complete command format is /delenv KEY", "clearenv": "Clear all user configuration", "system": "View some system information", "redo": "Redo the last conversation, /redo with modified content or directly /redo", "echo": "Echo the message" }, "new": { "new_chat_start": "A new conversation has started" } } };
function loadI18n(lang) {
switch (lang?.toLowerCase()) {
case "cn":
case "zh-cn":
case "zh-hans":
return zhHans;
case "zh-tw":
case "zh-hk":
case "zh-mo":
case "zh-hant":
return zhHant;
case "pt":
case "pt-br":
return pt;
case "en":
case "en-us":
return en;
default:
return en;
}
}
class EnvironmentConfig {
LANGUAGE = "zh-cn";
UPDATE_BRANCH = "master";
CHAT_COMPLETE_API_TIMEOUT = 0;
TELEGRAM_API_DOMAIN = "https://api.telegram.org";
TELEGRAM_AVAILABLE_TOKENS = [];
DEFAULT_PARSE_MODE = "Markdown";
TELEGRAM_MIN_STREAM_INTERVAL = 0;
TELEGRAM_PHOTO_SIZE_OFFSET = 1;
TELEGRAM_IMAGE_TRANSFER_MODE = "url";
I_AM_A_GENEROUS_PERSON = false;
CHAT_WHITE_LIST = [];
LOCK_USER_CONFIG_KEYS = [
"OPENAI_API_BASE",
"GOOGLE_COMPLETIONS_API",
"MISTRAL_API_BASE",
"COHERE_API_BASE",
"ANTHROPIC_API_BASE",
"AZURE_COMPLETIONS_API",
"AZURE_DALLE_API"
];
TELEGRAM_BOT_NAME = [];
CHAT_GROUP_WHITE_LIST = [];
GROUP_CHAT_BOT_ENABLE = true;
GROUP_CHAT_BOT_SHARE_MODE = true;
AUTO_TRIM_HISTORY = true;
MAX_HISTORY_LENGTH = 20;
MAX_TOKEN_LENGTH = -1;
HISTORY_IMAGE_PLACEHOLDER = null;
HIDE_COMMAND_BUTTONS = [];
SHOW_REPLY_BUTTON = false;
EXTRA_MESSAGE_CONTEXT = false;
STREAM_MODE = true;
SAFE_MODE = true;
DEBUG_MODE = false;
DEV_MODE = false;
}
class AgentShareConfig {
AI_PROVIDER = "auto";
AI_IMAGE_PROVIDER = "auto";
SYSTEM_INIT_MESSAGE = null;
SYSTEM_INIT_MESSAGE_ROLE = "system";
}
class OpenAIConfig {
OPENAI_API_KEY = [];
OPENAI_CHAT_MODEL = "gpt-4o-mini";
OPENAI_API_BASE = "https://api.openai.com/v1";
OPENAI_API_EXTRA_PARAMS = {};
}
class DalleAIConfig {
DALL_E_MODEL = "dall-e-2";
DALL_E_IMAGE_SIZE = "512x512";
DALL_E_IMAGE_QUALITY = "standard";
DALL_E_IMAGE_STYLE = "vivid";
}
class AzureConfig {
AZURE_API_KEY = null;
AZURE_COMPLETIONS_API = null;
AZURE_DALLE_API = null;
}
class WorkersConfig {
CLOUDFLARE_ACCOUNT_ID = null;
CLOUDFLARE_TOKEN = null;
WORKERS_CHAT_MODEL = "@cf/mistral/mistral-7b-instruct-v0.1 ";
WORKERS_IMAGE_MODEL = "@cf/stabilityai/stable-diffusion-xl-base-1.0";
}
class GeminiConfig {
GOOGLE_API_KEY = null;
GOOGLE_COMPLETIONS_API = "https://generativelanguage.googleapis.com/v1beta/models/";
GOOGLE_COMPLETIONS_MODEL = "gemini-pro";
}
class MistralConfig {
MISTRAL_API_KEY = null;
MISTRAL_API_BASE = "https://api.mistral.ai/v1";
MISTRAL_CHAT_MODEL = "mistral-tiny";
}
class CohereConfig {
COHERE_API_KEY = null;
COHERE_API_BASE = "https://api.cohere.com/v1";
COHERE_CHAT_MODEL = "command-r-plus";
}
class AnthropicConfig {
ANTHROPIC_API_KEY = null;
ANTHROPIC_API_BASE = "https://api.anthropic.com/v1";
ANTHROPIC_CHAT_MODEL = "claude-3-haiku-20240307";
}
class DefineKeys {
DEFINE_KEYS = [];
}
function createAgentUserConfig() {
return Object.assign(
{},
new DefineKeys(),
new AgentShareConfig(),
new OpenAIConfig(),
new DalleAIConfig(),
new AzureConfig(),
new WorkersConfig(),
new GeminiConfig(),
new MistralConfig(),
new CohereConfig(),
new AnthropicConfig()
);
}
const ENV_KEY_MAPPER = {
CHAT_MODEL: "OPENAI_CHAT_MODEL",
API_KEY: "OPENAI_API_KEY",
WORKERS_AI_MODEL: "WORKERS_CHAT_MODEL"
};
class Environment extends EnvironmentConfig {
BUILD_TIMESTAMP = 1726714840 ;
BUILD_VERSION = "bb11947" ;
I18N = loadI18n();
PLUGINS_ENV = {};
USER_CONFIG = createAgentUserConfig();
CUSTOM_COMMAND = {};
PLUGINS_COMMAND = {};
DATABASE = null;
API_GUARD = null;
merge(source) {
this.DATABASE = source.DATABASE;
this.API_GUARD = source.API_GUARD;
this.mergeCommands(
"CUSTOM_COMMAND_",
"COMMAND_DESCRIPTION_",
"COMMAND_SCOPE_",
source,
this.CUSTOM_COMMAND
);
this.mergeCommands(
"PLUGIN_COMMAND_",
"PLUGIN_DESCRIPTION_",
"PLUGIN_SCOPE_",
source,
this.PLUGINS_COMMAND
);
const pluginEnvPrefix = "PLUGIN_ENV_";
for (const key of Object.keys(source)) {
if (key.startsWith(pluginEnvPrefix)) {
const plugin = key.substring(pluginEnvPrefix.length);
this.PLUGINS_ENV[plugin] = source[key];
}
}
ConfigMerger.merge(this, source, [
"BUILD_TIMESTAMP",
"BUILD_VERSION",
"I18N",
"PLUGINS_ENV",
"USER_CONFIG",
"CUSTOM_COMMAND",
"PLUGINS_COMMAND",
"DATABASE",
"API_GUARD"
]);
ConfigMerger.merge(this.USER_CONFIG, source);
this.migrateOldEnv(source);
this.USER_CONFIG.DEFINE_KEYS = [];
this.I18N = loadI18n(this.LANGUAGE.toLowerCase());
}
mergeCommands(prefix, descriptionPrefix, scopePrefix, source, target) {
for (const key of Object.keys(source)) {
if (key.startsWith(prefix)) {
const cmd = key.substring(prefix.length);
target[`/${cmd}`] = {
value: source[key],
description: source[`${descriptionPrefix}${cmd}`],
scope: source[`${scopePrefix}${cmd}`]?.split(",").map((s) => s.trim())
};
}
}
}
migrateOldEnv(source) {
if (source.TELEGRAM_TOKEN && !this.TELEGRAM_AVAILABLE_TOKENS.includes(source.TELEGRAM_TOKEN)) {
if (source.BOT_NAME && this.TELEGRAM_AVAILABLE_TOKENS.length === this.TELEGRAM_BOT_NAME.length) {
this.TELEGRAM_BOT_NAME.push(source.BOT_NAME);
}
this.TELEGRAM_AVAILABLE_TOKENS.push(source.TELEGRAM_TOKEN);
}
if (source.OPENAI_API_DOMAIN && !this.USER_CONFIG.OPENAI_API_BASE) {
this.USER_CONFIG.OPENAI_API_BASE = `${source.OPENAI_API_DOMAIN}/v1`;
}
if (source.WORKERS_AI_MODEL && !this.USER_CONFIG.WORKERS_CHAT_MODEL) {
this.USER_CONFIG.WORKERS_CHAT_MODEL = source.WORKERS_AI_MODEL;
}
if (source.API_KEY && this.USER_CONFIG.OPENAI_API_KEY.length === 0) {
this.USER_CONFIG.OPENAI_API_KEY = source.API_KEY.split(",");
}
if (source.CHAT_MODEL && !this.USER_CONFIG.OPENAI_CHAT_MODEL) {
this.USER_CONFIG.OPENAI_CHAT_MODEL = source.CHAT_MODEL;
}
if (!this.USER_CONFIG.SYSTEM_INIT_MESSAGE) {
this.USER_CONFIG.SYSTEM_INIT_MESSAGE = this.I18N?.env?.system_init_message || "You are a helpful assistant";
}
}
}
const ENV = new Environment();
class ShareContext {
botId;
botToken;
botName = null;
chatHistoryKey;
lastMessageKey;
configStoreKey;
groupAdminsKey;
constructor(token, message) {
const botId = Number.parseInt(token.split(":")[0]);
const telegramIndex = ENV.TELEGRAM_AVAILABLE_TOKENS.indexOf(token);
if (telegramIndex === -1) {
throw new Error("Token not allowed");
}
if (ENV.TELEGRAM_BOT_NAME.length > telegramIndex) {
this.botName = ENV.TELEGRAM_BOT_NAME[telegramIndex];
}
this.botToken = token;
this.botId = botId;
const id = message?.chat?.id;
if (id === void 0 || id === null) {
throw new Error("Chat id not found");
}
let historyKey = `history:${id}`;
let configStoreKey = `user_config:${id}`;
if (botId) {
historyKey += `:${botId}`;
configStoreKey += `:${botId}`;
}
switch (message.chat.type) {
case "group":
case "supergroup":
if (!ENV.GROUP_CHAT_BOT_SHARE_MODE && message.from?.id) {
historyKey += `:${message.from.id}`;
configStoreKey += `:${message.from.id}`;
}
this.groupAdminsKey = `group_admin:${id}`;
break;
}
if (message?.chat.is_forum && message?.is_topic_message) {
if (message?.message_thread_id) {
historyKey += `:${message.message_thread_id}`;
configStoreKey += `:${message.message_thread_id}`;
}
}
this.chatHistoryKey = historyKey;
this.lastMessageKey = `last_message_id:${historyKey}`;
this.configStoreKey = configStoreKey;
}
}
class WorkerContext {
USER_CONFIG;
SHARE_CONTEXT;
constructor(USER_CONFIG, SHARE_CONTEXT) {
this.USER_CONFIG = USER_CONFIG;
this.SHARE_CONTEXT = SHARE_CONTEXT;
}
static async from(token, message) {
const SHARE_CONTEXT = new ShareContext(token, message);
const USER_CONFIG = Object.assign({}, ENV.USER_CONFIG);
try {
const userConfig = JSON.parse(await ENV.DATABASE.get(SHARE_CONTEXT.configStoreKey));
ConfigMerger.merge(USER_CONFIG, ConfigMerger.trim(userConfig, ENV.LOCK_USER_CONFIG_KEYS) || {});
} catch (e) {
console.warn(e);
}
return new WorkerContext(USER_CONFIG, SHARE_CONTEXT);
}
}
class Cache {
maxItems;
maxAge;
cache;
constructor() {
this.maxItems = 10;
this.maxAge = 1e3 * 60 * 60;
this.cache = {};
}
set(key, value) {
this.trim();
this.cache[key] = {
value,
time: Date.now()
};
}
get(key) {
this.trim();
return this.cache[key]?.value;
}
trim() {
let keys = Object.keys(this.cache);
for (const key of keys) {
if (Date.now() - this.cache[key].time > this.maxAge) {
delete this.cache[key];
}
}
keys = Object.keys(this.cache);
if (keys.length > this.maxItems) {
keys.sort((a, b) => this.cache[a].time - this.cache[b].time);
for (let i = 0; i < keys.length - this.maxItems; i++) {
delete this.cache[keys[i]];
}
}
}
}
const IMAGE_CACHE = new Cache();
async function fetchImage(url) {
const cache = IMAGE_CACHE.get(url);
if (cache) {
return cache;
}
return fetch(url).then((resp) => resp.blob()).then((blob) => {
IMAGE_CACHE.set(url, blob);
return blob;
});
}
async function urlToBase64String(url) {
try {
const { Buffer } = await import('node:buffer');
return fetchImage(url).then((blob) => blob.arrayBuffer()).then((buffer) => Buffer.from(buffer).toString("base64"));
} catch {
return fetchImage(url).then((blob) => blob.arrayBuffer()).then((buffer) => btoa(String.fromCharCode.apply(null, new Uint8Array(buffer))));
}
}
function getImageFormatFromBase64(base64String) {
const firstChar = base64String.charAt(0);
switch (firstChar) {
case "/":
return "jpeg";
case "i":
return "png";
case "R":
return "gif";
case "U":
return "webp";
default:
throw new Error("Unsupported image format");
}
}
async function imageToBase64String(url) {
const base64String = await urlToBase64String(url);
const format = getImageFormatFromBase64(base64String);
return {
data: base64String,
format: `image/${format}`
};
}
function renderBase64DataURI(params) {
return `data:${params.format};base64,${params.data}`;
}
class Stream {
response;
controller;
decoder;
parser;
constructor(response, controller, parser = null) {
this.response = response;
this.controller = controller;
this.decoder = new SSEDecoder();
this.parser = parser || defaultSSEJsonParser;
}
async *iterMessages() {
if (!this.response.body) {
this.controller.abort();
throw new Error("Attempted to iterate over a response with no body");
}
const lineDecoder = new LineDecoder();
const iter = this.response.body;
for await (const chunk of iter) {
for (const line of lineDecoder.decode(chunk)) {
const sse = this.decoder.decode(line);
if (sse) {
yield sse;
}
}
}
for (const line of lineDecoder.flush()) {
const sse = this.decoder.decode(line);
if (sse) {
yield sse;
}
}
}
async *[Symbol.asyncIterator]() {
let done = false;
try {
for await (const sse of this.iterMessages()) {
if (done) {
continue;
}
if (!sse) {
continue;
}
const { finish, data } = this.parser(sse);
if (finish) {
done = finish;
continue;
}
if (data) {
yield data;
}
}
done = true;
} catch (e) {
if (e instanceof Error && e.name === "AbortError") {
return;
}
throw e;
} finally {
if (!done) {
this.controller.abort();
}
}
}
}
class SSEDecoder {
event;
data;
constructor() {
this.event = null;
this.data = [];
}
decode(line) {
if (line.endsWith("\r")) {
line = line.substring(0, line.length - 1);
}
if (!line) {
if (!this.event && !this.data.length) {
return null;
}
const sse = {
event: this.event,
data: this.data.join("\n")
};
this.event = null;
this.data = [];
return sse;
}
if (line.startsWith(":")) {
return null;
}
let [fieldName, _, value] = this.partition(line, ":");
if (value.startsWith(" ")) {
value = value.substring(1);
}
if (fieldName === "event") {
this.event = value;
} else if (fieldName === "data") {
this.data.push(value);
}
return null;
}
partition(str, delimiter) {
const index = str.indexOf(delimiter);
if (index !== -1) {
return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];
}
return [str, "", ""];
}
}
function defaultSSEJsonParser(sse) {
if (sse.data?.startsWith("[DONE]")) {
return { finish: true };
}
if (sse.event === null && sse.data) {
try {
return { data: JSON.parse(sse.data) };
} catch (e) {
console.error(e, sse);
}
}
return {};
}
class LineDecoder {
buffer;
trailingCR;
textDecoder;
static NEWLINE_CHARS = new Set(["\n", "\r"]);
static NEWLINE_REGEXP = /\r\n|[\n\r]/g;
constructor() {
this.buffer = [];
this.trailingCR = false;
}
decode(chunk) {
let text = this.decodeText(chunk);
if (this.trailingCR) {
text = `\r${text}`;
this.trailingCR = false;
}
if (text.endsWith("\r")) {
this.trailingCR = true;
text = text.slice(0, -1);
}
if (!text) {
return [];
}
const trailingNewline = LineDecoder.NEWLINE_CHARS.has(text[text.length - 1] || "");
let lines = text.split(LineDecoder.NEWLINE_REGEXP);
if (lines.length === 1 && !trailingNewline) {
this.buffer.push(lines[0]);
return [];
}
if (this.buffer.length > 0) {
lines = [this.buffer.join("") + lines[0], ...lines.slice(1)];
this.buffer = [];
}
if (!trailingNewline) {
this.buffer = [lines.pop() || ""];
}
return lines;
}
decodeText(bytes) {
if (bytes == null) {
return "";
}
if (typeof bytes === "string") {
return bytes;
}
if (typeof Buffer !== "undefined") {
if (bytes instanceof Buffer) {
return bytes.toString();
}
if (bytes instanceof Uint8Array) {
return Buffer.from(bytes).toString();
}
throw new Error(`Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`);
}
if (typeof TextDecoder !== "undefined") {
if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) {
if (!this.textDecoder) {
this.textDecoder = new TextDecoder("utf8");
}
return this.textDecoder.decode(bytes, { stream: true });
}
throw new Error(`Unexpected: received non-Uint8Array/ArrayBuffer in a web platform. Please report this error.`);
}
throw new Error("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.");
}
flush() {
if (!this.buffer.length && !this.trailingCR) {
return [];
}
const lines = [this.buffer.join("")];
this.buffer = [];
this.trailingCR = false;
return lines;
}
}
function fixOpenAICompatibleOptions(options) {
options = options || {};
options.streamBuilder = options.streamBuilder || function(r, c) {
return new Stream(r, c);
};
options.contentExtractor = options.contentExtractor || function(d) {
return d?.choices?.[0]?.delta?.content;
};
options.fullContentExtractor = options.fullContentExtractor || function(d) {
return d.choices?.[0]?.message.content;
};
options.errorExtractor = options.errorExtractor || function(d) {
return d.error?.message;
};
return options;
}
function isJsonResponse(resp) {
return resp.headers.get("content-type")?.includes("json") || false;
}
function isEventStreamResponse(resp) {
const types = ["application/stream+json", "text/event-stream"];
const content = resp.headers.get("content-type") || "";
for (const type of types) {
if (content.includes(type)) {
return true;
}
}
return false;
}
async function requestChatCompletions(url, header, body, onStream, onResult = null, options = null) {
const controller = new AbortController();
const { signal } = controller;
let timeoutID = null;
let lastUpdateTime = Date.now();
if (ENV.CHAT_COMPLETE_API_TIMEOUT > 0) {
timeoutID = setTimeout(() => controller.abort(), ENV.CHAT_COMPLETE_API_TIMEOUT);
}
const resp = await fetch(url, {
method: "POST",
headers: header,
body: JSON.stringify(body),
signal
});
if (timeoutID) {
clearTimeout(timeoutID);
}
options = fixOpenAICompatibleOptions(options);
if (onStream && resp.ok && isEventStreamResponse(resp)) {
const stream = options.streamBuilder?.(resp, controller);
if (!stream) {
throw new Error("Stream builder error");
}
let contentFull = "";
let lengthDelta = 0;
let updateStep = 50;
try {
for await (const data of stream) {
const c = options.contentExtractor?.(data) || "";
if (c === "") {
continue;
}
lengthDelta += c.length;
contentFull = contentFull + c;
if (lengthDelta > updateStep) {
if (ENV.TELEGRAM_MIN_STREAM_INTERVAL > 0) {
const delta = Date.now() - lastUpdateTime;
if (delta < ENV.TELEGRAM_MIN_STREAM_INTERVAL) {
continue;
}
lastUpdateTime = Date.now();
}
lengthDelta = 0;
updateStep += 20;
await onStream(`${contentFull}
...`);
}
}
} catch (e) {
contentFull += `
ERROR: ${e.message}`;
}
return contentFull;
}
if (!isJsonResponse(resp)) {
throw new Error(resp.statusText);
}
const result = await resp.json();
if (!result) {
throw new Error("Empty response");
}
if (options.errorExtractor?.(result)) {
throw new Error(options.errorExtractor?.(result) || "Unknown error");
}
try {
await onResult?.(result);
return options.fullContentExtractor?.(result) || "";
} catch (e) {
console.error(e);
throw new Error(JSON.stringify(result));
}
}
class Anthropic {
name = "anthropic";
modelKey = "ANTHROPIC_CHAT_MODEL";
enable = (context) => {
return !!context.ANTHROPIC_API_KEY;
};
render = async (item) => {
const res = {
role: item.role,
content: item.content
};
if (item.images && item.images.length > 0) {
res.content = [];
if (item.content) {
res.content.push({ type: "text", text: item.content });
}
for (const image of item.images) {
res.content.push(await imageToBase64String(image).then(({ format, data }) => {
return { type: "image", source: { type: "base64", media_type: format, data } };
}));
}
}
return res;
};
model = (ctx) => {
return ctx.ANTHROPIC_CHAT_MODEL;
};
static parser(sse) {
switch (sse.event) {
case "content_block_delta":
try {
return { data: JSON.parse(sse.data || "") };
} catch (e) {
console.error(e, sse.data);
return {};
}
case "message_start":
case "content_block_start":
case "content_block_stop":
return {};
case "message_stop":
return { finish: true };
default:
return {};
}
}
request = async (params, context, onStream) => {
const { message, images, prompt, history } = params;
const url = `${context.ANTHROPIC_API_BASE}/messages`;
const header = {
"x-api-key": context.ANTHROPIC_API_KEY || "",
"anthropic-version": "2023-06-01",
"content-type": "application/json"
};
const messages = (history || []).concat({ role: "user", content: message, images });
if (messages.length > 0 && messages[0].role === "assistant") {
messages.shift();
}
const body = {
system: prompt,
model: context.ANTHROPIC_CHAT_MODEL,
messages: await Promise.all(messages.map((item) => this.render(item))),
stream: onStream != null,
max_tokens: ENV.MAX_TOKEN_LENGTH > 0 ? ENV.MAX_TOKEN_LENGTH : 2048
};
if (!body.system) {
delete body.system;
}
const options = {};
options.streamBuilder = function(r, c) {
return new Stream(r, c, Anthropic.parser);
};
options.contentExtractor = function(data) {
return data?.delta?.text;
};
options.fullContentExtractor = function(data) {
return data?.content?.[0].text;
};
options.errorExtractor = function(data) {
return data?.error?.message;
};
return requestChatCompletions(url, header, body, onStream, null, options);
};
}
async function renderOpenAIMessage(item) {
const res = {
role: item.role,
content: item.content
};
if (item.images && item.images.length > 0) {
res.content = [];
if (item.content) {
res.content.push({ type: "text", text: item.content });
}
for (const image of item.images) {
switch (ENV.TELEGRAM_IMAGE_TRANSFER_MODE) {
case "base64":
res.content.push({ type: "image_url", image_url: {
url: renderBase64DataURI(await imageToBase64String(image))
} });
break;
case "url":
default:
res.content.push({ type: "image_url", image_url: { url: image } });
break;
}
}
}
return res;
}
class OpenAIBase {
name = "openai";
apikey = (context) => {
const length = context.OPENAI_API_KEY.length;
return context.OPENAI_API_KEY[Math.floor(Math.random() * length)];
};
}
class OpenAI extends OpenAIBase {
modelKey = "OPENAI_CHAT_MODEL";
enable = (context) => {
return context.OPENAI_API_KEY.length > 0;
};
model = (ctx) => {
return ctx.OPENAI_CHAT_MODEL;
};
render = async (item) => {
return renderOpenAIMessage(item);
};
request = async (params, context, onStream) => {
const { message, images, prompt, history } = params;
const url = `${context.OPENAI_API_BASE}/chat/completions`;
const header = {
"Content-Type": "application/json",
"Authorization": `Bearer ${this.apikey(context)}`
};
const messages = [...history || [], { role: "user", content: message, images }];
if (prompt) {
messages.unshift({ role: context.SYSTEM_INIT_MESSAGE_ROLE, content: prompt });
}
const body = {
model: context.OPENAI_CHAT_MODEL,
...context.OPENAI_API_EXTRA_PARAMS,
messages: await Promise.all(messages.map(this.render)),
stream: onStream != null
};
return requestChatCompletions(url, header, body, onStream);
};
}
class Dalle extends OpenAIBase {
modelKey = "OPENAI_DALLE_API";
enable = (context) => {
return context.OPENAI_API_KEY.length > 0;
};
model = (ctx) => {
return ctx.DALL_E_MODEL;
};
request = async (prompt, context) => {
const url = `${context.OPENAI_API_BASE}/images/generations`;
const header = {
"Content-Type": "application/json",
"Authorization": `Bearer ${this.apikey(context)}`
};
const body = {
prompt,
n: 1,
size: context.DALL_E_IMAGE_SIZE,
model: context.DALL_E_MODEL
};
if (body.model === "dall-e-3") {
body.quality = context.DALL_E_IMAGE_QUALITY;
body.style = context.DALL_E_IMAGE_STYLE;
}
const resp = await fetch(url, {
method: "POST",
headers: header,
body: JSON.stringify(body)
}).then((res) => res.json());
if (resp.error?.message) {
throw new Error(resp.error.message);
}
return resp?.data?.[0]?.url;
};
}
class AzureBase {
name = "azure";
modelFromURI = (uri) => {
if (!uri) {
return "";
}
try {
const url = new URL(uri);
return url.pathname.split("/")[3];
} catch {
return uri;
}
};
}
class AzureChatAI extends AzureBase {
modelKey = "AZURE_COMPLETIONS_API";
enable = (context) => {
return !!(context.AZURE_API_KEY && context.AZURE_COMPLETIONS_API);
};
model = (ctx) => {
return this.modelFromURI(ctx.AZURE_COMPLETIONS_API);
};
request = async (params, context, onStream) => {
const { message, images, prompt, history } = params;
const url = context.AZURE_COMPLETIONS_API;
if (!url || !context.AZURE_API_KEY) {
throw new Error("Azure Completions API is not set");
}
const header = {
"Content-Type": "application/json",
"api-key": context.AZURE_API_KEY
};
const messages = [...history || [], { role: "user", content: message, images }];
if (prompt) {
messages.unshift({ role: context.SYSTEM_INIT_MESSAGE_ROLE, content: prompt });
}
const body = {
...context.OPENAI_API_EXTRA_PARAMS,
messages: await Promise.all(messages.map(renderOpenAIMessage)),
stream: onStream != null
};
return requestChatCompletions(url, header, body, onStream);
};
}
class AzureImageAI extends AzureBase {
modelKey = "AZURE_DALLE_API";
enable = (context) => {
return !!(context.AZURE_API_KEY && context.AZURE_DALLE_API);
};
model = (ctx) => {
return this.modelFromURI(ctx.AZURE_DALLE_API);
};
request = async (prompt, context) => {
const url = context.AZURE_DALLE_API;
if (!url || !context.AZURE_API_KEY) {
throw new Error("Azure DALL-E API is not set");
}
const header = {
"Content-Type": "application/json",
"api-key": context.AZURE_API_KEY
};