Repository navigation
Expand file tree
/
Copy path_worker.js
More file actions
5528 lines (4942 loc) · 175 KB
/
Copy path_worker.js
File metadata and controls
5528 lines (4942 loc) · 175 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
/**
* WorkersAI2API
* 一个反向代理:把 Cloudflare Workers AI 转换成 OpenAI 兼容的接口格式,
* 支持多账号负载均衡、故障自动切换重试,还自带一个可视化管理面板。
*/
// 默认模型映射表(左边是客户端请求的模型名,右边是 Cloudflare 上对应的真实模型)
const DEFAULT_MODEL_MAP = {
// 对话 / 文本生成模型
'glm-5.2': '@cf/zai-org/glm-5.2',
'glm-4.7-flash': '@cf/zai-org/glm-4.7-flash',
'kimi-k2.7-code': '@cf/moonshotai/kimi-k2.7-code',
'kimi-k2.6': '@cf/moonshotai/kimi-k2.6', // 就是一坨屎,别吃
'gemma-4-26b-a4b-it': '@cf/google/gemma-4-26b-a4b-it',
'nemotron-3-120b-a12b': '@cf/nvidia/nemotron-3-120b-a12b',
'gpt-oss-20b': '@cf/openai/gpt-oss-20b',
'gpt-oss-120b': '@cf/openai/gpt-oss-120b',
// 向量嵌入(Embeddings)模型
'embeddinggemma-300m': '@cf/google/embeddinggemma-300m',
'qwen3-embedding-0.6b': '@cf/qwen/qwen3-embedding-0.6b',
'bge-m3': '@cf/baai/bge-m3'
};
export default {
async fetch(request, env, ctx) {
// 1. 检查是否绑定了 KV 存储
if (!env.KV) {
return handleKVError(request);
}
// 2. 检查是否配置了 ADMIN_PASSWORD 环境变量
if (!env.ADMIN_PASSWORD) {
return handlePasswordError(request);
}
// 处理跨域预检请求(OPTIONS)
if (request.method === 'OPTIONS') {
return new Response(null, {
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS, DELETE',
'Access-Control-Allow-Headers': 'Content-Type, Authorization, x-api-key'
}
});
}
const url = new URL(request.url);
// 2. OpenAI 兼容的代理接口(/v1/ 开头)
if (url.pathname.startsWith('/v1/')) {
const response = await handleV1Proxy(request, env, ctx);
return addCORSHeaders(response);
}
// 3. 后台管理面板的 API 接口(/api/ 开头)
if (url.pathname.startsWith('/api/')) {
const response = await handleDashboardApi(request, env, ctx);
return addCORSHeaders(response);
}
// 4. 后台管理面板页面
if (url.pathname === '/admin' || url.pathname === '/admin/') {
const isLoggedIn = await verifyAdminCookie(request, env);
if (isLoggedIn) {
return handleAdminPage(request, env, ctx);
} else {
// 未登录则跳转到首页(登录页)
return new Response(null, {
status: 302,
headers: { 'Location': '/' }
});
}
}
// 5. 首页 / 登录页
if (url.pathname === '/') {
return handleLandingPage(request, env, ctx);
}
// robots.txt 支持,用于屏蔽搜索引擎爬虫
if (url.pathname === '/robots.txt') {
return new Response('User-agent: *\nDisallow: /', {
headers: { 'Content-Type': 'text/plain; charset=utf-8' }
});
}
// 6. 其他路径一律返回 404
return new Response('404 Not Found', { status: 404 });
}
};
// 工具函数:给响应加上跨域(CORS)响应头
function addCORSHeaders(response) {
const newResponse = new Response(response.body, response);
newResponse.headers.set('Access-Control-Allow-Origin', '*');
newResponse.headers.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, DELETE');
newResponse.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization, x-api-key');
return newResponse;
}
// 工具函数:计算字符串的 SHA-256 哈希值
async function sha256(message) {
const msgBuffer = new TextEncoder().encode(message);
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}
// ----------------------------------------------------
// KV 读写相关工具函数
// (把所有配置合并存到一个 'config' 键里,一次读取就能拿到全部配置,省 KV 读次数)
// ----------------------------------------------------
const memoryCache = {
config: null,
configExpiry: 0
};
const CACHE_TTL_MS = 60000; // 内存缓存有效期:1 分钟
async function getAppConfig(env) {
const now = Date.now();
if (memoryCache.config && now < memoryCache.configExpiry) {
return memoryCache.config;
}
const raw = await env.KV.get('config');
let parsed = { accounts: [], apiKeys: [], customModelMap: {} };
if (raw) {
try {
const data = JSON.parse(raw);
parsed = {
accounts: data.accounts || [],
apiKeys: data.apiKeys || [],
customModelMap: data.customModelMap || {}
};
} catch (e) { }
} else {
// 仅在 KV 首次初始化时写入默认模型映射,避免覆盖已有配置。
parsed.customModelMap = { ...DEFAULT_MODEL_MAP };
await env.KV.put('config', JSON.stringify(parsed));
}
memoryCache.config = parsed;
memoryCache.configExpiry = now + CACHE_TTL_MS;
return parsed;
}
async function saveAppConfig(env, config) {
await env.KV.put('config', JSON.stringify(config));
memoryCache.config = config;
memoryCache.configExpiry = Date.now() + CACHE_TTL_MS;
}
async function getAccounts(env) {
const config = await getAppConfig(env);
return config.accounts;
}
async function saveAccounts(env, accounts) {
const config = await getAppConfig(env);
config.accounts = accounts;
await saveAppConfig(env, config);
await env.KV.delete('cache_usage_summary'); // 清除用量统计的缓存
}
async function getApiKeys(env) {
const config = await getAppConfig(env);
return config.apiKeys;
}
async function saveApiKeys(env, keys) {
const config = await getAppConfig(env);
config.apiKeys = keys;
await saveAppConfig(env, config);
}
async function getCustomModelMap(env) {
const config = await getAppConfig(env);
return config.customModelMap;
}
async function saveCustomModelMap(env, map) {
const config = await getAppConfig(env);
config.customModelMap = map;
await saveAppConfig(env, config);
}
// ----------------------------------------------------
// 管理员身份验证(同时支持 Cookie 和 Authorization 请求头)
// ----------------------------------------------------
async function checkAdminAuth(request, env) {
// 1. 先从 Cookie 里取登录令牌(浏览器访问时走这里)
const cookies = request.headers.get('Cookie') || '';
const cookieMatch = cookies.match(/admin_token=([^;]+)/);
let token = cookieMatch ? cookieMatch[1] : null;
// 2. Cookie 里没有的话,再从 Authorization 请求头里取(API 工具调用时走这里)
if (!token) {
const authHeader = request.headers.get('Authorization');
if (authHeader && authHeader.startsWith('Bearer ')) {
token = authHeader.substring(7);
}
}
if (!token) return false;
const expectedPassword = env.ADMIN_PASSWORD ? env.ADMIN_PASSWORD.trim() : '';
if (!expectedPassword) return false; // 还没配置管理员密码
const expectedHash = await sha256(expectedPassword);
return token === expectedHash;
}
// 校验管理员的登录 Cookie(用于页面访问的权限判断)
async function verifyAdminCookie(request, env) {
const cookies = request.headers.get('Cookie') || '';
const cookieMatch = cookies.match(/admin_token=([^;]+)/);
if (!cookieMatch) return false;
const token = cookieMatch[1];
const expectedPassword = env.ADMIN_PASSWORD ? env.ADMIN_PASSWORD.trim() : '';
if (!expectedPassword) return false;
const expectedHash = await sha256(expectedPassword);
return token === expectedHash;
}
// ----------------------------------------------------
// 代理接口的鉴权工具函数
// ----------------------------------------------------
async function checkProxyAuth(request, env) {
const apiKeys = await getApiKeys(env);
if (apiKeys.length === 0) {
return true; // 没配置任何密钥 = 不校验,谁都能用
}
// 先检查 x-api-key 头
const xApiKey = request.headers.get('x-api-key');
if (xApiKey && apiKeys.some(k => k.key === xApiKey)) {
return true;
}
// 再检查 Authorization: Bearer 头
const authHeader = request.headers.get('Authorization');
if (authHeader && authHeader.startsWith('Bearer ')) {
const token = authHeader.substring(7);
return apiKeys.some(k => k.key === token);
}
return false;
}
// ----------------------------------------------------
// 用量统计的缓存工具函数
// ----------------------------------------------------
async function getCachedSummary(env) {
const cached = await env.KV.get('cache_usage_summary');
if (cached) {
try {
const data = JSON.parse(cached);
if (Date.now() - data.timestamp < 300000) { // 缓存有效期 5 分钟
return data;
}
} catch (e) { }
}
return null;
}
async function setCachedSummary(env, summaryData) {
const data = {
...summaryData,
timestamp: Date.now()
};
await env.KV.put('cache_usage_summary', JSON.stringify(data));
}
async function refreshAccountsUsage(env, accounts, limit = 20) {
const cachedDetailsRaw = await env.KV.get('cache_usage_details');
let cacheMap = {};
if (cachedDetailsRaw) {
try {
cacheMap = JSON.parse(cachedDetailsRaw) || {};
} catch (e) {
cacheMap = {};
}
}
// 按最后更新的时间戳升序排序(时间戳为 0 或不存在的最先更新)
const sortedAccounts = [...accounts].sort((a, b) => {
const tA = cacheMap[a.id]?.timestamp || 0;
const tB = cacheMap[b.id]?.timestamp || 0;
return tA - tB;
});
const accountsToUpdate = sortedAccounts.slice(0, limit);
const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
sevenDaysAgo.setUTCHours(0, 0, 0, 0);
const startSevenDays = sevenDaysAgo.toISOString().split('.')[0] + 'Z';
const todayUTC = new Date();
todayUTC.setUTCHours(0, 0, 0, 0);
const startToday = todayUTC.toISOString().split('.')[0] + 'Z';
const promises = accountsToUpdate.map(async (account) => {
try {
const [todayGroups, historyGroups] = await Promise.all([
queryGraphQL(account.accountId, account.apiToken, startToday),
queryGraphQL(account.accountId, account.apiToken, startSevenDays)
]);
const todayParsed = processAnalytics(todayGroups);
const historyParsed = processAnalytics(historyGroups);
cacheMap[account.id] = {
status: 'active',
error: null,
usageToday: todayParsed.todayTotalNeurons,
modelsToday: todayParsed.todayModels,
history: historyParsed.history,
timestamp: Date.now()
};
} catch (e) {
console.error(`Error querying GraphQL for ${account.name}:`, e);
cacheMap[account.id] = {
status: 'error',
error: e.message,
usageToday: cacheMap[account.id]?.usageToday || 0,
modelsToday: cacheMap[account.id]?.modelsToday || [],
history: cacheMap[account.id]?.history || [],
timestamp: Date.now() // 即使出错也更新时间戳,以便其他账号轮转刷新
};
}
});
await Promise.all(promises);
await env.KV.put('cache_usage_details', JSON.stringify(cacheMap));
return cacheMap;
}
// ----------------------------------------------------
// Cloudflare GraphQL 用量分析查询
// ----------------------------------------------------
async function queryGraphQL(accountId, apiToken, startDateTime) {
const query = `
query GetAIUsage($accountId: String!, $start: String!) {
viewer {
accounts(filter: { accountTag: $accountId }) {
aiInferenceAdaptiveGroups(
filter: { datetime_geq: $start }
limit: 1000
) {
count
sum {
totalNeurons
}
dimensions {
date
modelId
}
}
}
}
}
`;
const response = await fetch(`https://api.cloudflare.com/client/v4/graphql`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
query,
variables: {
accountId,
start: startDateTime
}
})
});
if (!response.ok) {
throw new Error(`GraphQL API error: ${response.statusText}`);
}
const result = await response.json();
if (result.errors && result.errors.length > 0) {
throw new Error(result.errors[0].message);
}
return result?.data?.viewer?.accounts?.[0]?.aiInferenceAdaptiveGroups || [];
}
function processAnalytics(groups) {
const todayStr = new Date().toISOString().split('T')[0];
let todayTotalNeurons = 0;
const todayModelsMap = {};
const historyMap = {};
// 先把最近 7 天的历史数据全部初始化为 0
for (let i = 6; i >= 0; i--) {
const d = new Date(Date.now() - i * 24 * 60 * 60 * 1000);
const dStr = d.toISOString().split('T')[0];
historyMap[dStr] = 0;
}
for (const group of groups) {
const date = group.dimensions.date;
const model = group.dimensions.modelId;
const neurons = group.sum.totalNeurons || 0;
const count = group.count || 0;
if (date === todayStr) {
todayTotalNeurons += neurons;
if (!todayModelsMap[model]) {
todayModelsMap[model] = { model, neurons: 0, requests: 0 };
}
todayModelsMap[model].neurons += neurons;
todayModelsMap[model].requests += count;
}
if (historyMap[date] !== undefined) {
historyMap[date] += neurons;
}
}
const todayModels = Object.values(todayModelsMap).sort((a, b) => b.neurons - a.neurons);
const history = Object.keys(historyMap)
.sort()
.map(date => ({ date, neurons: historyMap[date] }));
return {
todayTotalNeurons,
todayModels,
history
};
}
// ----------------------------------------------------
// OpenAI 兼容代理接口(/v1/)的处理函数
// ----------------------------------------------------
async function handleV1Proxy(request, env, ctx) {
const url = new URL(request.url);
// 1. 校验调用密钥(API Key)
if (!await checkProxyAuth(request, env)) {
// /v1/messages 返回 Anthropic 格式错误,其他路径返回 OpenAI 格式
if (url.pathname === '/v1/messages') {
return new Response(JSON.stringify({
type: 'error',
error: {
type: 'authentication_error',
message: 'Invalid x-api-key or Authorization header.'
}
}), { status: 401, headers: { 'Content-Type': 'application/json' } });
}
return new Response(JSON.stringify({
error: {
message: "Incorrect or missing API key. Configure keys in the dashboard.",
type: "invalid_request_error",
param: null,
code: "invalid_api_key"
}
}), { status: 401, headers: { 'Content-Type': 'application/json' } });
}
// 2. 获取模型列表接口(/v1/models)
if (url.pathname === '/v1/models' && request.method === 'GET') {
const customMap = await getCustomModelMap(env);
const combinedMap = { ...DEFAULT_MODEL_MAP, ...customMap };
const modelsData = Object.keys(combinedMap).map(id => {
const isEmbedding = id.includes('embedding');
return {
id,
object: 'model',
created: 1686935000,
owned_by: isEmbedding ? 'openai' : 'meta'
};
});
return new Response(JSON.stringify({
object: 'list',
data: modelsData
}), { headers: { 'Content-Type': 'application/json' } });
}
// 3. 对话补全 / 文本补全 接口
if ((url.pathname === '/v1/chat/completions' || url.pathname === '/v1/completions') && request.method === 'POST') {
return handleCompletions(request, env, url.pathname);
}
// 4. Anthropic Messages API 接口(/v1/messages)
if (url.pathname === '/v1/messages' && request.method === 'POST') {
return handleMessages(request, env);
}
// 向量嵌入接口
if (url.pathname === '/v1/embeddings' && request.method === 'POST') {
return handleEmbeddings(request, env);
}
return new Response(JSON.stringify({
error: { message: `Path not found: ${url.pathname}`, type: "invalid_request_error" }
}), { status: 404, headers: { 'Content-Type': 'application/json' } });
}
// ----------------------------------------------------
// 可复用的核心 API 调用函数
// 将 OpenAI Chat Completions 格式的请求发送到 Cloudflare AI 网关,
// 支持多账号负载均衡和故障自动切换。
// 返回格式:{ success: true, data: cfJson } 或 { success: false, error: "..." }
// ----------------------------------------------------
async function callOpenAICompatibleAPI(cfPayload, env, stream) {
const accounts = await getAccounts(env);
const activeAccounts = accounts.filter(a => a.status === 'active');
if (activeAccounts.length === 0) {
return { success: false, error: "No active Cloudflare accounts configured. Add them in the WebUI." };
}
const shuffledAccounts = [...activeAccounts].sort(() => Math.random() - 0.5);
let lastError = null;
for (const account of shuffledAccounts) {
try {
const cfResponse = await fetch(
`https://api.cloudflare.com/client/v4/accounts/${account.accountId}/ai/v1/chat/completions`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${account.apiToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(cfPayload),
}
);
if (cfResponse.ok) {
if (stream) {
return { success: true, stream: cfResponse.body };
} else {
const cfJson = await cfResponse.json();
return { success: true, data: cfJson };
}
} else {
const errorText = await cfResponse.text();
lastError = `CF API returned ${cfResponse.status}: ${errorText}`;
}
} catch (e) {
lastError = `Connection error: ${e.message}`;
}
}
return { success: false, error: `All Cloudflare accounts failed. Last error: ${lastError}` };
}
// 共享的模型名解析函数:根据用户传入的模型名,映射到 Cloudflare 实际模型
async function resolveModelName(model, env) {
if (model.startsWith('@cf/')) return model;
const customMap = await getCustomModelMap(env);
const combinedMap = { ...DEFAULT_MODEL_MAP, ...customMap };
return combinedMap[model] || '@cf/zai-org/glm-4.7-flash';
}
// 对话补全 / 文本补全 的代理处理函数
async function handleCompletions(request, env, pathname) {
let body;
try {
body = await request.json();
} catch (e) {
return new Response(JSON.stringify({ error: { message: "Invalid JSON body", type: "invalid_request_error" } }), { status: 400 });
}
const { model, messages, prompt, stream } = body;
if (pathname === '/v1/chat/completions' && !messages) {
return new Response(JSON.stringify({ error: { message: "messages field is required", type: "invalid_request_error" } }), { status: 400 });
}
if (pathname === '/v1/completions' && !prompt) {
return new Response(JSON.stringify({ error: { message: "prompt field is required", type: "invalid_request_error" } }), { status: 400 });
}
// 解析模型名映射
const cfModel = await resolveModelName(model, env);
// 构造发给 Cloudflare 的请求体
const cfPayload = {
model: cfModel,
messages: pathname === '/v1/chat/completions' ? messages : [{ role: 'user', content: prompt }],
stream: !!stream,
};
const passthroughFields = [
'temperature', 'max_tokens', 'top_p', 'n',
'stop', 'presence_penalty', 'frequency_penalty',
'logprobs', 'top_logprobs', 'seed', 'user',
'tools', 'tool_choice', 'parallel_tool_calls',
'response_format',
];
for (const field of passthroughFields) {
if (body[field] !== undefined) cfPayload[field] = body[field];
}
const result = await callOpenAICompatibleAPI(cfPayload, env, stream);
if (!result.success) {
return new Response(JSON.stringify({
error: { message: result.error, type: "server_error" }
}), { status: 502, headers: { 'Content-Type': 'application/json' } });
}
if (stream) {
const transformedStream = passthroughStream(result.stream, model);
return new Response(transformedStream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Transfer-Encoding': 'chunked',
},
});
} else {
const cfJson = result.data;
if (cfJson.model !== undefined) cfJson.model = model;
return new Response(JSON.stringify(cfJson), {
headers: { 'Content-Type': 'application/json' },
});
}
}
// ----------------------------------------------------
// Anthropic Messages API → OpenAI Chat Completions 格式转换
// ----------------------------------------------------
function convertAnthropicToOpenAI(anthropicBody) {
const openaiBody = {};
// model 直接映射
openaiBody.model = anthropicBody.model;
// max_tokens 直接映射
if (anthropicBody.max_tokens !== undefined) {
openaiBody.max_tokens = anthropicBody.max_tokens;
}
// stream 直接映射
if (anthropicBody.stream !== undefined) {
openaiBody.stream = anthropicBody.stream;
}
// temperature 直接映射
if (anthropicBody.temperature !== undefined) {
openaiBody.temperature = anthropicBody.temperature;
}
// top_p 直接映射
if (anthropicBody.top_p !== undefined) {
openaiBody.top_p = anthropicBody.top_p;
}
// stop_sequences → stop
if (anthropicBody.stop_sequences !== undefined) {
openaiBody.stop = anthropicBody.stop_sequences;
}
// 构建 OpenAI 格式的 messages 数组
const openaiMessages = [];
// Anthropic system 字段 → OpenAI system role message (插入到 messages 最前面)
if (anthropicBody.system) {
let systemContent = '';
if (typeof anthropicBody.system === 'string') {
systemContent = anthropicBody.system;
} else if (Array.isArray(anthropicBody.system)) {
// system 为数组格式:[{type: "text", text: "..."}, ...]
for (const block of anthropicBody.system) {
if (block.type === 'text' && block.text) {
systemContent += block.text + '\n';
}
}
systemContent = systemContent.trim();
}
if (systemContent) {
openaiMessages.push({ role: 'system', content: systemContent });
}
}
// 转换 messages
for (const msg of anthropicBody.messages) {
const role = msg.role;
const content = msg.content;
// Anthropic 的 content 可能是字符串或数组
if (typeof content === 'string') {
openaiMessages.push({ role, content });
} else if (Array.isArray(content)) {
// assistant 消息:text 和 tool_use 需合并为一条消息(Bug #4)
if (role === 'assistant') {
let textContent = '';
const toolCalls = [];
for (const block of content) {
if (block.type === 'text') {
textContent += block.text || '';
} else if (block.type === 'tool_use') {
toolCalls.push({
id: block.id,
type: 'function',
function: {
name: block.name,
arguments: JSON.stringify(block.input || {})
}
});
}
}
const assistantMsg = { role: 'assistant', content: textContent || null };
if (toolCalls.length > 0) {
assistantMsg.tool_calls = toolCalls;
}
openaiMessages.push(assistantMsg);
continue;
}
// user 消息:先处理 tool_result,再处理 text/image(Bug #5)
if (role === 'user') {
// 先处理 tool_result 块
for (const block of content) {
if (block.type === 'tool_result') {
let resultContent = '';
if (typeof block.content === 'string') {
resultContent = block.content;
} else if (Array.isArray(block.content)) {
for (const c of block.content) {
if (c.type === 'text' && c.text) {
resultContent += c.text;
}
}
}
const toolMsg = {
role: 'tool',
tool_call_id: block.tool_use_id,
content: resultContent
};
if (block.name) toolMsg.name = block.name;
openaiMessages.push(toolMsg);
}
}
// 再处理剩余的 text 和 image 块
const openaiContentParts = [];
for (const block of content) {
if (block.type === 'text') {
openaiContentParts.push({ type: 'text', text: block.text || '' });
} else if (block.type === 'image') {
// Anthropic image source → OpenAI image_url
const source = block.source || {};
let imageUrl = '';
if (source.type === 'url' && source.url) {
// URL 类型图片(Bug #3)
imageUrl = source.url;
} else if (source.data) {
const mediaType = source.media_type || 'image/png';
imageUrl = `data:${mediaType};base64,${source.data}`;
}
if (imageUrl) {
openaiContentParts.push({
type: 'image_url',
image_url: { url: imageUrl }
});
}
}
}
if (openaiContentParts.length > 0) {
openaiMessages.push({ role: 'user', content: openaiContentParts });
}
continue;
}
// 兜底:其他角色只处理 text 块
const openaiContentParts = [];
for (const block of content) {
if (block.type === 'text') {
openaiContentParts.push({ type: 'text', text: block.text || '' });
}
}
if (openaiContentParts.length > 0) {
openaiMessages.push({ role, content: openaiContentParts });
}
}
}
// 确保第一条消息是 user(OpenAI 要求第一条消息必须是 user 或 system)
// 如果第一条是 assistant(来自 Anthropic 的多轮 tool calling),在它前面插入一条占位 user 消息
const firstNonSystemMsg = openaiMessages.find(m => m.role !== 'system');
if (firstNonSystemMsg && firstNonSystemMsg.role === 'assistant') {
// 找到 system 消息后的位置,插入一条空的 user 消息
const systemCount = openaiMessages.filter(m => m.role === 'system').length;
openaiMessages.splice(systemCount, 0, {
role: 'user',
content: '_'
});
}
openaiBody.messages = openaiMessages;
// tools 字段转换:Anthropic 格式 → OpenAI 格式
if (anthropicBody.tools && Array.isArray(anthropicBody.tools)) {
openaiBody.tools = anthropicBody.tools.map(tool => ({
type: 'function',
function: {
name: tool.name,
description: tool.description || '',
parameters: tool.input_schema || {}
}
}));
}
// tool_choice 转换
if (anthropicBody.tool_choice) {
const tc = anthropicBody.tool_choice;
if (tc.type === 'auto') {
openaiBody.tool_choice = 'auto';
} else if (tc.type === 'any') {
openaiBody.tool_choice = 'required';
} else if (tc.type === 'tool' && tc.name) {
openaiBody.tool_choice = { type: 'function', function: { name: tc.name } };
}
}
return openaiBody;
}
// ----------------------------------------------------
// OpenAI Chat Completion 响应 → Anthropic Messages 格式转换
// ----------------------------------------------------
function convertOpenAIToAnthropic(openaiResponse, originalModel) {
const choice = openaiResponse.choices?.[0] || {};
const message = choice.message || {};
const anthropicResponse = {
id: `msg_${crypto.randomUUID()}`,
type: 'message',
role: 'assistant',
content: [],
model: originalModel,
stop_reason: null,
stop_sequence: null,
usage: {
input_tokens: openaiResponse.usage?.prompt_tokens || 0,
output_tokens: openaiResponse.usage?.completion_tokens || 0
}
};
// 文本内容 → text block
if (message.content) {
anthropicResponse.content.push({
type: 'text',
text: message.content
});
}
// tool_calls → tool_use blocks
if (message.tool_calls && Array.isArray(message.tool_calls)) {
for (const tc of message.tool_calls) {
let inputObj = {};
try {
inputObj = typeof tc.function.arguments === 'string'
? JSON.parse(tc.function.arguments)
: tc.function.arguments;
} catch (_) {
inputObj = {};
}
anthropicResponse.content.push({
type: 'tool_use',
id: tc.id,
name: tc.function.name,
input: inputObj
});
}
}
// finish_reason → stop_reason 映射
const finishReason = choice.finish_reason;
if (finishReason === 'stop') {
anthropicResponse.stop_reason = 'end_turn';
} else if (finishReason === 'tool_calls') {
anthropicResponse.stop_reason = 'tool_use';
} else if (finishReason === 'length') {
anthropicResponse.stop_reason = 'max_tokens';
} else {
anthropicResponse.stop_reason = finishReason || 'end_turn';
}
return anthropicResponse;
}
// ----------------------------------------------------
// OpenAI 错误响应 → Anthropic 错误格式转换
// ----------------------------------------------------
function convertOpenAIErrorToAnthropic(openaiError, statusCode) {
return {
type: 'error',
error: {
type: 'api_error',
message: openaiError?.error?.message || openaiError?.message || 'Unknown error'
}
};
}
// ----------------------------------------------------
// Anthropic /v1/messages 路由处理函数
// ----------------------------------------------------
async function handleMessages(request, env) {
// 认证由 handleV1Proxy 的 checkProxyAuth 统一处理(支持 x-api-key + Bearer)
// 解析请求体
let anthropicBody;
try {
anthropicBody = await request.json();
} catch (e) {
return new Response(JSON.stringify({
type: 'error',
error: { type: 'invalid_request_error', message: 'Invalid JSON body.' }
}), { status: 400, headers: { 'Content-Type': 'application/json' } });
}
// 基本参数校验
if (!anthropicBody.messages || !Array.isArray(anthropicBody.messages)) {
return new Response(JSON.stringify({
type: 'error',
error: { type: 'invalid_request_error', message: 'messages field is required and must be an array.' }
}), { status: 400, headers: { 'Content-Type': 'application/json' } });
}
if (!anthropicBody.max_tokens) {
return new Response(JSON.stringify({
type: 'error',
error: { type: 'invalid_request_error', message: 'max_tokens is required.' }
}), { status: 400, headers: { 'Content-Type': 'application/json' } });
}
// 解析模型名映射
const model = anthropicBody.model;
const cfModel = await resolveModelName(model, env);
// Anthropic → OpenAI 格式转换
const openaiBody = convertAnthropicToOpenAI(anthropicBody);
openaiBody.model = cfModel;
const stream = !!anthropicBody.stream;
const result = await callOpenAICompatibleAPI(openaiBody, env, stream);
if (!result.success) {
// 尝试解析 CF 错误详情
let errorDetail;
try {
if (result.error && result.error.includes('CF API returned')) {
const match = result.error.match(/CF API returned \d+: (.+)/);
if (match) {
errorDetail = JSON.parse(match[1]);
}
}
} catch (_) { }
const anthropicError = convertOpenAIErrorToAnthropic(
errorDetail || { message: result.error },
502
);
return new Response(JSON.stringify(anthropicError), {
status: 502,
headers: { 'Content-Type': 'application/json' }
});
}
if (stream) {
// 流式:转换流
const transformedStream = anthropicStreamTransform(result.stream, model, anthropicBody.messages);
return new Response(transformedStream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Transfer-Encoding': 'chunked',
},
});
} else {
// 非流式:转换响应
const openaiResponse = result.data;
const anthropicResponse = convertOpenAIToAnthropic(openaiResponse, model);
return new Response(JSON.stringify(anthropicResponse), {
headers: { 'Content-Type': 'application/json' },
});
}
}