文章摘要
空天之境的AI系统

注意

以下api以及ai模型和2api技术仅适用于学习,如需api服务的可直接在留言板或页面底部留言窗口留言,部分模型完全免费。

使用AI请遵守国家法律法规,详情请前往清朗·整治AI技术滥用了解

一、sophnet2api


https://www.sophnet.com/#/playground/chat
正在维护
当前版本 2.2.1 Beta
Demo https://warm-squirrel-74.deno.dev
语言 TypeScript
框架 Deno

Models

  • Qwen千问全系列

https://if.be-a.dev/

Features

  • /v1 下的 OpenAI 兼容 API, 支持聊天补全与模型获取.
  • -Search 后缀模型是带有联网搜索
  • -Full-Context 后缀模型是绕过了 10 条上下文限制

1、部署

前往Deno创建XXX.ts

sophnet2api.ts
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
import { serve } from "https://deno.land/std@0.220.1/http/server.ts";

// 定义常量
const SOPHNET_BASE_URL = "https://www.sophnet.com/api";
const PROJECT_UUID = "Ar79PWUQUAhjJOja2orHs";
const PORT = 3000;
const TOKEN_KEY = "sophnet_anonymous_token";
const MAX_RETRIES = 5; // 增加最大重试次数
const INITIAL_RETRY_DELAY_MS = 100; // 初始重试延迟(毫秒)
const MAX_RETRY_DELAY_MS = 5000; // 最大重试延迟(毫秒)

// 初始化Deno KV
const kv = await Deno.openKv();

// 定义接口
interface AnonymousTokenResponse {
status: number;
message: string;
result: {
anonymousToken: string;
expires: string;
};
timestamp: number;
}

interface SophNetModel {
id: number;
serviceUuid: string | null;
projectUuid: string;
displayName: string;
modelFamily: string;
available: boolean;
isBaseModel: boolean;
features: any;
supportedStream: boolean;
supportedImageInputs: boolean;
schema: Array<{
name: string;
displayName: string;
des: string;
type: string;
range: number[];
defaultValue: number;
required: boolean;
}>;
}

interface ModelsResponse {
status: number;
message: string;
result: SophNetModel[];
timestamp: number;
}

interface TokenInfo {
token: string;
expires: string;
}

interface Message {
role: string;
content: string;
}

interface Reference {
content: string;
id: string;
index: number;
title: string;
type: string;
url: string;
}

// 随机生成一个用户代理字符串
function getRandomUserAgent(): string {
const userAgents = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Safari/605.1.15",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.2151.44",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/119.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Firefox/119.0",
"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/119.0",
];
return userAgents[Math.floor(Math.random() * userAgents.length)];
}

// 计算指数退避延迟
function getExponentialBackoffDelay(retryCount: number): number {
const delay = INITIAL_RETRY_DELAY_MS * Math.pow(2, retryCount);
const jitter = Math.random() * INITIAL_RETRY_DELAY_MS; // 添加随机抖动
return Math.min(delay + jitter, MAX_RETRY_DELAY_MS);
}

// 延迟函数
function sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}

// 从KV获取token
async function getTokenFromKV(): Promise<TokenInfo | null> {
const tokenEntry = await kv.get<TokenInfo>([TOKEN_KEY]);
return tokenEntry.value;
}

// 存储token到KV
async function storeTokenToKV(token: string, expires: string): Promise<void> {
await kv.set([TOKEN_KEY], { token, expires });
}

// 获取匿名token
async function getAnonymousToken(retryCount = 0): Promise<string> {
try {
const response = await fetch(`${SOPHNET_BASE_URL}/sys/login/anonymous`, {
method: "GET",
headers: {
"Accept": "application/json",
"User-Agent": getRandomUserAgent(), // 使用随机UA
},
});

// 如果是 429 或 500 错误,进行重试
if ((response.status === 429 || response.status >= 500) && retryCount < MAX_RETRIES) {
const delay = getExponentialBackoffDelay(retryCount);
console.warn(`Get token failed with status ${response.status}. Retrying in ${delay}ms... (${retryCount + 1}/${MAX_RETRIES})`);
await sleep(delay);
return getAnonymousToken(retryCount + 1);
}

if (!response.ok) {
throw new Error(`Failed to get token: ${response.status}`);
}

const data = await response.json() as AnonymousTokenResponse;
await storeTokenToKV(data.result.anonymousToken, data.result.expires);
return data.result.anonymousToken;
} catch (error) {
console.error("Error getting anonymous token:", error);
throw error;
}
}

// 获取有效token
async function getValidToken(): Promise<string> {
// 先尝试从KV获取
const tokenInfo = await getTokenFromKV();

// 如果KV中有token且未过期,则使用该token
if (tokenInfo && new Date(tokenInfo.expires) > new Date()) {
return tokenInfo.token;
}

// 否则获取新token
return await getAnonymousToken();
}

// 获取模型列表
async function getModels(token: string, retryCount = 0): Promise<SophNetModel[]> {
try {
const response = await fetch(
`${SOPHNET_BASE_URL}/public/playground/models?projectUuid=${PROJECT_UUID}`,
{
method: "GET",
headers: {
"Accept": "application/json",
"User-Agent": getRandomUserAgent(), // 使用随机UA
"Authorization": `Bearer anon-${token}`,
},
},
);

// 如果是401或403错误,尝试刷新token并重试
if ((response.status === 401 || response.status === 403) && retryCount < MAX_RETRIES) {
console.log(`Token expired, refreshing and retrying models request (${retryCount + 1}/${MAX_RETRIES})...`);
const newToken = await getAnonymousToken();
return await getModels(newToken, retryCount + 1);
}

// 如果是 429 或 500 错误,进行重试
if ((response.status === 429 || response.status >= 500) && retryCount < MAX_RETRIES) {
const delay = getExponentialBackoffDelay(retryCount);
console.warn(`Get models failed with status ${response.status}. Retrying in ${delay}ms... (${retryCount + 1}/${MAX_RETRIES})`);
await sleep(delay);
return getModels(token, retryCount + 1); // 使用当前token重试,如果失败会在上面的逻辑中刷新
}

if (!response.ok) {
throw new Error(`Failed to get models: ${response.status}`);
}

const data = await response.json() as ModelsResponse;

// 请求成功后获取新token并存储 (后台刷新)
getAnonymousToken().catch(err => console.error("Background token refresh failed:", err));

return data.result;
} catch (error) {
console.error("Error getting models:", error);
throw error;
}
}

// 将SophNet模型转换为OpenAI格式
function transformModelsToOpenAIFormat(models: SophNetModel[]) {
const transformedModels = [];

// 为每个模型创建标准版本、搜索版本和全上下文版本
for (const model of models) {
// 添加标准模型
transformedModels.push({
id: model.modelFamily,
object: "model",
created: Date.now(),
owned_by: "sophnet",
permission: [{
id: `modelperm-${model.id}`,
object: "model_permission",
created: Date.now(),
allow_create_engine: false,
allow_sampling: true,
allow_logprobs: false,
allow_search_indices: false,
allow_view: true,
allow_fine_tuning: false,
organization: "*",
group: null,
is_blocking: false,
}],
root: model.modelFamily,
parent: null,
});

// 添加搜索版本模型
transformedModels.push({
id: `${model.modelFamily}-Search`,
object: "model",
created: Date.now(),
owned_by: "sophnet",
permission: [{
id: `modelperm-${model.id}-Search`,
object: "model_permission",
created: Date.now(),
allow_create_engine: false,
allow_sampling: true,
allow_logprobs: false,
allow_search_indices: true,
allow_view: true,
allow_fine_tuning: false,
organization: "*",
group: null,
is_blocking: false,
}],
root: model.modelFamily,
parent: null,
});

// 添加全上下文版本模型
transformedModels.push({
id: `${model.modelFamily}-Full-Context`,
object: "model",
created: Date.now(),
owned_by: "sophnet",
permission: [{
id: `modelperm-${model.id}-Full-Context`,
object: "model_permission",
created: Date.now(),
allow_create_engine: false,
allow_sampling: true,
allow_logprobs: false,
allow_search_indices: false,
allow_view: true,
allow_fine_tuning: false,
organization: "*",
group: null,
is_blocking: false,
}],
root: model.modelFamily,
parent: null,
});

// 添加全上下文+搜索版本模型
transformedModels.push({
id: `${model.modelFamily}-Full-Context-Search`,
object: "model",
created: Date.now(),
owned_by: "sophnet",
permission: [{
id: `modelperm-${model.id}-Full-Context-Search`,
object: "model_permission",
created: Date.now(),
allow_create_engine: false,
allow_sampling: true,
allow_logprobs: false,
allow_search_indices: true,
allow_view: true,
allow_fine_tuning: false,
organization: "*",
group: null,
is_blocking: false,
}],
root: model.modelFamily,
parent: null,
});
}

return {
object: "list",
data: transformedModels,
};
}

// 处理全上下文功能
function processFullContext(messages: Message[]): Message[] {
// 复制消息数组,避免修改原数组
const messagesCopy = [...messages];

// 提取系统消息(如果存在)
const systemMessages = messagesCopy.filter(msg => msg.role === "system");

// 获取非系统消息
const nonSystemMessages = messagesCopy.filter(msg => msg.role !== "system");

// 如果消息总数少于或等于3对(6条消息),则不需要处理
if (nonSystemMessages.length <= 6) {
return messages;
}

// 提取最后3轮对话(最多6条消息)
const recentMessages = nonSystemMessages.slice(-6);

// 提取需要合并的历史消息
const historyMessages = nonSystemMessages.slice(0, -6);

// 创建历史消息的摘要
const historySummary = {
role: "user",
content: `这里是此前的对话上下文: ${JSON.stringify(historyMessages)}`
};

// 组合新的消息数组:系统消息 + 历史摘要 + 最近消息
return [...systemMessages, historySummary, ...recentMessages];
}

// 将数字转换为上标形式
function convertToSuperscript(num: number): string {
const normalDigits = '0123456789';
const superscriptDigits = '⁰¹²³⁴⁵⁶⁷⁸⁹';

return num.toString()
.split('')
.map(char => {
const index = normalDigits.indexOf(char);
return index !== -1 ? superscriptDigits[index] : char;
})
.join('');
}

// 处理聊天完成请求
async function handleChatCompletions(
token: string,
requestBody: any,
stream: boolean,
retryCount = 0,
): Promise<Response> {
// 检查模型名称的后缀
const modelId = requestBody.model;
const webSearchEnable = modelId.includes("-Search");
const fullContextEnable = modelId.includes("-Full-Context");

// 根据后缀确定实际模型ID
let actualModelId = modelId;
if (webSearchEnable) actualModelId = actualModelId.replace("-Search", "");
if (fullContextEnable) actualModelId = actualModelId.replace("-Full-Context", "");

// 处理消息
let processedMessages = requestBody.messages;
if (fullContextEnable) {
processedMessages = processFullContext(requestBody.messages);
}

const sophNetBody = {
temperature: requestBody.temperature || 0.7,
top_p: requestBody.top_p || 0.9,
frequency_penalty: requestBody.frequency_penalty || 0,
presence_penalty: requestBody.presence_penalty || 0,
max_tokens: requestBody.max_tokens || 2048,
webSearchEnable: webSearchEnable,
stop: requestBody.stop || [],
stream: stream.toString(),
model_id: actualModelId,
messages: processedMessages,
};

try {
const response = await fetch(
`${SOPHNET_BASE_URL}/open-apis/projects/${PROJECT_UUID}/chat/completions`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer anon-${token}`,
"Accept": stream ? "text/event-stream" : "application/json",
"User-Agent": getRandomUserAgent(), // 使用随机UA
},
body: JSON.stringify(sophNetBody),
},
);

// 如果是401或403错误,尝试刷新token并重试
if ((response.status === 401 || response.status === 403) && retryCount < MAX_RETRIES) {
console.log(`Chat completion token expired, refreshing and retrying (${retryCount + 1}/${MAX_RETRIES})...`);
const newToken = await getAnonymousToken();
// 使用指数退避等待
const delay = getExponentialBackoffDelay(retryCount);
await sleep(delay);
return await handleChatCompletions(newToken, requestBody, stream, retryCount + 1);
}

// 如果是 429 或 500 错误,进行指数退避重试
if ((response.status === 429 || response.status >= 500) && retryCount < MAX_RETRIES) {
const delay = getExponentialBackoffDelay(retryCount);
console.warn(`Chat completion failed with status ${response.status}. Retrying in ${delay}ms... (${retryCount + 1}/${MAX_RETRIES})`);
await sleep(delay);
return handleChatCompletions(token, requestBody, stream, retryCount + 1); // 使用当前token重试,如果失败会在上面的逻辑中刷新
}

if (!response.ok) {
throw new Error(`Chat completion failed: ${response.status}`);
}

// 请求成功后获取新token并存储 (后台刷新)
getAnonymousToken().catch(err => console.error("Background token refresh failed:", err));

return response;

} catch (error) {
console.error("Error during chat completion fetch:", error);
// 如果是网络错误或其他非HTTP错误,也进行指数退避重试
if (retryCount < MAX_RETRIES) {
const delay = getExponentialBackoffDelay(retryCount);
console.warn(`Chat completion network error. Retrying in ${delay}ms... (${retryCount + 1}/${MAX_RETRIES})`);
await sleep(delay);
return handleChatCompletions(token, requestBody, stream, retryCount + 1);
}
throw error; // 达到最大重试次数后抛出错误
}
}

// 转换流式响应
async function* transformStreamResponse(
readableStream: ReadableStream<Uint8Array>,
) {
const reader = readableStream.getReader();
const decoder = new TextDecoder();
let buffer = "";

// 用于存储所有引用,以便在结束时生成参考资料部分
const references: Reference[] = [];
let referencesEmitted = false; // 标记是否已经发送过参考资料部分

try {
while (true) {
const { done, value } = await reader.read();
if (done) {
// 如果有引用但尚未发送,在结束前发送参考资料部分
if (references.length > 0 && !referencesEmitted) {
const referencesSection = generateReferencesSection(references);
yield `data: ${JSON.stringify({
id: `chatcmpl-${Date.now()}`, // 生成一个唯一的ID
object: "chat.completion.chunk",
created: Math.floor(Date.now() / 1000),
model: "sophnet-model", // 可以使用 SophNet 返回的模型名,或者固定一个
choices: [
{
index: 0,
delta: {
content: `\n\n${referencesSection}`,
},
finish_reason: null, // 在发送参考资料时,finish_reason通常为null
},
],
})}\n\n`;
referencesEmitted = true;
}
break;
}

buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop() || "";

for (const line of lines) {
if (line.trim() === "" || !line.startsWith("data:")) continue;

const data = line.substring(5).trim();
if (data === "[DONE]") {
// 如果有引用但尚未发送,在结束前发送参考资料部分
if (references.length > 0 && !referencesEmitted) {
const referencesSection = generateReferencesSection(references);
yield `data: ${JSON.stringify({
id: `chatcmpl-${Date.now()}`, // 生成一个唯一的ID
object: "chat.completion.chunk",
created: Math.floor(Date.now() / 1000),
model: "sophnet-model", // 可以使用 SophNet 返回的模型名,或者固定一个
choices: [
{
index: 0,
delta: {
content: `\n\n${referencesSection}`,
},
finish_reason: null, // 在发送参考资料时,finish_reason通常为null
},
],
})}\n\n`;
referencesEmitted = true;
}

yield "data: [DONE]\n\n";
continue;
}

try {
const sophNetEvent = JSON.parse(data);

// 检查是否包含引用
if (sophNetEvent.choices?.[0]?.refs && sophNetEvent.choices[0].refs.length > 0) {
// 处理引用
for (const ref of sophNetEvent.choices[0].refs) {
// 检查是否已经存在相同URL的引用
const existingRefIndex = references.findIndex(r => r.url === ref.url);
if (existingRefIndex === -1) {
// 添加新引用
references.push(ref);

// 生成引用标记,使用上标数字
const refIndex = references.length;
const superscriptIndex = `⁽${convertToSuperscript(refIndex)}⁾`;

// 创建带引用标记的事件
yield `data: ${JSON.stringify({
id: sophNetEvent.id || `chatcmpl-${Date.now()}`, // 使用SophNet ID或生成新ID
object: "chat.completion.chunk",
created: Math.floor(Date.now() / 1000),
model: sophNetEvent.model || "sophnet-model", // 使用SophNet模型名或固定
choices: [
{
index: 0,
delta: {
// SophNet的引用信息通常不在content中,我们需要手动添加
content: `[${superscriptIndex}](${ref.url})`,
},
finish_reason: null, // 引用事件通常没有finish_reason
},
],
})}\n\n`;
}
}
} else {
// 转换为OpenAI格式的事件
const openAIEvent = {
id: sophNetEvent.id || `chatcmpl-${Date.now()}`, // 使用SophNet ID或生成新ID
object: "chat.completion.chunk",
created: Math.floor(Date.now() / 1000),
model: sophNetEvent.model || "sophnet-model", // 使用SophNet模型名或固定
choices: [
{
index: 0,
delta: {
// OpenAI通常将内容放在delta.content
reasoning_content: sophNetEvent.choices?.[0]?.delta?.reasoning_content || "",
content: sophNetEvent.choices?.[0]?.delta?.content || "",
},
finish_reason: sophNetEvent.choices?.[0]?.finish_reason || null,
},
],
};

yield `data: ${JSON.stringify(openAIEvent)}\n\n`;
}
} catch (e) {
console.error("Error parsing event:", e, "Line:", line);
// 可以选择在这里发送一个错误事件给客户端
}
}
}
} finally {
reader.releaseLock();
}
}

// 生成参考资料部分
function generateReferencesSection(references: Reference[]): string {
if (references.length === 0) return "";

let section = "## 参考资料\n\n";
references.forEach((ref, index) => {
section += `${index + 1}. [${ref.title}](${ref.url})\n`;
});

return section;
}

// 转换非流式响应
async function transformNonStreamResponse(response: Response) {
const sophNetResponse = await response.json();

// 处理引用
let content = sophNetResponse.choices?.[0]?.message?.content || "";
const references: Reference[] = [];

// 收集所有引用
if (sophNetResponse.choices?.[0]?.message?.refs && sophNetResponse.choices[0].message.refs.length > 0) {
for (const ref of sophNetResponse.choices[0].message.refs) {
references.push(ref);
}

// 为每个引用添加上标标记
references.forEach((ref, index) => {
const refIndex = index + 1;
const superscriptIndex = `⁽${convertToSuperscript(refIndex)}⁾`;
// 在内容末尾添加引用标记
content += ` [${superscriptIndex}](${ref.url})`;
});

// 添加参考资料部分
if (references.length > 0) {
content += "\n\n" + generateReferencesSection(references);
}
}

return {
id: sophNetResponse.id || `chatcmpl-${Date.now()}`, // 使用SophNet ID或生成新ID
object: "chat.completion",
created: Math.floor(Date.now() / 1000),
model: sophNetResponse.model || "sophnet-model", // 使用SophNet模型名或固定
choices: [
{
index: 0,
message: {
role: "assistant",
reasoning_content: sophNetResponse.choices?.[0]?.message?.reasoning_content || "",
content: content,
},
finish_reason: sophNetResponse.choices?.[0]?.finish_reason || "stop",
},
],
usage: sophNetResponse.usage || {
prompt_tokens: 0,
completion_tokens: 0,
total_tokens: 0,
},
};
}

// 主处理函数
async function handler(req: Request): Promise<Response> {
const url = new URL(req.url);
const path = url.pathname;

// CORS预检请求处理
if (req.method === "OPTIONS") {
return new Response(null, {
status: 204,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Max-Age": "86400",
},
});
}

// 获取有效token
let token;
try {
token = await getValidToken();
} catch (error) {
console.error("Failed to get token in handler:", error);
return new Response(
JSON.stringify({ error: "Failed to get token", details: error.message }),
{
status: 500,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
},
);
}

try {
// 模型列表接口
if (path === "/v1/models" && req.method === "GET") {
const models = await getModels(token);
const openAIModels = transformModelsToOpenAIFormat(models);

return new Response(JSON.stringify(openAIModels), {
status: 200,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
});
}

// 聊天完成接口
else if (path === "/v1/chat/completions" && req.method === "POST") {
const requestBody = await req.json();
const stream = requestBody.stream === true;

const sophNetResponse = await handleChatCompletions(token, requestBody, stream);

if (stream) {
const transformedStream = new ReadableStream({
async start(controller) {
try {
for await (const chunk of transformStreamResponse(sophNetResponse.body!)) {
controller.enqueue(new TextEncoder().encode(chunk));
}
controller.close();
} catch (error) {
console.error("Stream transformation error:", error);
// 在流中发送错误信息
const errorData = JSON.stringify({
error: {
message: `Stream processing error: ${error.message}`,
type: "stream_error",
code: null,
}
});
controller.enqueue(new TextEncoder().encode(`data: ${errorData}\n\n`));
controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n"));
controller.close();
}
},
});

return new Response(transformedStream, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"Access-Control-Allow-Origin": "*",
},
});
} else {
const transformedResponse = await transformNonStreamResponse(sophNetResponse);

return new Response(JSON.stringify(transformedResponse), {
status: 200,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
});
}
}

// 未找到路由
else {
return new Response(
JSON.stringify({ error: "Not found", message: "Endpoint not supported" }),
{
status: 404,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
},
);
}
} catch (error) {
console.error("Request handling error:", error);

// 返回统一的错误响应格式
return new Response(
JSON.stringify({
error: {
message: error.message,
type: "api_error", // 或者更具体的错误类型
code: error.status || null, // 如果是HTTP错误,包含状态码
}
}),
{
status: error.status || 500, // 使用错误状态码或默认500
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
},
);
}
}

// 启动服务器
console.log(`Starting server on port ${PORT}...`);
serve(handler, { port: PORT });

2api1.png

图中 projectuuid 即为需要的数据。

2、调用

1、此时我们打开deno分配的链接,
2api2.png
返回json说明部署成功。
2、通过使用OpenWebui,NextChat,酒馆等api调用项目
2api3.png
可以看到刷出50多个模型实现ai自由。
2api4.png
-search为联网搜索版本,这里使用的是最新的千问3。

二、scira2api

https://mcp.scira.ai/
正在维护
当前版本 0.1.0 Alpha
Demo https://lazy-bear-13.deno.dev
语言 TypeScript
框架 Deno

Models

  • Claude 3.7 Sonnet
  • Gemini 2.5 Flash
  • GPT 4.1 Mini
  • Qwen QwQ

Features

  • /v1 下的 OpenAI 兼容 API, 支持聊天补全与模型获取.

1、部署

前往Deno创建XXX.ts

scira2api.ts
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
import { serve } from "https://deno.land/std@0.220.1/http/server.ts";

// 定义常量 搜索https://mcp.scira.ai/api/chat获取变量
const API_URL = "https://mcp.scira.ai/api/chat";
const FIXED_USER_ID = "siufoijroijoifjdhdhd";
const FIXED_CHAT_ID = "Yin5ax00WN24iuR5ASl1f";
const DEFAULT_MODEL = "claude-3-7-sonnet";
const PORT = 8888;

// 定义接口
interface Message {
role: string;
content: string;
parts?: Array<{
type: string;
text: string;
}>;
}

interface SciraPayload {
id: string;
messages: Message[];
selectedModel: string;
mcpServers: any[];
chatId: string;
userId: string;
}

interface OpenAIModel {
id: string;
created: number;
object: string;
}

// 可用模型列表
const AVAILABLE_MODELS: OpenAIModel[] = [
{
id: "qwen-qwq",
created: Date.now(),
object: "model",
},
{
id: "gemini-2.5-flash",
created: Date.now(),
object: "model",
},
{
id: "gpt-4.1-mini",
created: Date.now(),
object: "model",
},
{
id: "claude-3-7-sonnet",
created: Date.now(),
object: "model",
},
];

// 格式化消息为Scira格式
function formatMessagesForScira(messages: Message[]): Message[] {
return messages.map(msg => ({
role: msg.role,
content: msg.content,
parts: [{
type: "text",
text: msg.content
}]
}));
}

// 构建Scira请求负载
function buildSciraPayload(messages: Message[], model = DEFAULT_MODEL): SciraPayload {
const formattedMessages = formatMessagesForScira(messages);
return {
id: FIXED_CHAT_ID,
messages: formattedMessages,
selectedModel: model,
mcpServers: [],
chatId: FIXED_CHAT_ID,
userId: FIXED_USER_ID
};
}

// 处理模型列表请求
async function handleModelsRequest(): Promise<Response> {
const response = {
object: "list",
data: AVAILABLE_MODELS,
};
return new Response(JSON.stringify(response), {
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
},
});
}

// 处理聊天补全请求
async function handleChatCompletionsRequest(req: Request): Promise<Response> {
const requestData = await req.json();
const { messages, model = DEFAULT_MODEL, stream = false } = requestData;

const sciraPayload = buildSciraPayload(messages, model);
const response = await fetch(API_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:137.0) Gecko/20100101 Firefox/137.0",
"Accept": "*/*",
"Referer": `https://mcp.scira.ai/chat/${FIXED_CHAT_ID}`,
"Origin": "https://mcp.scira.ai",
},
body: JSON.stringify(sciraPayload),
});

if (stream) {
return handleStreamResponse(response, model);
} else {
return handleRegularResponse(response, model);
}
}

// 处理流式响应
async function handleStreamResponse(response: Response, model: string): Promise<Response> {
const reader = response.body!.getReader();
const encoder = new TextEncoder();
const decoder = new TextDecoder();

const id = `chatcmpl-${Date.now().toString(36)}${Math.random().toString(36).substring(2, 10)}`;
const createdTime = Math.floor(Date.now() / 1000);
const systemFingerprint = `fp_${Math.random().toString(36).substring(2, 12)}`;

const stream = new ReadableStream({
async start(controller) {
// 发送流式头部
const headerEvent = {
id: id,
object: "chat.completion.chunk",
created: createdTime,
model: model,
system_fingerprint: systemFingerprint,
choices: [{
index: 0,
delta: { role: "assistant" },
logprobs: null,
finish_reason: null
}]
};
controller.enqueue(encoder.encode(`data: ${JSON.stringify(headerEvent)}\n\n`));

try {
let buffer = "";

while (true) {
const { done, value } = await reader.read();
if (done) break;

// 解码当前数据块并添加到缓冲区
buffer += decoder.decode(value, { stream: true });

// 处理完整的行
const lines = buffer.split('\n');
// 保留最后一个可能不完整的行
buffer = lines.pop() || "";

// 处理并立即发送每一行
for (const line of lines) {
if (!line.trim()) continue;

if (line.startsWith('g:')) {
// 对于g开头的行,输出reasoning_content
let content = line.slice(2).replace(/^"/, "").replace(/"$/, "");
content = content.replace(/\\n/g, "\n");

const event = {
id: id,
object: "chat.completion.chunk",
created: createdTime,
model: model,
system_fingerprint: systemFingerprint,
choices: [{
index: 0,
delta: { reasoning_content: content },
logprobs: null,
finish_reason: null
}]
};
controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
} else if (line.startsWith('0:')) {
// 对于0开头的行,输出content
let content = line.slice(2).replace(/^"/, "").replace(/"$/, "");
content = content.replace(/\\n/g, "\n");

const event = {
id: id,
object: "chat.completion.chunk",
created: createdTime,
model: model,
system_fingerprint: systemFingerprint,
choices: [{
index: 0,
delta: { content: content },
logprobs: null,
finish_reason: null
}]
};
controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
} else if (line.startsWith('e:')) {
// 完成消息
try {
const finishData = JSON.parse(line.slice(2));
const event = {
id: id,
object: "chat.completion.chunk",
created: createdTime,
model: model,
system_fingerprint: systemFingerprint,
choices: [{
index: 0,
delta: {},
logprobs: null,
finish_reason: finishData.finishReason || "stop"
}]
};
controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
} catch (error) {
console.error("Error parsing finish data:", error);
}
}
}
}

// 处理缓冲区中剩余的内容(如果有的话)
if (buffer.trim()) {
const line = buffer.trim();
if (line.startsWith('g:')) {
let content = line.slice(2).replace(/^"/, "").replace(/"$/, "");
content = content.replace(/\\n/g, "\n");

const event = {
id: id,
object: "chat.completion.chunk",
created: createdTime,
model: model,
system_fingerprint: systemFingerprint,
choices: [{
index: 0,
delta: { reasoning_content: content },
logprobs: null,
finish_reason: null
}]
};
controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
} else if (line.startsWith('0:')) {
let content = line.slice(2).replace(/^"/, "").replace(/"$/, "");
content = content.replace(/\\n/g, "\n");

const event = {
id: id,
object: "chat.completion.chunk",
created: createdTime,
model: model,
system_fingerprint: systemFingerprint,
choices: [{
index: 0,
delta: { content: content },
logprobs: null,
finish_reason: null
}]
};
controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
}
}
} catch (error) {
console.error("Stream error:", error);
} finally {
// 确保发送 "data: [DONE]"
controller.enqueue(encoder.encode("data: [DONE]\n\n"));
controller.close();
}
}
});

return new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"Access-Control-Allow-Origin": "*",
},
});
}

// 处理非流式响应
async function handleRegularResponse(response: Response, model: string): Promise<Response> {
const text = await response.text();
const lines = text.split('\n');

let content = "";
let reasoning_content = "";
let usage = { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };
let finish_reason = "stop";

for (const line of lines) {
if (!line.trim()) continue;

if (line.startsWith('0:')) {
// 常规内容 - 处理转义的换行符
let lineContent = line.slice(2).replace(/^"/, "").replace(/"$/, "");
lineContent = lineContent.replace(/\\n/g, "\n");
content += lineContent;
} else if (line.startsWith('g:')) {
// 推理内容 - 处理转义的换行符
let lineContent = line.slice(2).replace(/^"/, "").replace(/"$/, "");
lineContent = lineContent.replace(/\\n/g, "\n");
reasoning_content += lineContent;
} else if (line.startsWith('e:')) {
try {
const finishData = JSON.parse(line.slice(2));
if (finishData.finishReason) {
finish_reason = finishData.finishReason;
}
} catch (error) {
console.error("Error parsing finish data:", error);
}
} else if (line.startsWith('d:')) {
try {
const finishData = JSON.parse(line.slice(2));
if (finishData.usage) {
usage.prompt_tokens = finishData.usage.promptTokens || 0;
usage.completion_tokens = finishData.usage.completionTokens || 0;
usage.total_tokens = usage.prompt_tokens + usage.completion_tokens;
}
} catch (error) {
console.error("Error parsing usage data:", error);
}
}
}

const systemFingerprint = `fp_${Math.random().toString(36).substring(2, 12)}`;
const id = `chatcmpl-${Date.now().toString(36)}${Math.random().toString(36).substring(2, 10)}`;

const openAIResponse = {
id: id,
object: "chat.completion",
created: Math.floor(Date.now() / 1000),
model: model,
system_fingerprint: systemFingerprint,
choices: [{
index: 0,
message: {
role: "assistant",
content: content
},
logprobs: null,
finish_reason: finish_reason
}],
usage: usage
};

// 如果存在推理内容,添加到消息中
if (reasoning_content.trim()) {
openAIResponse.choices[0].message.reasoning_content = reasoning_content;
}

return new Response(JSON.stringify(openAIResponse), {
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
},
});
}

// 主请求处理函数
async function handler(req: Request): Promise<Response> {
const url = new URL(req.url);

// 设置CORS头
const headers = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
};

// 处理OPTIONS请求(CORS预检)
if (req.method === "OPTIONS") {
return new Response(null, {
headers,
status: 204
});
}

try {
// 处理模型列表接口
if (url.pathname === "/v1/models") {
return handleModelsRequest();
}

// 处理聊天补全接口
if (url.pathname === "/v1/chat/completions") {
return handleChatCompletionsRequest(req);
}

// 未找到的路由
return new Response(
JSON.stringify({ error: "Not found" }), {
status: 404,
headers: {
"Content-Type": "application/json",
...headers
},
}
);
} catch (error) {
console.error("Error processing request:", error);
return new Response(
JSON.stringify({ error: error.message || "Internal server error" }),
{
status: 500,
headers: {
"Content-Type": "application/json",
...headers
},
}
);
}
}

// 启动服务器
console.log(`Starting server on port ${PORT}...`);
serve(handler, { port: PORT });

在对应位置找到 userId chatId 并修改对应参数。
2api5.png

和前文相同的是:

1、打开deno的链接会返回json。

2、通过api调用可以搜索到四个模型(注意:cloud 3.7的模型名字为claude-3-7-sonnet)

2api6.png
可以畅用cloud 3.7和gemini2.5
2api7.png

三、scira2api

https://assistant.on.adaptive.ai/
正在维护
当前版本 0.1.0 Alpha
Demo https://skykchatgpt4o.deno.dev
语言 TypeScript
框架 Deno

Models

  • gpt-4o

Features

  • 需要鉴权,所以无法直接粘贴代码,请自行手动部署
  • Chatgpt-4o Omni全能多模态大模型直接自由了
  • 直接点我的demo链接是无效的,自行部署

1、部署

前往Deno创建XXX.ts

scira2api.ts
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
import { serve } from "https://deno.land/std@0.220.1/http/server.ts";

// --- 配置常量 ---
const AUTH_KEY = Deno.env.get("AUTH_KEY") ?? "default_api_key_value"; //API密钥在Environment Variables中添加,否则默认是default_api_key_value
const TARGET_URL = 'https://assistant.on.adaptive.ai/api/sendMessage';
const PROXY_MODEL_NAME = "gpt-4o"; // 代理服务返回的模型名称


const TARGET_HEADERS = {
'content-type': 'application/json',
'x-channel-id': "0"
};

// --- 辅助函数:创建 SSE 数据块 ---
function createSSEChunk(id: string, model: string, content: string | null, role: string | null, finish_reason: string | null): string {
const now = Math.floor(Date.now() / 1000);
const chunk: any = {
id: id,
object: "chat.completion.chunk",
created: now,
model: model,
choices: [
{
index: 0,
delta: {},
finish_reason: finish_reason,
logprobs: null,
}
],
// system_fingerprint: null, // 可选
};
if (role) {
chunk.choices[0].delta.role = role;
}
if (content) {
chunk.choices[0].delta.content = content;
}
// 如果 delta 为空且有 finish_reason,确保 delta 是空对象
if (!role && !content && finish_reason) {
chunk.choices[0].delta = {};
}

return `data: ${JSON.stringify(chunk)}\n\n`;
}

/**
* 向 Adaptive AI 发送创建新聊天的请求。
* 成功时返回新聊天的 ID (字符串)。
* 如果在过程中发生任何错误,则捕获错误并返500。
*
* @returns {Promise<string | 500>} 返回成功创建的聊天的 ID (string),或在失败时返回 500。
*/
async function createChatAndGetId(): Promise<string> {
const url = 'https://assistant.on.adaptive.ai/api/createChat';
// 定义请求头 (省略了 cookie 和 priority)
const headers = {
'content-type': 'application/json',
};
// 构建请求体,使用当前时间戳作为请求 ID
const payload = {
json: {
jsonrpc: "2.0",
id: Date.now(), // 使用动态 ID
method: "createChat",
params: []
}
};
console.log("正在发送创建聊天请求...");
try {
const response = await fetch(url, {
method: 'POST',
headers: headers,
body: JSON.stringify(payload) // 将 payload 对象转换为 JSON 字符串
});
// 检查 HTTP 响应状态码是否表示成功
if (!response.ok) {
let errorBody = "无法读取响应体";
try {
errorBody = await response.text(); // 尝试读取错误响应体
} catch (readError) {
console.warn("读取错误响应体失败:", readError);
}
throw new Error(`创建聊天请求失败,HTTP 状态码: ${response.status}. 响应: ${errorBody}`);
}
// 解析 JSON 响应体
let responseData: any;
try {
responseData = await response.json();
} catch (parseError) {
// 如果响应不是有效的 JSON,则抛出错误
console.error("解析创建聊天响应 JSON 时出错:", parseError);
throw new Error(`无法将响应解析为 JSON: ${parseError.message}`);
}
// 提取并验证 ID
// ID 预期在 responseData.json.result.id
// 使用可选链操作符 (?.) 来安全地访问嵌套属性,防止因中间属性不存在而报错
const chatId = responseData?.json?.result?.id;
// 检查提取到的 ID 是否是一个有效的、非空的字符串
if (typeof chatId === 'string' && chatId.length > 0) {
console.log(`成功创建聊天,获取到 ID: ${chatId}`);
return chatId; // 返回提取到的 ID
} else {
// 如果 ID 不存在或格式不正确,则抛出错误
console.error("从响应中未能提取有效的聊天 ID。响应数据:", JSON.stringify(responseData));
throw new Error("创建聊天的响应格式无效或缺少 'json.result.id' 字段。");
}
} catch (error) {
// 捕获 try 块中抛出的任何错误,或 fetch 本身的网络错误
const errorMessage = error instanceof Error ? error.message : String(error);
console.error("执行 createChatAndGetId 时发生错误:", errorMessage); // 记录详细错误信息
// 创建并返回一个 Response 对象
// 状态码为 500 (Internal Server Error)
// 响应体为 JSON 格式,包含错误信息
return new Response(
JSON.stringify({ error: `创建聊天会话失败: ${errorMessage}` }), // 将错误信息包装在 JSON 对象中
{
status: 500, // 设置 HTTP 状态码为 500
headers: {
"Content-Type": "application/json", // 设置响应内容类型为 JSON
"Access-Control-Allow-Origin": "*" // 如果需要跨域,添加此头
}
}
);
}

}

// --- 主处理函数 ---
async function handler(req: Request): Promise<Response> {
const url = new URL(req.url);

// --- CORS 预检请求处理 ---
if (req.method === "OPTIONS") {
return new Response(null, {
status: 204,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Max-Age": "86400",
},
});
}


// 模型列表接口
if (url.pathname === "/v1/models" && req.method === "GET") {
return new Response(
JSON.stringify({
object: "list",
data: [
{
id: "gpt-4o",
object: "model",
created: 0,
owned_by: "unlimitedai",
permission: [{
id: "modelperm-gpt-4o",
object: "model_permission",
created: 0,
allow_create_engine: false,
allow_sampling: true,
allow_logprobs: false,
allow_search_indices: false,
allow_view: true,
allow_fine_tuning: false,
organization: "*",
group: null,
is_blocking: false,
}],
root: "gpt-4o",
parent: null,
},
],
}),
{
status: 200,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
}
);
}

// --- 路径和方法检查 ---
if (url.pathname !== "/v1/chat/completions" || req.method !== "POST") {
return new Response(JSON.stringify({ error: "Not Found or Method Not Allowed" }), {
status: 404,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
});
}
// --- 添加认证检查 ---
const authHeader = req.headers.get("Authorization");
let providedKey = "";
// 检查 Authorization header 是否存在且格式正确 (Bearer <key>)
if (!authHeader || !authHeader.toLowerCase().startsWith("bearer ")) {
console.warn(`认证失败: 缺少或格式错误的 Authorization header`);
return new Response(JSON.stringify({
error: {
message: "Unauthorized: Missing or invalid Authorization header. Use 'Bearer <YOUR_API_KEY>' format.",
type: "invalid_request_error",
param: null,
code: "missing_or_invalid_header"
}
}), {
status: 401, // Unauthorized
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"WWW-Authenticate": 'Bearer realm="API Access"'
}
});
}
// 提取 key 部分
providedKey = authHeader.substring(7); // "Bearer ".length is 7
console.log("providedKey:" + providedKey);
// 直接比较提供的 key 和硬编码的 key
if (providedKey !== AUTH_KEY) {
console.warn(`认证失败: 无效的 API Key 提供`);
return new Response(JSON.stringify({
error: {
message: "Unauthorized: Invalid API Key provided.",
type: "invalid_request_error",
param: null,
code: "inAUTH_KEY"
}
}), {
status: 401, // Unauthorized
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"WWW-Authenticate": 'Bearer realm="API Access"'
}
});
}

// --- 处理 POST 请求 ---
try {

// 1. 解析入站请求体
let requestBody: any;
try {
requestBody = await req.json();
console.log(requestBody)
} catch (e) {
console.error("Failed to parse request JSON:", e);
return new Response(JSON.stringify({ error: "Invalid JSON in request body" }), {
status: 400, headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" },
});
}

// 2. 检查是否请求流式响应
const isStream = requestBody.stream === true;

// 3. 提取用户输入的内容 - 将 messages 数组转换为字符串
let userContent: string | undefined;
if (Array.isArray(requestBody.messages) && requestBody.messages.length > 0) {
try {
// 直接将整个 messages 数组转换为 JSON 字符串
userContent = JSON.stringify(requestBody.messages);
} catch (e) {
console.error("Failed to stringify 'messages' array:", e);
// 如果 JSON.stringify 失败 (虽然对数组不太可能,但以防万一)
return new Response(JSON.stringify({ error: "Failed to process 'messages' array." }), {
status: 400, headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" },
});
}
}
// 检查 userContent 是否成功生成
// 如果 requestBody.messages 不存在、不是数组、为空,或者转换出错,userContent 会是 undefined
if (!userContent) {
console.error("Request body must contain a non-empty 'messages' array.");
return new Response(JSON.stringify({ error: "Request body must contain a non-empty 'messages' array." }), {
status: 400, headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" },
});
}

// 现在 userContent 包含了整个对话历史的字符串表示
console.log("Formatted user content:", userContent); // 可以取消注释来调试输出

const CHAT_ID = await createChatAndGetId();//获取新的聊天ID


// 4. 构建目标 API Payload
const payload = {
json: {
jsonrpc: "2.0", id: Date.now(), method: "sendMessage",
params: [{ chatId: CHAT_ID, content: userContent, fileId: null, fileIds: [] }]
},
meta: { values: { "params.0.fileId": ["undefined"] } }
};

// 5. 发送请求到目标 API (无论是否流式,都需要先获取完整响应)
console.log("Forwarding request to:", TARGET_URL);
const targetResponse = await fetch(TARGET_URL, {
method: 'POST', headers: TARGET_HEADERS, body: JSON.stringify(payload),
});

// 6. 处理目标 API 的响应
if (!targetResponse.ok) {
const errorBody = await targetResponse.text();
console.error(`Target API Error (${targetResponse.status}):`, errorBody);
// 即使是流式请求失败,也返回 JSON 错误
return new Response(JSON.stringify({ error: `Upstream API request failed with status ${targetResponse.status}`, details: errorBody }), {
status: 502, headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" },
});
}

// 7. 解析目标 API 的 JSON 响应
let targetData: any;
try {
targetData = await targetResponse.json();
} catch (e) {
console.error("Failed to parse target API response JSON:", e);
// 即使是流式请求失败,也返回 JSON 错误
return new Response(JSON.stringify({ error: "Failed to parse upstream API response" }), {
status: 500, headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" },
});
}

// 8. 从目标响应中提取内容
const assistantContent = targetData?.json?.result?.content;
if (typeof assistantContent !== 'string') {
console.error("Could not extract 'content' from target API response:", JSON.stringify(targetData));
// 即使是流式请求失败,也返回 JSON 错误
return new Response(JSON.stringify({ error: "Invalid response format from upstream API" }), {
status: 500, headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" },
});
}

// 9. 根据 isStream 决定返回格式
const chatCompletionId = `chatcmpl-${crypto.randomUUID()}`; // 为本次交互生成唯一 ID
const modelName = requestBody.model || PROXY_MODEL_NAME; // 确定模型名称

if (isStream) {
// --- 返回模拟的流式响应 ---
console.log("Simulating stream response...");
const encoder = new TextEncoder();
const stream = new ReadableStream({
async start(controller) {
try {
// 模拟发送块
// 块 1: 发送角色信息
controller.enqueue(encoder.encode(
createSSEChunk(chatCompletionId, modelName, null, "assistant", null)
));
await new Promise(resolve => setTimeout(resolve, 10)); // 短暂延迟,模拟处理

// 块 2: 发送完整内容
controller.enqueue(encoder.encode(
createSSEChunk(chatCompletionId, modelName, assistantContent, null, null)
));
await new Promise(resolve => setTimeout(resolve, 10)); // 短暂延迟

// 块 3: 发送结束信号
controller.enqueue(encoder.encode(
createSSEChunk(chatCompletionId, modelName, null, null, "stop")
));

// 发送 [DONE] 标记
controller.enqueue(encoder.encode("data: [DONE]\n\n"));

// 关闭流
controller.close();
} catch (error) {
console.error("Error during stream simulation:", error);
controller.error(error); // 通知流出错了
}
}
});

return new Response(stream, {
status: 200,
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive', // 建议 SSE 使用
'Access-Control-Allow-Origin': '*'
},
});

} else {
// --- 返回完整的 JSON 响应 ---
console.log("Returning non-stream response.");
const finalResponse = {
id: chatCompletionId,
object: "chat.completion",
created: Math.floor(Date.now() / 1000),
model: modelName,
choices: [
{
index: 0,
message: {
role: "assistant",
content: assistantContent,
},
finish_reason: "stop",
logprobs: null,
}
],
usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },
};

return new Response(JSON.stringify(finalResponse), {
status: 200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
});
}

} catch (error) {
// --- 全局错误处理 ---
console.error("Unhandled error in handler:", error);
// 即使请求流式,也返回 JSON 错误
return new Response(JSON.stringify({ error: "Internal Server Error" }), {
status: 500,
headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" },
});
}
}


serve(handler);

站点没有检测,所以我自己加了鉴权防止2to2。
生图能力
2api8.png
视频创造
2api9.png
强大的模型能力。