forked from XxxXTeam/flowith2api_deno
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
2438 lines (2188 loc) · 91.9 KB
/
main.ts
File metadata and controls
2438 lines (2188 loc) · 91.9 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
import { serve } from "https://deno.land/std@0.224.0/http/server.ts";
import { DB } from "https://deno.land/x/sqlite/mod.ts";
// ============ 存储抽象层 ============
interface StorageAdapter {
get<T>(key: string[]): Promise<T | null>;
set<T>(key: string[], value: T, options?: { expireIn?: number }): Promise<void>;
delete(key: string[]): Promise<void>;
close(): Promise<void>;
}
// SQLite 存储适配器
class SQLiteAdapter implements StorageAdapter {
private db: DB;
constructor(path: string) {
this.db = new DB(path);
this.db.execute(`
CREATE TABLE IF NOT EXISTS kv_store (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
expire_at INTEGER
)
`);
this.db.execute(`CREATE INDEX IF NOT EXISTS idx_expire ON kv_store(expire_at)`);
// 定期清理过期数据
setInterval(() => this.cleanup(), 60000);
}
private cleanup() {
try {
const now = Date.now();
this.db.query("DELETE FROM kv_store WHERE expire_at IS NOT NULL AND expire_at < ?", [now]);
} catch (e) {
console.error("[SQLite] Cleanup error:", e);
}
}
async get<T>(key: string[]): Promise<T | null> {
const keyStr = JSON.stringify(key);
const now = Date.now();
const rows = this.db.query("SELECT value FROM kv_store WHERE key = ? AND (expire_at IS NULL OR expire_at > ?)", [keyStr, now]);
if (rows.length === 0) return null;
try {
return JSON.parse(rows[0][0] as string) as T;
} catch {
return null;
}
}
async set<T>(key: string[], value: T, options?: { expireIn?: number }): Promise<void> {
const keyStr = JSON.stringify(key);
const valueStr = JSON.stringify(value);
const expireAt = options?.expireIn ? Date.now() + options.expireIn : null;
this.db.query(
"INSERT OR REPLACE INTO kv_store (key, value, expire_at) VALUES (?, ?, ?)",
[keyStr, valueStr, expireAt]
);
}
async delete(key: string[]): Promise<void> {
const keyStr = JSON.stringify(key);
this.db.query("DELETE FROM kv_store WHERE key = ?", [keyStr]);
}
async close(): Promise<void> {
this.db.close();
}
}
// Deno KV 存储适配器
class DenoKVAdapter implements StorageAdapter {
constructor(private kv: Deno.Kv) {}
async get<T>(key: string[]): Promise<T | null> {
const result = await this.kv.get<T>(key);
return result.value;
}
async set<T>(key: string[], value: T, options?: { expireIn?: number }): Promise<void> {
await this.kv.set(key, value, options);
}
async delete(key: string[]): Promise<void> {
await this.kv.delete(key);
}
async close(): Promise<void> {
this.kv.close();
}
}
// 内存存储适配器
class MemoryAdapter implements StorageAdapter {
private store = new Map<string, { value: any; expireAt?: number }>();
constructor() {
setInterval(() => this.cleanup(), 60000);
}
private cleanup() {
const now = Date.now();
for (const [key, entry] of this.store.entries()) {
if (entry.expireAt && entry.expireAt < now) {
this.store.delete(key);
}
}
}
async get<T>(key: string[]): Promise<T | null> {
const keyStr = JSON.stringify(key);
const entry = this.store.get(keyStr);
if (!entry) return null;
if (entry.expireAt && entry.expireAt < Date.now()) {
this.store.delete(keyStr);
return null;
}
return entry.value as T;
}
async set<T>(key: string[], value: T, options?: { expireIn?: number }): Promise<void> {
const keyStr = JSON.stringify(key);
const expireAt = options?.expireIn ? Date.now() + options.expireIn : undefined;
this.store.set(keyStr, { value, expireAt });
}
async delete(key: string[]): Promise<void> {
const keyStr = JSON.stringify(key);
this.store.delete(keyStr);
}
async close(): Promise<void> {
this.store.clear();
}
}
// ============ 存储初始化 ============
const STORAGE_TYPE = (Deno.env.get("STORAGE_TYPE") ?? "kv").toLowerCase();
let storage: StorageAdapter | null = null;
let kv: Deno.Kv | null = null; // 保留向后兼容
async function initStorage(): Promise<void> {
const kvPath = Deno.env.get("DENO_KV_PATH");
const sqlitePath = Deno.env.get("SQLITE_PATH") || "./data.db";
try {
if (STORAGE_TYPE === "sqlite") {
storage = new SQLiteAdapter(sqlitePath);
console.log(`[Storage] SQLite initialized at ${sqlitePath}`);
} else if (STORAGE_TYPE === "memory") {
storage = new MemoryAdapter();
console.log("[Storage] Memory storage initialized");
} else {
// 默认使用 Deno KV
const denoKv = await Deno.openKv(kvPath);
kv = denoKv; // 保留向后兼容
storage = new DenoKVAdapter(denoKv);
console.log(`[Storage] Deno KV initialized${kvPath ? ` at ${kvPath}` : ""}`);
}
} catch (e) {
console.error("[Storage] Initialization failed:", e);
console.log("[Storage] Falling back to memory storage");
storage = new MemoryAdapter();
}
}
await initStorage();
// ============ 配置管理系统 ============
interface AppConfig {
// Token配置
tokens: string[];
apiKeys: string[];
adminKey: string;
// 服务配置
port: number;
logLevel: string;
// 上游配置
flowithBase: string;
flowithRegion: string;
origin: string;
// 超时配置
headerTimeoutMs: number;
bodyTimeoutMs: number;
streamIdleTimeoutMs: number;
streamTotalTimeoutMs: number;
// 重试配置
retryMax: number;
retryBackoffBaseMs: number;
sseRetryOnEmpty: boolean;
sseMinContentLength: number;
retryOnStatus: number[];
// 长上下文配置
enableLongContext: boolean;
maxContextMessages: number;
contextTTLSeconds: number;
// 思考注入配置
enableThinkingInjection: boolean;
thinkingPrompt: string;
// MCP配置
enableMCP: boolean;
mcpTools: string[];
// 存储配置
storageType: "kv" | "sqlite" | "memory";
sqlitePath?: string;
// 仅服务端模式
serverOnly: boolean;
// Claude API 兼容
enableClaudeAPI: boolean;
// 思考功能增强
enableThinkingTags: boolean;
// 性能优化
enableStreamOptimization: boolean;
}
// 从环境变量加载配置
function loadConfigFromEnv(): AppConfig {
const flowithBase = (Deno.env.get("FLOWITH_BASE") ?? "").trim();
const flowithRegion = (Deno.env.get("FLOWITH_REGION") ?? "").trim();
const origin = flowithBase
? flowithBase.replace(/\/+$/, "")
: (flowithRegion ? `https://${flowithRegion}.edge.flowith.net` : `https://edge.flowith.net`);
const storageTypeEnv = (Deno.env.get("STORAGE_TYPE") ?? "kv").toLowerCase();
const storageType = (storageTypeEnv === "sqlite" || storageTypeEnv === "memory") ? storageTypeEnv : "kv";
return {
// tokens 不从这里加载,而是通过 syncTokensFromEnv() 统一管理
tokens: [],
apiKeys: (Deno.env.get("API_KEYS") ?? "").split(",").map(s => s.trim()).filter(Boolean),
adminKey: (Deno.env.get("ADMIN_KEY") ?? Deno.env.get("API_KEYS") ?? "").split(",")[0]?.trim() ?? "",
port: Number(Deno.env.get("PORT") ?? "8787"),
logLevel: (Deno.env.get("LOG_LEVEL") ?? "info").toLowerCase(),
flowithBase,
flowithRegion,
origin,
headerTimeoutMs: Math.max(1000, Number(Deno.env.get("UPSTREAM_TIMEOUT_MS") ?? "25000")),
bodyTimeoutMs: Math.max(2000, Number(Deno.env.get("UPSTREAM_BODY_TIMEOUT_MS") ?? "30000")),
streamIdleTimeoutMs: Math.max(2000, Number(Deno.env.get("STREAM_IDLE_TIMEOUT_MS") ?? "15000")),
streamTotalTimeoutMs: Math.max(5000, Number(Deno.env.get("STREAM_TOTAL_TIMEOUT_MS") ?? "180000")),
retryMax: Math.max(0, Number(Deno.env.get("UPSTREAM_RETRY_MAX") ?? "3")),
retryBackoffBaseMs: Math.max(0, Number(Deno.env.get("UPSTREAM_RETRY_BACKOFF_MS") ?? "200")),
sseRetryOnEmpty: (Deno.env.get("SSE_RETRY_ON_EMPTY") ?? "true").toLowerCase() === "true",
sseMinContentLength: Math.max(0, Number(Deno.env.get("SSE_MIN_CONTENT_LENGTH") ?? "10")),
retryOnStatus: [401, 403, 408, 402, 409, 425, 429, 500, 502, 503, 504],
enableLongContext: (Deno.env.get("ENABLE_LONG_CONTEXT") ?? "true").toLowerCase() === "true",
maxContextMessages: Math.max(1, Number(Deno.env.get("MAX_CONTEXT_MESSAGES") ?? "20")),
contextTTLSeconds: Math.max(60, Number(Deno.env.get("CONTEXT_TTL_SECONDS") ?? "3600")),
enableThinkingInjection: (Deno.env.get("ENABLE_THINKING_INJECTION") ?? "true").toLowerCase() === "true",
thinkingPrompt: Deno.env.get("THINKING_PROMPT") ?? "Please think step by step before answering.",
enableMCP: (Deno.env.get("ENABLE_MCP") ?? "true").toLowerCase() === "true",
mcpTools: (Deno.env.get("MCP_TOOLS") ?? "web_search,image_gen,code_interpreter").split(",").map(s => s.trim()).filter(Boolean),
storageType: storageType as "kv" | "sqlite" | "memory",
sqlitePath: Deno.env.get("SQLITE_PATH") || "./data.db",
serverOnly: (Deno.env.get("SERVER_ONLY") ?? "false").toLowerCase() === "true",
enableClaudeAPI: (Deno.env.get("ENABLE_CLAUDE_API") ?? "true").toLowerCase() === "true",
enableThinkingTags: (Deno.env.get("ENABLE_THINKING_TAGS") ?? "true").toLowerCase() === "true",
enableStreamOptimization: (Deno.env.get("ENABLE_STREAM_OPTIMIZATION") ?? "true").toLowerCase() === "true"
};
}
// 全局配置对象
let CONFIG = loadConfigFromEnv();
// 保存配置到存储
async function saveConfigToStorage(): Promise<void> {
if (!storage) return;
try {
await storage.set(["config"], CONFIG);
console.log("[Storage] Configuration saved");
} catch (e) {
console.error("[Storage] Failed to save config:", e);
}
}
// 从存储加载配置
async function loadConfigFromStorage(): Promise<void> {
if (!storage) return;
try {
const value = await storage.get<AppConfig>(["config"]);
if (value) {
CONFIG = { ...CONFIG, ...value };
console.log("[Storage] Configuration loaded");
}
} catch (e) {
console.error("[Storage] Failed to load config:", e);
}
}
// 兼容性:从配置对象读取值
const TOKENS: string[] = CONFIG.tokens;
const API_KEYS = CONFIG.apiKeys;
const ADMIN_KEY = CONFIG.adminKey;
const PORT = CONFIG.port;
const LOG_LEVEL = CONFIG.logLevel;
const HEADER_TIMEOUT_MS = CONFIG.headerTimeoutMs;
const BODY_TIMEOUT_MS = CONFIG.bodyTimeoutMs;
const STREAM_IDLE_TIMEOUT_MS = CONFIG.streamIdleTimeoutMs;
const STREAM_TOTAL_TIMEOUT_MS = CONFIG.streamTotalTimeoutMs;
const RETRY_MAX = CONFIG.retryMax;
const RETRY_BACKOFF_BASE_MS = CONFIG.retryBackoffBaseMs;
const SSE_RETRY_ON_EMPTY = CONFIG.sseRetryOnEmpty;
const SSE_MIN_CONTENT_LENGTH = CONFIG.sseMinContentLength;
const RETRY_ON_STATUS = new Set(CONFIG.retryOnStatus);
const FLOWITH_BASE = CONFIG.flowithBase;
const FLOWITH_REGION = CONFIG.flowithRegion;
const ORIGIN = CONFIG.origin;
const URL_SEEK = `${ORIGIN}/external/use/knowledge-base/seek`;
const URL_MODELS = `${ORIGIN}/external/use/knowledge-base/models`;
const levels: Record<string, number> = { debug:10, info:20, warn:30, error:40 };
function logAt(level:"debug"|"info"|"warn"|"error", obj:Record<string,unknown>){
if (levels[level] < levels[LOG_LEVEL]) return;
console.log(JSON.stringify({ level, ts:new Date().toISOString(), ...obj }));
}
const log = {
debug:(o:any)=>logAt("debug",o),
info :(o:any)=>logAt("info",o),
warn :(o:any)=>logAt("warn",o),
error:(o:any)=>logAt("error",o),
};
// ============ 数据操作函数 ============
async function loadTokensFromStorage(): Promise<void> {
if (!storage) return;
try {
const value = await storage.get<string[]>(["tokens"]);
if (value && Array.isArray(value)) {
TOKENS.length = 0;
TOKENS.push(...value);
console.log(`[Storage] Loaded ${TOKENS.length} tokens`);
}
} catch (e) {
console.error("[Storage] Failed to load tokens:", e);
}
}
async function saveTokensToStorage(): Promise<void> {
if (!storage) return;
try {
await storage.set(["tokens"], TOKENS);
console.log(`[Storage] Saved ${TOKENS.length} tokens`);
} catch (e) {
console.error("[Storage] Failed to save tokens:", e);
}
}
async function loadStatsFromStorage(): Promise<void> {
if (!storage) return;
try {
const value = await storage.get<{
totalRequests: number;
successRequests: number;
failedRequests: number;
tokenUsage: Record<string, number>;
lastResetTime: number;
}>(["stats"]);
if (value) {
stats.totalRequests = value.totalRequests ?? 0;
stats.successRequests = value.successRequests ?? 0;
stats.failedRequests = value.failedRequests ?? 0;
stats.tokenUsage = new Map(Object.entries(value.tokenUsage ?? {}));
stats.lastResetTime = value.lastResetTime ?? Date.now();
console.log(`[Storage] Loaded stats: ${stats.totalRequests} total requests`);
}
} catch (e) {
console.error("[Storage] Failed to load stats:", e);
}
}
async function saveStatsToStorage(): Promise<void> {
if (!storage) return;
try {
await storage.set(["stats"], {
totalRequests: stats.totalRequests,
successRequests: stats.successRequests,
failedRequests: stats.failedRequests,
tokenUsage: Object.fromEntries(stats.tokenUsage),
lastResetTime: stats.lastResetTime
});
} catch (e) {
console.error("[Storage] Failed to save stats:", e);
}
}
// 添加请求计数器和统计
const stats = {
totalRequests: 0,
successRequests: 0,
failedRequests: 0,
tokenUsage: new Map<string, number>(),
lastResetTime: Date.now()
};
interface Session {
sessionId: string;
messages: Array<{ role: string; content: string; timestamp: number }>;
createdAt: number;
lastAccessedAt: number;
kbList?: string[]; // 保存 kb_list UUID v4 数组,连续对话时复用
metadata?: Record<string, any>;
apiKey?: string; // 关联的 API key(用于自动会话)
model?: string; // 关联的模型(用于自动会话)
}
// 生成自动会话 ID(基于 API key + 模型)
function generateAutoSessionId(apiKey: string, model: string): string {
const key = `auto_${apiKey}_${model}`.replace(/[^a-zA-Z0-9_-]/g, '_');
return key.substring(0, 100); // 限制长度
}
class SessionManager {
private sessions = new Map<string, Session>();
async getSession(sessionId: string): Promise<Session | null> {
// 先从内存查找
let session = this.sessions.get(sessionId);
if (session) {
session.lastAccessedAt = Date.now();
return session;
}
if (storage) {
try {
const value = await storage.get<Session>(["sessions", sessionId]);
if (value) {
session = value;
session.lastAccessedAt = Date.now();
this.sessions.set(sessionId, session);
return session;
}
} catch (e) {
log.error({ 事件: "会话加载失败", sessionId, 错误: String(e) });
}
}
return null;
}
async createSession(sessionId: string): Promise<Session> {
const session: Session = {
sessionId,
messages: [],
createdAt: Date.now(),
lastAccessedAt: Date.now()
};
this.sessions.set(sessionId, session);
await this.saveSession(session);
return session;
}
async saveSession(session: Session): Promise<void> {
if (storage) {
try {
await storage.set(["sessions", session.sessionId], session, {
expireIn: CONFIG.contextTTLSeconds * 1000
});
} catch (e) {
log.error({ 事件: "会话保存失败", sessionId: session.sessionId, 错误: String(e) });
}
}
}
async addMessage(sessionId: string, role: string, content: string, kbList?: string[]): Promise<void> {
let session = await this.getSession(sessionId);
if (!session) {
session = await this.createSession(sessionId);
}
session.messages.push({ role, content, timestamp: Date.now() });
// 保持最大消息数限制
if (session.messages.length > CONFIG.maxContextMessages) {
session.messages = session.messages.slice(-CONFIG.maxContextMessages);
}
// 更新或设置 kb_list(如果提供)
if (kbList && kbList.length > 0) {
session.kbList = kbList;
}
await this.saveSession(session);
}
async getKbList(sessionId: string): Promise<string[] | undefined> {
const session = await this.getSession(sessionId);
return session?.kbList;
}
async setKbList(sessionId: string, kbList: string[]): Promise<void> {
let session = await this.getSession(sessionId);
if (!session) {
session = await this.createSession(sessionId);
}
session.kbList = kbList;
await this.saveSession(session);
}
async getContext(sessionId: string): Promise<Array<{ role: string; content: string }>> {
const session = await this.getSession(sessionId);
if (!session) return [];
return session.messages.map(({ role, content }) => ({ role, content }));
}
async clearSession(sessionId: string): Promise<void> {
this.sessions.delete(sessionId);
if (storage) {
try {
await storage.delete(["sessions", sessionId]);
} catch (e) {
log.error({ 事件: "会话删除失败", sessionId, 错误: String(e) });
}
}
}
// 清理过期会话
async cleanupExpiredSessions(): Promise<void> {
const now = Date.now();
const ttl = CONFIG.contextTTLSeconds * 1000;
for (const [sessionId, session] of this.sessions.entries()) {
if (now - session.lastAccessedAt > ttl) {
await this.clearSession(sessionId);
}
}
}
}
const sessionManager = new SessionManager();
// 定期清理过期会话(每5分钟)
if (CONFIG.enableLongContext) {
setInterval(() => {
sessionManager.cleanupExpiredSessions().catch(e =>
log.error({ 事件: "会话清理失败", 错误: String(e) })
);
}, 300000);
}
// ============ MCP工具定义 ============
interface MCPTool {
type: "function";
function: {
name: string;
description: string;
parameters: {
type: "object";
properties: Record<string, any>;
required: string[];
};
};
}
const MCP_TOOLS: MCPTool[] = [
{
type: "function",
function: {
name: "web_search",
description: "Search the web for current information. Use this when you need up-to-date facts or recent events.",
parameters: {
type: "object",
properties: {
query: {
type: "string",
description: "The search query"
}
},
required: ["query"]
}
}
},
{
type: "function",
function: {
name: "image_gen",
description: "Generate images based on text descriptions. Use this for creating visual content.",
parameters: {
type: "object",
properties: {
prompt: {
type: "string",
description: "Description of the image to generate"
},
size: {
type: "string",
description: "Image size (e.g., '1024x1024')",
enum: ["256x256", "512x512", "1024x1024"]
}
},
required: ["prompt"]
}
}
},
{
type: "function",
function: {
name: "code_interpreter",
description: "Execute Python code for calculations, data analysis, or other programming tasks.",
parameters: {
type: "object",
properties: {
code: {
type: "string",
description: "Python code to execute"
}
},
required: ["code"]
}
}
}
];
// 加载初始数据
if (storage) {
await loadConfigFromStorage(); // 先加载配置
await loadTokensFromStorage(); // 从存储加载已保存的tokens
await syncTokensFromEnv(); // 同步环境变量中的tokens(差异或完全同步)
await loadStatsFromStorage();
await saveConfigToStorage(); // 保存当前配置(如果存储中没有)
} else {
// 如果没有存储,也执行环境变量同步(只是不保存)
const envTokensStr = Deno.env.get("FLOWITH_AUTH_TOKENS") ?? "";
const envTokens = Array.from(new Set(
envTokensStr.split(",").map(s => s.trim()).filter(Boolean)
));
if (envTokens.length > 0 && TOKENS.length === 0) {
TOKENS.push(...envTokens);
console.log(`[Sync] Loaded ${TOKENS.length} tokens from environment (no storage)`);
}
}
// 定期保存统计数据(每30秒)
if (storage) {
setInterval(() => {
saveStatsToStorage().catch(e => console.error("[Storage] Auto-save stats failed:", e));
}, 30000);
}
const mask = (s?:string|null)=>!s?"":(s.length<=8?"***":`${s.slice(0,4)}...${s.slice(-4)}`);
const enc = new TextEncoder(), dec = new TextDecoder();
// ============ 优化的轮询机制 ============
const rrBuf = new SharedArrayBuffer(4);
const rrView = new Int32Array(rrBuf);
// 初始化轮询索引(从0开始)
Atomics.store(rrView, 0, 0);
/**
* 获取下一个token(按顺序轮询)
* 实现方式:使用原子操作确保并发安全
* 第1次请求 -> token[0]
* 第2次请求 -> token[1]
* 第3次请求 -> token[2]
* ...
* 第N+1次请求 -> token[0](循环)
*/
function nextToken(): { idx:number, token:string, totalCalls: number } | null {
const n = TOKENS.length;
if (n === 0) {
log.warn({ 事件:"无可用token", 时间: new Date().toISOString() });
return null;
}
// 原子操作:获取当前索引并自增
const currentIndex = Atomics.load(rrView, 0);
const nextIndex = (currentIndex + 1) % n;
Atomics.store(rrView, 0, nextIndex);
// 获取当前要使用的token
const idx = currentIndex % n;
const token = TOKENS[idx];
// 更新token使用统计
const maskedToken = mask(token);
stats.tokenUsage.set(maskedToken, (stats.tokenUsage.get(maskedToken) ?? 0) + 1);
// 返回详细信息
return {
idx,
token,
totalCalls: currentIndex + 1 // 总调用次数
};
}
/**
* 获取当前轮询状态(不移动索引)
*/
function getCurrentTokenIndex(): number {
return Atomics.load(rrView, 0) % TOKENS.length;
}
/**
* 重置轮询索引到指定位置
*/
function resetTokenIndex(index: number = 0): void {
Atomics.store(rrView, 0, Math.max(0, index));
log.info({ 事件:"重置轮询索引", 新索引: index });
}
function jsonResponse(obj:any, status=200, extraHeaders?: Record<string, string>){
return new Response(JSON.stringify(obj), {
status, headers:{ "content-type":"application/json", ...extraHeaders }
});
}
function badRequest(msg:string){ return jsonResponse({ error:{ message:msg, type:"bad_request"} }, 400); }
function unauthorized(){ return jsonResponse({ error:{ message:"Unauthorized", type:"auth_error"} }, 401); }
function forbidden(){ return jsonResponse({ error:{ message:"Forbidden", type:"forbidden"} }, 403); }
function gatewayError(e:any){ return jsonResponse({ error:{ message:"Bad Gateway: "+String((e as any)?.message ?? e), type:"network"}}, 502); }
function gatewayTimeout(msg:string){ return jsonResponse({ error:{ message:msg, type:"gateway_timeout"} }, 504); }
function genReqId(h:Headers){ return h.get("x-req-id") ?? crypto.randomUUID(); }
function delay(ms:number){ return new Promise(r=>setTimeout(r,ms)); }
function isAdminAuthorized(req:Request): boolean {
const auth = req.headers.get("authorization") ?? "";
const provided = auth.startsWith("Bearer ") ? auth.slice(7) : "";
// 优先使用 ADMIN_KEY,如果没有则使用 API_KEYS
if (ADMIN_KEY) {
return provided === ADMIN_KEY;
}
// 如果没有 ADMIN_KEY,则检查 API_KEYS(任何一个 API_KEY 都可以作为管理员)
if (API_KEYS.length > 0) {
return API_KEYS.includes(provided);
}
return false; // 没有配置任何密钥
}
async function addToken(token:string): Promise<{ success:boolean, message:string }> {
const trimmed = token.trim();
if (!trimmed) return { success:false, message:"Token cannot be empty" };
if (TOKENS.includes(trimmed)) return { success:false, message:"Token already exists" };
TOKENS.push(trimmed);
await saveTokensToStorage();
return { success:true, message:"Token added successfully" };
}
async function removeToken(token:string): Promise<{ success:boolean, message:string }> {
const trimmed = token.trim();
const idx = TOKENS.indexOf(trimmed);
if (idx === -1) return { success:false, message:"Token not found" };
TOKENS.splice(idx, 1);
await saveTokensToStorage();
return { success:true, message:"Token removed successfully" };
}
async function addTokensBatch(tokens: string[]): Promise<{ success:boolean, message:string, added:number, skipped:number, failed:string[] }> {
let added = 0;
let skipped = 0;
const failed: string[] = [];
for (const token of tokens) {
const trimmed = token.trim();
if (!trimmed) {
failed.push(`Empty token`);
continue;
}
if (TOKENS.includes(trimmed)) {
skipped++;
continue;
}
TOKENS.push(trimmed);
added++;
}
if (added > 0) {
try {
await saveTokensToStorage();
} catch (e) {
// 如果保存失败,回滚已添加的tokens
TOKENS.splice(-added);
return {
success: false,
message: `Failed to save tokens: ${String(e)}`,
added: 0,
skipped,
failed: [...failed, ...tokens.slice(-added).map(t => `${t} (rollback)`)]
};
}
}
return {
success: added > 0,
message: `Added ${added} tokens, skipped ${skipped} duplicates${failed.length > 0 ? `, ${failed.length} failed` : ''}`,
added,
skipped,
failed
};
}
async function removeTokensBatch(tokens: string[]): Promise<{ success:boolean, message:string, removed:number, notFound:number }> {
let removed = 0;
let notFound = 0;
for (const token of tokens) {
const trimmed = token.trim();
if (!trimmed) continue;
const idx = TOKENS.indexOf(trimmed);
if (idx === -1) {
notFound++;
continue;
}
TOKENS.splice(idx, 1);
removed++;
}
if (removed > 0) {
await saveTokensToStorage();
}
return {
success: removed > 0,
message: `Removed ${removed} tokens${notFound > 0 ? `, ${notFound} not found` : ''}`,
removed,
notFound
};
}
async function clearAllTokens(): Promise<{ success:boolean, message:string, cleared:number }> {
const count = TOKENS.length;
TOKENS.length = 0;
await saveTokensToStorage();
return {
success: true,
message: `Cleared ${count} tokens`,
cleared: count
};
}
// 启动时同步环境变量中的tokens
async function syncTokensFromEnv(): Promise<void> {
const envTokensStr = Deno.env.get("FLOWITH_AUTH_TOKENS") ?? "";
const envTokens = Array.from(new Set(
envTokensStr.split(",").map(s => s.trim()).filter(Boolean)
));
const rsyncMode = (Deno.env.get("RSYNC") ?? "0").trim() === "1";
if (envTokens.length === 0) {
console.log("[Sync] No tokens in environment variable, skipping sync");
return;
}
if (rsyncMode) {
// 完全同步模式:清空存储,完全替换
console.log(`[Sync] RSYNC mode enabled: clearing all tokens and loading ${envTokens.length} tokens from environment`);
TOKENS.length = 0;
TOKENS.push(...envTokens);
await saveTokensToStorage();
console.log(`[Sync] Full sync completed: ${TOKENS.length} tokens loaded`);
} else {
// 差异同步模式:只添加新的token,保留存储中已有的
const existingSet = new Set(TOKENS);
const newTokens: string[] = [];
for (const token of envTokens) {
if (!existingSet.has(token)) {
TOKENS.push(token);
newTokens.push(token);
}
}
if (newTokens.length > 0) {
await saveTokensToStorage();
console.log(`[Sync] Differential sync completed: added ${newTokens.length} new tokens, total ${TOKENS.length} tokens`);
} else {
console.log(`[Sync] Differential sync completed: no new tokens to add, total ${TOKENS.length} tokens`);
}
}
}
async function fetchWithHeaderTimeout(input: Request|string, init: RequestInit & { headerTimeoutMs:number, logCtx:any }){
const { headerTimeoutMs, logCtx, ...rest } = init;
const controller = new AbortController();
const timer = setTimeout(()=>controller.abort(new Error("upstream header timeout")), headerTimeoutMs);
try{
const hdrs = new Headers(rest.headers as HeadersInit);
const hdrEntries = Object.fromEntries(hdrs.entries());
if (hdrEntries["authorization"]) hdrEntries["authorization"] = `Bearer ${mask((hdrEntries["authorization"] as string).slice(7))}`;
log.info({ 事件:"上游请求", 方法:(rest.method ?? "GET"), URL: typeof input==="string"? input : (input as Request).url, 头: hdrEntries, ...logCtx });
const resp = await fetch(input, { ...rest, signal: controller.signal });
clearTimeout(timer);
log.info({
事件:"上游响应头",
状态: resp.status,
类型: resp.headers.get("content-type") ?? "",
长度: resp.headers.get("content-length") ?? "",
头: Object.fromEntries(resp.headers.entries()),
...logCtx
});
return resp;
}catch(e){
clearTimeout(timer);
log.warn({ 事件:"上游请求异常/首包超时", 错误:String((e as any)?.message ?? e), ...logCtx });
throw e;
}
}
function withTimeout<T>(p: Promise<T>, ms: number, label = "timeout", logCtx?:any): Promise<T> {
return new Promise<T>((resolve, reject) => {
const t = setTimeout(() => {
log.warn({ 事件:"Promise超时", 标签:label, 限时ms:ms, ...logCtx });
reject(new Error(label));
}, ms);
p.then(v => { clearTimeout(t); resolve(v); }, e => { clearTimeout(t); reject(e); });
});
}
function openaiChunk(model:string, textDelta:string){
return { id: "chatcmpl_" + Math.random().toString(36).slice(2), object:"chat.completion.chunk",
created: Math.floor(Date.now()/1000), model,
choices:[{ index:0, delta:{ content:textDelta }, finish_reason:null }] };
}
function openaiNonStream(model:string, content:string){
return { id: "chatcmpl_" + Math.random().toString(36).slice(2), object:"chat.completion",
created: Math.floor(Date.now()/1000), model,
choices:[{ index:0, message:{ role:"assistant", content }, finish_reason:"stop" }], usage:null };
}
function extractTextFromPart(part:any):string{
if (part==null) return "";
if (typeof part==="string") return part;
if (typeof part==="object"){
const t = (part.type ?? "").toString().toLowerCase();
if (t==="text" || t==="input_text") return typeof part.text==="string" ? part.text : String(part?.text ?? "");
}
return "";
}
function flattenContent(content:any):string{
if (content==null) return "";
if (typeof content==="string") return content;
if (Array.isArray(content)) return content.map(extractTextFromPart).filter(Boolean).join("\n\n").trim();
if (typeof content==="object") return extractTextFromPart(content).trim();
return String(content);
}
function normalizeMessages(messages:any[]){ return messages.map(m=>({ role:(m?.role ?? "user").toString(), content: flattenContent(m?.content) })); }
function extractDeltaFromTextChunk(raw: string): { delta: string; isFinal: boolean } {
let s = (raw ?? "").trim();
if (!s) return { delta: "", isFinal: false };
if (s.startsWith("data:")) s = s.slice(5).trim();
try {
const obj = JSON.parse(s);
const text = typeof obj?.content === "string" ? obj.content
: typeof obj?.answer === "string" ? obj.answer
: typeof obj?.message === "string" ? obj.message
: typeof obj?.text === "string" ? obj.text
: "";
const isFinal = (obj?.tag === "final") || (obj?.finish_reason === "stop");
if (text) return { delta: text, isFinal };
} catch {}
const m = s.match(/"content"\s*:\s*"([^"]*)"/);
if (m) return { delta: m[1], isFinal: /"tag"\s*:\s*"final"/.test(s) };
return { delta: s, isFinal: false };
}
async function incrementallyReadPlainText(
resp: Response,
logCtx: any,
idleMs: number,
totalMs: number
): Promise<{ content: string; status: number; headers: Headers }> {
const body = resp.body as ReadableStream<Uint8Array> | null;
if (!body) return { content: "", status: resp.status, headers: resp.headers };
const reader = body.getReader();
let idleTimer: number | undefined;
let totalTimer: number | undefined;
let readerClosed = false;
let buf = "";
let content = "";
const resetIdle = () => {
if (idleTimer) clearTimeout(idleTimer);
idleTimer = setTimeout(() => {
log.warn({ 事件:"上游plain空闲超时(增量)", 空闲毫秒: idleMs, ...logCtx });
try { reader.cancel("idle timeout"); } catch {}
readerClosed = true;
}, idleMs) as unknown as number;
};
const startTotal = () => {
totalTimer = setTimeout(() => {
log.warn({ 事件:"上游plain总时限触发(增量)", 总毫秒: totalMs, ...logCtx });
try { reader.cancel("total timeout"); } catch {}
readerClosed = true;
}, totalMs) as unknown as number;
};
resetIdle();
startTotal();
try {
while (!readerClosed) {
const { done, value } = await reader.read();
if (done) break;
resetIdle();
buf += dec.decode(value, { stream:true });
let idx;
while ((idx = buf.indexOf("\n\n")) !== -1) {
const chunk = buf.slice(0, idx); buf = buf.slice(idx + 2);
const { delta, isFinal } = extractDeltaFromTextChunk(chunk);
log.debug({ 事件:"上游plain分片", 原文预览: chunk.slice(0, 200), 提取: delta.slice(0, 200), ...logCtx });
if (delta) content += delta;
if (isFinal) { readerClosed = true; break; }
}