Spaces:
Runtime error
Runtime error
Update main.ts
Browse files
main.ts
CHANGED
|
@@ -1,925 +1,629 @@
|
|
| 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 |
-
cost savings directly attributable to the Software.
|
| 27 |
-
* Use in training or educational programs for which a fee is charged.
|
| 28 |
-
* Use to support any for-profit entity, regardless of whether the software
|
| 29 |
-
itself is sold.
|
| 30 |
-
* Reselling, or sublicensing this software.
|
| 31 |
-
If you require a commercial license, please contact Neuroplexus at isneuroplexus@duck.com.
|
| 32 |
-
|
| 33 |
-
2. Attribution and Original Author/Project Notice:
|
| 34 |
-
|
| 35 |
-
Any use, distribution, or modification of the Software (in whole or in part)
|
| 36 |
-
must prominently include the following:
|
| 37 |
-
* The original copyright notice: `Copyright (c) 2025 Neuroplexus`
|
| 38 |
-
* A clear and unambiguous statement identifying Neuroplexus as the original
|
| 39 |
-
author of the Software.
|
| 40 |
-
* A link or reference to the original project location (e.g., a URL to a
|
| 41 |
-
repository, if applicable). For example: "Based on the Neuroplexus
|
| 42 |
-
HuanyuanInterface project, available at https://linux.do/t/topic/507324.
|
| 43 |
-
|
| 44 |
-
3. Share-Alike (Derivative Works):
|
| 45 |
-
|
| 46 |
-
If you modify the Software, any distribution of the modified version (the
|
| 47 |
-
"Derivative Work") must be licensed under the *same* terms and conditions as
|
| 48 |
-
this License (Neuroplexus Non-Commercial Share-Alike License). This means:
|
| 49 |
-
* The Derivative Work must also be restricted to non-commercial use.
|
| 50 |
-
* The Derivative Work must include the attribution requirements outlined
|
| 51 |
-
in Section 2.
|
| 52 |
-
* The source code of the Derivative Work must be made available under
|
| 53 |
-
this same License.
|
| 54 |
-
|
| 55 |
-
4. Modification Notices:
|
| 56 |
-
|
| 57 |
-
Any Derivative Work must include prominent notices stating that you have
|
| 58 |
-
modified the Software, and the date and nature of the changes made. These
|
| 59 |
-
notices must be placed:
|
| 60 |
-
* In the source code files that have been modified.
|
| 61 |
-
* In a separate `CHANGELOG` or `MODIFICATIONS` file included with the
|
| 62 |
-
Derivative Work's distribution. This file should clearly list all
|
| 63 |
-
modifications made to the original Software.
|
| 64 |
-
|
| 65 |
-
5. No Endorsement:
|
| 66 |
-
|
| 67 |
-
The names of Neuroplexus or its contributors may not be used to endorse or
|
| 68 |
-
promote products derived from this Software without specific prior written
|
| 69 |
-
permission.
|
| 70 |
-
|
| 71 |
-
6. Termination:
|
| 72 |
-
|
| 73 |
-
This License automatically terminates if you violate any of its terms and
|
| 74 |
-
conditions. Upon termination, you must cease all use, distribution, and
|
| 75 |
-
modification of the Software and destroy all copies in your possession.
|
| 76 |
-
|
| 77 |
-
7. Severability:
|
| 78 |
-
|
| 79 |
-
If any provision of this License is held to be invalid or unenforceable, the
|
| 80 |
-
remaining provisions shall remain in full force and effect.
|
| 81 |
-
|
| 82 |
-
8. Governing Law:
|
| 83 |
-
|
| 84 |
-
This License shall be governed by and construed in accordance with the laws
|
| 85 |
-
of New South Wales, Australia, without
|
| 86 |
-
regard to its conflict of law principles.
|
| 87 |
-
|
| 88 |
-
9. Entire Agreement:
|
| 89 |
-
|
| 90 |
-
This license constitutes the entire agreement with respect to the software.
|
| 91 |
-
Neuroplexus is not bound by any additional provisions that may appear in any
|
| 92 |
-
communication from you.
|
| 93 |
-
*/
|
| 94 |
-
|
| 95 |
-
import { Application, Router, Context } from "https://deno.land/x/oak@v12.6.1/mod.ts";
|
| 96 |
-
import { Buffer } from "https://deno.land/std@0.152.0/io/buffer.ts"; // Not used, can be removed
|
| 97 |
-
|
| 98 |
-
const HUNYUAN_API_URL = "http://llm.hunyuan.tencent.com/aide/api/v2/triton_image/demo_text_chat/"; // Consider making this configurable
|
| 99 |
-
const DEFAULT_STAFFNAME = "staryxzhang"; // Consider making this configurable
|
| 100 |
-
const DEFAULT_WSID = "10697"; // Consider making this configurable
|
| 101 |
-
const API_KEY = "7auGXNATFSKl7dc"; // Consider loading this from an environment variable or config file
|
| 102 |
-
|
| 103 |
-
interface HunyuanMessage {
|
| 104 |
-
role: string;
|
| 105 |
-
content: string;
|
| 106 |
-
reasoning_content?: string;
|
| 107 |
-
}
|
| 108 |
-
|
| 109 |
-
interface HunyuanRequest {
|
| 110 |
-
stream: boolean;
|
| 111 |
-
model: string;
|
| 112 |
-
query_id: string;
|
| 113 |
-
messages: HunyuanMessage[];
|
| 114 |
-
stream_moderation: boolean;
|
| 115 |
-
enable_enhancement: boolean;
|
| 116 |
-
}
|
| 117 |
-
|
| 118 |
-
// These interfaces can be combined for better readability
|
| 119 |
-
interface OpenAIChoiceBase {
|
| 120 |
-
index: number;
|
| 121 |
-
finish_reason: string | null;
|
| 122 |
-
}
|
| 123 |
-
|
| 124 |
-
interface OpenAIChoiceDelta extends OpenAIChoiceBase {
|
| 125 |
-
delta: {
|
| 126 |
-
role?: string;
|
| 127 |
-
content?: string;
|
| 128 |
-
reasoning_content?: string;
|
| 129 |
-
};
|
| 130 |
-
}
|
| 131 |
-
|
| 132 |
-
interface OpenAIChoiceNonStream extends OpenAIChoiceBase {
|
| 133 |
-
message: {
|
| 134 |
-
role: string;
|
| 135 |
-
content: string;
|
| 136 |
-
reasoning_content?: string;
|
| 137 |
-
};
|
| 138 |
-
}
|
| 139 |
-
|
| 140 |
-
interface OpenAIStreamResponse {
|
| 141 |
-
id: string;
|
| 142 |
-
object: string;
|
| 143 |
-
created: number;
|
| 144 |
-
model: string;
|
| 145 |
-
system_fingerprint: string;
|
| 146 |
-
choices: OpenAIChoiceDelta[];
|
| 147 |
-
note?: string; // Rarely used, consider removing if not needed
|
| 148 |
-
}
|
| 149 |
-
|
| 150 |
-
interface OpenAIResponseNonStream {
|
| 151 |
-
id: string;
|
| 152 |
-
object: string;
|
| 153 |
-
created: number;
|
| 154 |
-
model: string;
|
| 155 |
-
choices: OpenAIChoiceNonStream[];
|
| 156 |
-
usage?: { // Placeholder for now
|
| 157 |
-
prompt_tokens: number;
|
| 158 |
-
completion_tokens: number;
|
| 159 |
-
total_tokens: number;
|
| 160 |
-
};
|
| 161 |
-
}
|
| 162 |
-
|
| 163 |
-
interface OpenAIModel {
|
| 164 |
-
id: string;
|
| 165 |
-
object: string;
|
| 166 |
-
created: number;
|
| 167 |
-
owned_by: string;
|
| 168 |
-
}
|
| 169 |
-
|
| 170 |
-
interface OpenAIModelsResponse {
|
| 171 |
-
object: string;
|
| 172 |
-
data: OpenAIModel[];
|
| 173 |
-
}
|
| 174 |
-
|
| 175 |
-
// Helper function to get Hunyuan model name from OpenAI model name
|
| 176 |
-
function getHunyuanModelName(openaiModelName: string): string {
|
| 177 |
-
switch (openaiModelName) {
|
| 178 |
-
case "hunyuan-turbos-latest":
|
| 179 |
-
return "hunyuan-turbos-latest";
|
| 180 |
-
case "hunyuan-t1-latest": // Fallthrough is intentional
|
| 181 |
-
default:
|
| 182 |
-
return "hunyuan-t1-latest";
|
| 183 |
-
}
|
| 184 |
-
}
|
| 185 |
-
|
| 186 |
-
async function hunyuanToOpenAIStream(
|
| 187 |
-
hunyuanResponse: Response,
|
| 188 |
-
openaiModelName: string,
|
| 189 |
-
): Promise<ReadableStream<string>> {
|
| 190 |
-
const decoder = new TextDecoder("utf-8");
|
| 191 |
-
let buffer = "";
|
| 192 |
-
|
| 193 |
-
return new ReadableStream<string>({
|
| 194 |
-
async start(controller) {
|
| 195 |
-
if (!hunyuanResponse.body) {
|
| 196 |
-
controller.close();
|
| 197 |
-
return;
|
| 198 |
}
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
const jsonStr = chunk.substring(5).trim();
|
| 215 |
-
if (jsonStr === "[DONE]") {
|
| 216 |
-
controller.enqueue(`data: [DONE]\n\n`);
|
| 217 |
-
continue;
|
| 218 |
-
}
|
| 219 |
-
try {
|
| 220 |
-
const hunyuanData = JSON.parse(jsonStr);
|
| 221 |
-
const openaiData: OpenAIStreamResponse = {
|
| 222 |
-
id: hunyuanData.id,
|
| 223 |
-
object: "chat.completion.chunk",
|
| 224 |
-
created: hunyuanData.created,
|
| 225 |
-
model: openaiModelName,
|
| 226 |
-
system_fingerprint: hunyuanData.system_fingerprint,
|
| 227 |
-
choices: hunyuanData.choices.map((choice): OpenAIChoiceDelta => ({
|
| 228 |
-
delta: {
|
| 229 |
-
role: choice.delta.role,
|
| 230 |
-
content: choice.delta.content,
|
| 231 |
-
reasoning_content: choice.delta.reasoning_content,
|
| 232 |
-
},
|
| 233 |
-
index: choice.index,
|
| 234 |
-
finish_reason: choice.finish_reason,
|
| 235 |
-
})),
|
| 236 |
-
};
|
| 237 |
-
controller.enqueue(`data: ${JSON.stringify(openaiData)}\n\n`);
|
| 238 |
-
} catch (error) {
|
| 239 |
-
console.error("Error parsing stream chunk:", error, jsonStr);
|
| 240 |
-
}
|
| 241 |
-
}
|
| 242 |
-
}
|
| 243 |
-
}
|
| 244 |
-
} finally {
|
| 245 |
-
reader.releaseLock();
|
| 246 |
-
controller.close();
|
| 247 |
}
|
| 248 |
},
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
if (!hunyuanResponse.body) {
|
| 264 |
-
throw new Error("Hunyuan response body is empty.");
|
| 265 |
-
}
|
| 266 |
-
const reader = hunyuanResponse.body.getReader();
|
| 267 |
-
|
| 268 |
-
try {
|
| 269 |
-
while (true) {
|
| 270 |
-
const { done, value } = await reader.read();
|
| 271 |
-
if (done) {
|
| 272 |
-
break;
|
| 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 |
-
} finally {
|
| 327 |
-
reader.releaseLock();
|
| 328 |
}
|
| 329 |
|
| 330 |
-
|
| 331 |
-
|
|
|
|
| 332 |
}
|
| 333 |
-
|
| 334 |
-
const openaiResponse: OpenAIResponseNonStream = {
|
| 335 |
-
id: finalId,
|
| 336 |
-
object: "chat.completion",
|
| 337 |
-
created: finalCreated,
|
| 338 |
-
model: finalModel,
|
| 339 |
-
choices: allChoices,
|
| 340 |
-
usage: { // Still placeholder, see notes below
|
| 341 |
-
prompt_tokens: 0,
|
| 342 |
-
completion_tokens: 0,
|
| 343 |
-
total_tokens: 0,
|
| 344 |
-
},
|
| 345 |
-
};
|
| 346 |
-
return openaiResponse;
|
| 347 |
}
|
| 348 |
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
return;
|
| 356 |
-
}
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
const body = await ctx.request.body({ type: "json" }).value;
|
| 360 |
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
ctx.response.body = { error: "Invalid request body: 'messages' array is required." };
|
| 364 |
-
return;
|
| 365 |
-
}
|
| 366 |
|
| 367 |
-
const
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
reasoning_content: msg.reasoning_content, // Pass through reasoning_content
|
| 375 |
-
}));
|
| 376 |
-
|
| 377 |
-
const hunyuanRequest: HunyuanRequest = {
|
| 378 |
-
stream: true, // Always stream to Hunyuan, then handle streaming/non-streaming for OpenAI
|
| 379 |
-
model: hunyuanModel,
|
| 380 |
-
query_id: crypto.randomUUID().replaceAll("-", ""),
|
| 381 |
-
messages: hunyuanMessages,
|
| 382 |
-
stream_moderation: true,
|
| 383 |
-
enable_enhancement: false,
|
| 384 |
};
|
| 385 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 386 |
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:136.0) Gecko/20100101 Firefox/136.0", // Consider making this configurable
|
| 392 |
-
"Accept": "*/*",
|
| 393 |
-
"Accept-Language": "en-US,en;q=0.5", // Consider making this configurable
|
| 394 |
-
"Accept-Encoding": "gzip, deflate, br, zstd",
|
| 395 |
-
"Referer": "https://llm.hunyuan.tencent.com/",
|
| 396 |
-
"Content-Type": "application/json",
|
| 397 |
-
"model": hunyuanModel, // Use the determined Hunyuan model
|
| 398 |
-
"polaris": "stream-server-online-sbs-10697",
|
| 399 |
-
"Authorization": `Bearer ${apiKey}`,
|
| 400 |
-
"Wsid": DEFAULT_WSID,
|
| 401 |
-
"staffname": DEFAULT_STAFFNAME,
|
| 402 |
-
"Origin": "https://llm.hunyuan.tencent.com",
|
| 403 |
-
"DNT": "1",
|
| 404 |
-
"Sec-GPC": "1",
|
| 405 |
-
"Connection": "keep-alive",
|
| 406 |
-
"Sec-Fetch-Dest": "empty",
|
| 407 |
-
"Sec-Fetch-Mode": "cors",
|
| 408 |
-
"Sec-Fetch-Site": "same-origin",
|
| 409 |
-
"Priority": "u=0",
|
| 410 |
-
"Pragma": "no-cache",
|
| 411 |
-
"Cache-Control": "no-cache",
|
| 412 |
-
"TE": "trailers",
|
| 413 |
-
},
|
| 414 |
-
body: JSON.stringify(hunyuanRequest),
|
| 415 |
-
});
|
| 416 |
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
ctx.response.status = hunyuanResponse.status;
|
| 421 |
-
ctx.response.body = { error: `Hunyuan API error: ${hunyuanResponse.status} - ${errorText}` };
|
| 422 |
-
return;
|
| 423 |
}
|
|
|
|
|
|
|
|
|
|
| 424 |
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
ctx.response.type = "application/json";
|
| 433 |
}
|
| 434 |
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
ctx.response.status = 500;
|
| 438 |
-
ctx.response.body = { error: "Internal Server Error" };
|
| 439 |
}
|
| 440 |
-
}
|
| 441 |
|
| 442 |
-
async
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 451 |
},
|
| 452 |
-
{
|
| 453 |
-
id:
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
}
|
| 463 |
-
|
| 464 |
-
const sharedStyles = `
|
| 465 |
-
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
|
| 466 |
-
|
| 467 |
-
:root {
|
| 468 |
-
--background: #f0f2f5;
|
| 469 |
-
--foreground: #2e3440;
|
| 470 |
-
--primary: #5e81ac;
|
| 471 |
-
--primary-foreground: #eceff4;
|
| 472 |
-
--card: #ffffff;
|
| 473 |
-
--card-foreground: #2e3440;
|
| 474 |
-
--muted: #d8dee9;
|
| 475 |
-
--muted-foreground: #4c566a;
|
| 476 |
-
--border: #d8dee9;
|
| 477 |
-
--radius: 8px;
|
| 478 |
-
--header-bg: #3b4252;
|
| 479 |
-
--header-fg: #eceff4;
|
| 480 |
-
--link-color: #81a1c1;
|
| 481 |
-
}
|
| 482 |
-
|
| 483 |
-
* { margin: 0; padding: 0; box-sizing: border-box; }
|
| 484 |
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
display: flex;
|
| 490 |
-
flex-direction: column;
|
| 491 |
-
min-height: 100vh;
|
| 492 |
-
line-height: 1.6;
|
| 493 |
-
}
|
| 494 |
|
| 495 |
-
|
| 496 |
-
background-color: var(--header-bg);
|
| 497 |
-
color: var(--header-fg);
|
| 498 |
-
padding: 1rem 0;
|
| 499 |
-
width: 100%;
|
| 500 |
-
text-align: center;
|
| 501 |
-
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
| 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 |
-
color: var(--foreground);
|
| 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 |
-
border: none;
|
| 615 |
-
}
|
| 616 |
|
| 617 |
-
.
|
| 618 |
-
|
| 619 |
-
|
|
|
|
| 620 |
|
| 621 |
-
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
color: var(--muted-foreground);
|
| 626 |
-
border-top: 1px solid var(--border);
|
| 627 |
-
width: 100%;
|
| 628 |
-
}
|
| 629 |
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
const homePage = `
|
| 652 |
-
<!DOCTYPE html>
|
| 653 |
-
<html lang="en">
|
| 654 |
-
<head>
|
| 655 |
-
<meta charset="UTF-8">
|
| 656 |
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 657 |
-
<title>Hunyuan OpenAI Proxy</title>
|
| 658 |
-
<style>${sharedStyles}</style>
|
| 659 |
-
</head>
|
| 660 |
-
<body>
|
| 661 |
-
${header}
|
| 662 |
-
<div class="container">
|
| 663 |
-
<h1>Hunyuan OpenAI Proxy</h1>
|
| 664 |
-
<div class="card">
|
| 665 |
-
<h2>Welcome</h2>
|
| 666 |
-
<p>This is a proxy server that converts the Tencent Hunyuan LLM API to an OpenAI-compatible API.</p>
|
| 667 |
-
<p>You can use this proxy to access the Hunyuan LLM with any OpenAI-compatible client.</p>
|
| 668 |
-
</div>
|
| 669 |
-
</div>
|
| 670 |
-
<div class="footer">
|
| 671 |
-
<p>Powered by <a href="https://neuroplexus.my" target="_blank">Neuroplexus</a></p>
|
| 672 |
-
</div>
|
| 673 |
-
</body>
|
| 674 |
-
</html>
|
| 675 |
-
`;
|
| 676 |
-
|
| 677 |
-
|
| 678 |
-
const playgroundPage = `
|
| 679 |
-
<!DOCTYPE html>
|
| 680 |
-
<html lang="en">
|
| 681 |
-
<head>
|
| 682 |
-
<meta charset="UTF-8">
|
| 683 |
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 684 |
-
<title>Hunyuan Playground</title>
|
| 685 |
-
<style>${sharedStyles}
|
| 686 |
-
textarea, #output {
|
| 687 |
-
width: 100%;
|
| 688 |
-
border: 1px solid var(--border);
|
| 689 |
-
border-radius: var(--radius);
|
| 690 |
-
padding: 1rem;
|
| 691 |
-
margin-bottom: 1rem;
|
| 692 |
-
font-family: inherit;
|
| 693 |
-
font-size: 1rem;
|
| 694 |
-
resize: vertical;
|
| 695 |
-
color: var(--foreground);
|
| 696 |
-
}
|
| 697 |
-
textarea { min-height: 10rem; }
|
| 698 |
-
#output { min-height: 15rem; background-color: var(--muted); overflow-y: auto; }
|
| 699 |
-
.button { width: 100%; }
|
| 700 |
-
|
| 701 |
-
</style>
|
| 702 |
-
</head>
|
| 703 |
-
<body>
|
| 704 |
-
${header}
|
| 705 |
-
<div class="container">
|
| 706 |
-
<h1>Hunyuan Playground</h1>
|
| 707 |
-
<div class="card">
|
| 708 |
-
<textarea id="input" placeholder="Enter your prompt here..."></textarea>
|
| 709 |
-
<button class="button" onclick="sendMessage()">Send</button>
|
| 710 |
-
<div id="output"></div>
|
| 711 |
-
</div>
|
| 712 |
-
</div>
|
| 713 |
-
<div class="footer">
|
| 714 |
-
<p>Powered by <a href="https://neuroplexus.my" target="_blank">Neuroplexus</a></p>
|
| 715 |
-
</div>
|
| 716 |
-
<script>
|
| 717 |
-
const apiKey = "${API_KEY}"; // Consider making this dynamic
|
| 718 |
-
async function sendMessage() {
|
| 719 |
-
const input = document.getElementById('input').value;
|
| 720 |
-
const outputDiv = document.getElementById('output');
|
| 721 |
-
outputDiv.innerHTML = '';
|
| 722 |
-
|
| 723 |
-
const response = await fetch('/v1/chat/completions', {
|
| 724 |
-
method: 'POST',
|
| 725 |
headers: {
|
| 726 |
'Content-Type': 'application/json',
|
| 727 |
-
'
|
| 728 |
-
},
|
| 729 |
-
body: JSON.stringify({
|
| 730 |
-
messages: [{ role: 'user', content: input }],
|
| 731 |
-
stream: true,
|
| 732 |
-
}),
|
| 733 |
-
});
|
| 734 |
-
|
| 735 |
-
if (!response.ok) {
|
| 736 |
-
outputDiv.innerHTML = 'Error: ' + response.statusText;
|
| 737 |
-
return;
|
| 738 |
-
}
|
| 739 |
-
|
| 740 |
-
const reader = response.body.getReader();
|
| 741 |
-
const decoder = new TextDecoder('utf-8');
|
| 742 |
-
let buffer = '';
|
| 743 |
-
|
| 744 |
-
try {
|
| 745 |
-
while (true) {
|
| 746 |
-
const { done, value } = await reader.read();
|
| 747 |
-
if (done) break;
|
| 748 |
-
|
| 749 |
-
buffer += decoder.decode(value, { stream: true });
|
| 750 |
-
|
| 751 |
-
let boundary = buffer.indexOf("\\n\\n");
|
| 752 |
-
while (boundary !== -1) {
|
| 753 |
-
const chunk = buffer.substring(0, boundary).trim();
|
| 754 |
-
buffer = buffer.substring(boundary + 2);
|
| 755 |
-
boundary = buffer.indexOf("\\n\\n");
|
| 756 |
-
|
| 757 |
-
if (chunk.startsWith("data:")) {
|
| 758 |
-
const jsonStr = chunk.substring(5).trim();
|
| 759 |
-
|
| 760 |
-
if (jsonStr === "[DONE]") {
|
| 761 |
-
continue
|
| 762 |
-
}
|
| 763 |
-
try {
|
| 764 |
-
const data = JSON.parse(jsonStr);
|
| 765 |
-
if (data.choices && data.choices[0] && data.choices[0].delta && data.choices[0].delta.content) {
|
| 766 |
-
outputDiv.innerHTML += data.choices[0].delta.content;
|
| 767 |
-
outputDiv.scrollTop = outputDiv.scrollHeight;
|
| 768 |
-
}
|
| 769 |
-
} catch (error) {
|
| 770 |
-
console.error("Error parsing JSON:", error);
|
| 771 |
-
outputDiv.innerHTML += "Error parsing response chunk. ";
|
| 772 |
-
}
|
| 773 |
-
}
|
| 774 |
-
}
|
| 775 |
}
|
| 776 |
-
}
|
| 777 |
-
reader.releaseLock();
|
| 778 |
-
}
|
| 779 |
}
|
| 780 |
-
</script>
|
| 781 |
-
</body>
|
| 782 |
-
</html>
|
| 783 |
-
`;
|
| 784 |
-
|
| 785 |
-
const docsPage = `
|
| 786 |
-
<!DOCTYPE html>
|
| 787 |
-
<html lang="en">
|
| 788 |
-
<head>
|
| 789 |
-
<meta charset="UTF-8">
|
| 790 |
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 791 |
-
<title>API Documentation</title>
|
| 792 |
-
<style>${sharedStyles}</style>
|
| 793 |
-
</head>
|
| 794 |
-
<body>
|
| 795 |
-
${header}
|
| 796 |
-
<div class="container">
|
| 797 |
-
<h1>API Documentation</h1>
|
| 798 |
-
<div class="card">
|
| 799 |
-
<h2>Chat Completions</h2>
|
| 800 |
-
<p>This endpoint mimics the OpenAI Chat Completion API.</p>
|
| 801 |
-
<h3>Endpoint</h3>
|
| 802 |
-
<pre><code>POST /v1/chat/completions</code></pre>
|
| 803 |
-
<h3>Request Headers</h3>
|
| 804 |
-
<pre><code>Authorization: Bearer YOUR_API_KEY</code></pre>
|
| 805 |
-
<pre><code>Content-Type: application/json</code></pre>
|
| 806 |
-
|
| 807 |
-
<h3>Request Body (Example)</h3>
|
| 808 |
-
<pre><code>{
|
| 809 |
-
"messages": [
|
| 810 |
-
{
|
| 811 |
-
"role": "user",
|
| 812 |
-
"content": "Hello, who are you?"
|
| 813 |
}
|
| 814 |
-
],
|
| 815 |
-
"model": "hunyuan-t1-latest",
|
| 816 |
-
"stream": true
|
| 817 |
-
}</code></pre>
|
| 818 |
-
<p>Supported models: <code>hunyuan-t1-latest</code>, <code>hunyuan-turbos-latest</code>. To make a non-streaming request, set <code>"stream": false</code> in the request body.</p>
|
| 819 |
-
<h3>Response</h3>
|
| 820 |
-
<p>Returns a stream of Server-Sent Events (SSE) in the OpenAI format for streaming requests, or a JSON object for non-streaming requests.</p>
|
| 821 |
-
</div>
|
| 822 |
-
|
| 823 |
-
<div class="card">
|
| 824 |
-
<h2>Models</h2>
|
| 825 |
-
<p>Get a list of available models.</p>
|
| 826 |
-
<h3>Endpoint</h3>
|
| 827 |
-
<pre><code>GET /v1/models</code></pre>
|
| 828 |
-
<h3>Response (Example)</h3>
|
| 829 |
-
<pre><code>
|
| 830 |
-
{
|
| 831 |
-
"object": "list",
|
| 832 |
-
"data": [
|
| 833 |
-
{
|
| 834 |
-
"id": "hunyuan-t1-latest",
|
| 835 |
-
"object": "model",
|
| 836 |
-
"created": 1678886400,
|
| 837 |
-
"owned_by": "tencent"
|
| 838 |
-
},
|
| 839 |
-
{
|
| 840 |
-
"id": "hunyuan-turbos-latest",
|
| 841 |
-
"object": "model",
|
| 842 |
-
"created": 1700000000,
|
| 843 |
-
"owned_by": "tencent"
|
| 844 |
-
}
|
| 845 |
-
]
|
| 846 |
-
}
|
| 847 |
-
</code></pre>
|
| 848 |
-
</div>
|
| 849 |
-
<div class="card">
|
| 850 |
-
<h2>Get API Key</h2>
|
| 851 |
-
<p>Retrieves the API key.</p>
|
| 852 |
-
<h3>Endpoint</h3>
|
| 853 |
-
<pre><code>GET /getkey</code></pre>
|
| 854 |
-
</div>
|
| 855 |
-
</div>
|
| 856 |
-
<div class="footer">
|
| 857 |
-
<p>Powered by <a href="https://neuroplexus.my" target="_blank">Neuroplexus</a></p>
|
| 858 |
-
</div>
|
| 859 |
-
</body>
|
| 860 |
-
</html>
|
| 861 |
-
`;
|
| 862 |
-
|
| 863 |
-
const getKeyPage = `
|
| 864 |
-
<!DOCTYPE html>
|
| 865 |
-
<html lang="en">
|
| 866 |
-
<head>
|
| 867 |
-
<meta charset="UTF-8">
|
| 868 |
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 869 |
-
<title>Get API Key</title>
|
| 870 |
-
<style>${sharedStyles}</style>
|
| 871 |
-
</head>
|
| 872 |
-
<body>
|
| 873 |
-
${header}
|
| 874 |
-
<div class="container">
|
| 875 |
-
<h1>Get API Key</h1>
|
| 876 |
-
<div class="card">
|
| 877 |
-
<p>Your API Key is: <code>${API_KEY}</code></p>
|
| 878 |
-
</div>
|
| 879 |
-
</div>
|
| 880 |
-
<div class="footer">
|
| 881 |
-
<p>Powered by <a href="https://neuroplexus.my" target="_blank">Neuroplexus</a></p>
|
| 882 |
-
</div>
|
| 883 |
-
</body>
|
| 884 |
-
</html>
|
| 885 |
-
`;
|
| 886 |
-
async function handleGetKey(ctx: Context) {
|
| 887 |
-
const acceptHeader = ctx.request.headers.get("Accept");
|
| 888 |
-
if (acceptHeader && acceptHeader.includes("application/json")) {
|
| 889 |
-
ctx.response.body = { key: API_KEY };
|
| 890 |
-
ctx.response.type = "application/json";
|
| 891 |
-
} else {
|
| 892 |
-
ctx.response.body = getKeyPage;
|
| 893 |
-
ctx.response.type = "text/html";
|
| 894 |
-
}
|
| 895 |
-
}
|
| 896 |
|
| 897 |
-
|
| 898 |
-
|
| 899 |
-
|
| 900 |
-
|
| 901 |
-
|
| 902 |
-
|
| 903 |
-
|
| 904 |
-
ctx.response.type = "text/html";
|
| 905 |
-
}
|
| 906 |
-
|
| 907 |
-
async function handleDocs(ctx: Context) {
|
| 908 |
-
ctx.response.body = docsPage;
|
| 909 |
-
ctx.response.type = "text/html";
|
| 910 |
-
}
|
| 911 |
-
|
| 912 |
-
const router = new Router();
|
| 913 |
-
router.post("/v1/chat/completions", handleChatCompletion);
|
| 914 |
-
router.get("/v1/models", handleModels);
|
| 915 |
-
router.get("/getkey", handleGetKey);
|
| 916 |
-
router.get("/", handleHomePage);
|
| 917 |
-
router.get("/playground", handlePlayground);
|
| 918 |
-
router.get("/docs", handleDocs);
|
| 919 |
-
|
| 920 |
-
const app = new Application();
|
| 921 |
-
app.use(router.routes());
|
| 922 |
-
app.use(router.allowedMethods());
|
| 923 |
-
|
| 924 |
-
console.log("Server listening on port 8000");
|
| 925 |
-
await app.listen({ port: 7860 });
|
|
|
|
| 1 |
+
// 配置常量啊1
|
| 2 |
+
const CONFIG = {
|
| 3 |
+
API: {
|
| 4 |
+
BASE_URL: "https://fragments.e2b.dev",
|
| 5 |
+
API_KEY: "sk-123456"//自定义你自己的认证密钥,记得修改
|
| 6 |
+
},
|
| 7 |
+
RETRY: {
|
| 8 |
+
MAX_ATTEMPTS: 1,
|
| 9 |
+
DELAY_BASE: 1000
|
| 10 |
+
},
|
| 11 |
+
MODEL_CONFIG: {
|
| 12 |
+
"o1-preview": {
|
| 13 |
+
id: "o1",
|
| 14 |
+
provider: "OpenAI",
|
| 15 |
+
providerId: "openai",
|
| 16 |
+
name: "o1",
|
| 17 |
+
multiModal: true,
|
| 18 |
+
Systemprompt: "",
|
| 19 |
+
opt_max: {
|
| 20 |
+
temperatureMax: 2,
|
| 21 |
+
max_tokensMax: 0,
|
| 22 |
+
presence_penaltyMax: 2,
|
| 23 |
+
frequency_penaltyMax: 2,
|
| 24 |
+
top_pMax: 1,
|
| 25 |
+
top_kMax: 500
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
}
|
| 27 |
+
},
|
| 28 |
+
"o3-mini": {
|
| 29 |
+
id: "o3-mini",
|
| 30 |
+
provider: "OpenAI",
|
| 31 |
+
providerId: "openai",
|
| 32 |
+
name: "o3 Mini",
|
| 33 |
+
multiModal: true,
|
| 34 |
+
Systemprompt: "",
|
| 35 |
+
opt_max: {
|
| 36 |
+
temperatureMax: 2,
|
| 37 |
+
max_tokensMax: 4096,
|
| 38 |
+
presence_penaltyMax: 2,
|
| 39 |
+
frequency_penaltyMax: 2,
|
| 40 |
+
top_pMax: 1,
|
| 41 |
+
top_kMax: 500
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
}
|
| 43 |
},
|
| 44 |
+
"gpt-4o": {
|
| 45 |
+
id: "gpt-4o",
|
| 46 |
+
provider: "OpenAI",
|
| 47 |
+
providerId: "openai",
|
| 48 |
+
name: "GPT-4o",
|
| 49 |
+
multiModal: true,
|
| 50 |
+
Systemprompt: "",
|
| 51 |
+
opt_max: {
|
| 52 |
+
temperatureMax: 2,
|
| 53 |
+
max_tokensMax: 16380,
|
| 54 |
+
presence_penaltyMax: 2,
|
| 55 |
+
frequency_penaltyMax: 2,
|
| 56 |
+
top_pMax: 1,
|
| 57 |
+
top_kMax: 500
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
}
|
| 59 |
+
},
|
| 60 |
+
"gpt-4.5-preview": {
|
| 61 |
+
id: "gpt-4.5-preview",
|
| 62 |
+
provider: "OpenAI",
|
| 63 |
+
providerId: "openai",
|
| 64 |
+
name: "GPT-4.5",
|
| 65 |
+
multiModal: true,
|
| 66 |
+
Systemprompt: "",
|
| 67 |
+
opt_max: {
|
| 68 |
+
temperatureMax: 2,
|
| 69 |
+
max_tokensMax: 16380,
|
| 70 |
+
presence_penaltyMax: 2,
|
| 71 |
+
frequency_penaltyMax: 2,
|
| 72 |
+
top_pMax: 1,
|
| 73 |
+
top_kMax: 500
|
| 74 |
+
}
|
| 75 |
+
},
|
| 76 |
+
"gpt-4-turbo": {
|
| 77 |
+
id: "gpt-4-turbo",
|
| 78 |
+
provider: "OpenAI",
|
| 79 |
+
providerId: "openai",
|
| 80 |
+
name: "GPT-4 Turbo",
|
| 81 |
+
multiModal: true,
|
| 82 |
+
Systemprompt: "",
|
| 83 |
+
opt_max: {
|
| 84 |
+
temperatureMax: 2,
|
| 85 |
+
max_tokensMax: 16380,
|
| 86 |
+
presence_penaltyMax: 2,
|
| 87 |
+
frequency_penaltyMax: 2,
|
| 88 |
+
top_pMax: 1,
|
| 89 |
+
top_kMax: 500
|
| 90 |
+
}
|
| 91 |
+
},
|
| 92 |
+
"gemini-1.5-pro": {
|
| 93 |
+
id: "gemini-1.5-pro-002",
|
| 94 |
+
provider: "Google Vertex AI",
|
| 95 |
+
providerId: "vertex",
|
| 96 |
+
name: "Gemini 1.5 Pro",
|
| 97 |
+
multiModal: true,
|
| 98 |
+
Systemprompt: "",
|
| 99 |
+
opt_max: {
|
| 100 |
+
temperatureMax: 2,
|
| 101 |
+
max_tokensMax: 8192,
|
| 102 |
+
presence_penaltyMax: 2,
|
| 103 |
+
frequency_penaltyMax: 2,
|
| 104 |
+
top_pMax: 1,
|
| 105 |
+
top_kMax: 500
|
| 106 |
+
}
|
| 107 |
+
},
|
| 108 |
+
"gemini-2.5-pro-exp-03-25": {
|
| 109 |
+
id: "gemini-2.5-pro-exp-03-25",
|
| 110 |
+
provider: "Google Generative AI",
|
| 111 |
+
providerId: "google",
|
| 112 |
+
name: "Gemini 2.5 Pro Experimental 03-25",
|
| 113 |
+
multiModal: true,
|
| 114 |
+
Systemprompt: "",
|
| 115 |
+
opt_max: {
|
| 116 |
+
temperatureMax: 2,
|
| 117 |
+
max_tokensMax: 8192,
|
| 118 |
+
presence_penaltyMax: 2,
|
| 119 |
+
frequency_penaltyMax: 2,
|
| 120 |
+
top_pMax: 1,
|
| 121 |
+
top_kMax: 40
|
| 122 |
+
}
|
| 123 |
+
},
|
| 124 |
+
"gemini-exp-1121": {
|
| 125 |
+
id: "gemini-exp-1121",
|
| 126 |
+
provider: "Google Generative AI",
|
| 127 |
+
providerId: "google",
|
| 128 |
+
name: "Gemini Experimental 1121",
|
| 129 |
+
multiModal: true,
|
| 130 |
+
Systemprompt: "",
|
| 131 |
+
opt_max: {
|
| 132 |
+
temperatureMax: 2,
|
| 133 |
+
max_tokensMax: 8192,
|
| 134 |
+
presence_penaltyMax: 2,
|
| 135 |
+
frequency_penaltyMax: 2,
|
| 136 |
+
top_pMax: 1,
|
| 137 |
+
top_kMax: 40
|
| 138 |
+
}
|
| 139 |
+
},
|
| 140 |
+
"gemini-2.0-flash-exp": {
|
| 141 |
+
id: "models/gemini-2.0-flash-exp",
|
| 142 |
+
provider: "Google Generative AI",
|
| 143 |
+
providerId: "google",
|
| 144 |
+
name: "Gemini 2.0 Flash",
|
| 145 |
+
multiModal: true,
|
| 146 |
+
Systemprompt: "",
|
| 147 |
+
opt_max: {
|
| 148 |
+
temperatureMax: 2,
|
| 149 |
+
max_tokensMax: 8192,
|
| 150 |
+
presence_penaltyMax: 2,
|
| 151 |
+
frequency_penaltyMax: 2,
|
| 152 |
+
top_pMax: 1,
|
| 153 |
+
top_kMax: 40
|
| 154 |
+
}
|
| 155 |
+
},
|
| 156 |
+
"claude-3-5-sonnet-latest": {
|
| 157 |
+
id: "claude-3-5-sonnet-latest",
|
| 158 |
+
provider: "Anthropic",
|
| 159 |
+
providerId: "anthropic",
|
| 160 |
+
name: "Claude 3.5 Sonnet",
|
| 161 |
+
multiModal: true,
|
| 162 |
+
Systemprompt: "",
|
| 163 |
+
opt_max: {
|
| 164 |
+
temperatureMax: 1,
|
| 165 |
+
max_tokensMax: 8192,
|
| 166 |
+
presence_penaltyMax: 2,
|
| 167 |
+
frequency_penaltyMax: 2,
|
| 168 |
+
top_pMax: 1,
|
| 169 |
+
top_kMax: 500
|
| 170 |
+
}
|
| 171 |
+
},
|
| 172 |
+
"claude-3-7-sonnet-latest": {
|
| 173 |
+
id: "claude-3-7-sonnet-latest",
|
| 174 |
+
provider: "Anthropic",
|
| 175 |
+
providerId: "anthropic",
|
| 176 |
+
name: "Claude 3.7 Sonnet",
|
| 177 |
+
multiModal: true,
|
| 178 |
+
Systemprompt: "",
|
| 179 |
+
opt_max: {
|
| 180 |
+
temperatureMax: 1,
|
| 181 |
+
max_tokensMax: 8192,
|
| 182 |
+
presence_penaltyMax: 2,
|
| 183 |
+
frequency_penaltyMax: 2,
|
| 184 |
+
top_pMax: 1,
|
| 185 |
+
top_kMax: 500
|
| 186 |
+
}
|
| 187 |
+
},
|
| 188 |
+
"claude-3-5-haiku-latest": {
|
| 189 |
+
id: "claude-3-5-haiku-latest",
|
| 190 |
+
provider: "Anthropic",
|
| 191 |
+
providerId: "anthropic",
|
| 192 |
+
name: "Claude 3.5 Haiku",
|
| 193 |
+
multiModal: false,
|
| 194 |
+
Systemprompt: "",
|
| 195 |
+
opt_max: {
|
| 196 |
+
temperatureMax: 1,
|
| 197 |
+
max_tokensMax: 8192,
|
| 198 |
+
presence_penaltyMax: 2,
|
| 199 |
+
frequency_penaltyMax: 2,
|
| 200 |
+
top_pMax: 1,
|
| 201 |
+
top_kMax: 500
|
| 202 |
+
}
|
| 203 |
+
}
|
| 204 |
+
},
|
| 205 |
+
DEFAULT_HEADERS: {
|
| 206 |
+
"accept": "*/*",
|
| 207 |
+
"accept-language": "zh-CN,zh;q=0.9",
|
| 208 |
+
"content-type": "application/json",
|
| 209 |
+
"priority": "u=1, i",
|
| 210 |
+
"sec-ch-ua": "\"Microsoft Edge\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"",
|
| 211 |
+
"sec-ch-ua-mobile": "?0",
|
| 212 |
+
"sec-ch-ua-platform": "\"Windows\"",
|
| 213 |
+
"sec-fetch-dest": "empty",
|
| 214 |
+
"sec-fetch-mode": "cors",
|
| 215 |
+
"sec-fetch-site": "same-origin",
|
| 216 |
+
"Referer": "https://fragments.e2b.dev/",
|
| 217 |
+
"Referrer-Policy": "strict-origin-when-cross-origin"
|
| 218 |
+
},
|
| 219 |
+
MODEL_PROMPT: "Chatting with users and starting role-playing, the most important thing is to pay attention to their latest messages, use only 'text' to output the chat text reply content generated for user messages, and finally output it in code"
|
| 220 |
+
};
|
| 221 |
+
|
| 222 |
+
// 日志工具类
|
| 223 |
+
class Logger {
|
| 224 |
+
static info(message: string, data?: any) {
|
| 225 |
+
const timestamp = new Date().toISOString();
|
| 226 |
+
console.log(`[${timestamp}] INFO: ${message}`);
|
| 227 |
+
if (data) {
|
| 228 |
+
try {
|
| 229 |
+
// 对于大型响应体,可能需要截断
|
| 230 |
+
const dataStr = JSON.stringify(data, null, 2).substring(0, 500);
|
| 231 |
+
console.log(dataStr + (dataStr.length >= 500 ? '...(truncated)' : ''));
|
| 232 |
+
} catch (e) {
|
| 233 |
+
console.log('无法序列化日志数据');
|
| 234 |
}
|
| 235 |
}
|
|
|
|
|
|
|
| 236 |
}
|
| 237 |
|
| 238 |
+
static error(message: string, error?: any) {
|
| 239 |
+
const timestamp = new Date().toISOString();
|
| 240 |
+
console.error(`[${timestamp}] ERROR: ${message}`, error);
|
| 241 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
}
|
| 243 |
|
| 244 |
+
// 工具类
|
| 245 |
+
class Utils {
|
| 246 |
+
static uuidv4(): string {
|
| 247 |
+
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
|
| 248 |
+
const r = Math.random() * 16 | 0;
|
| 249 |
+
const v = c === 'x' ? r : (r & 0x3 | 0x8);
|
| 250 |
+
return v.toString(16);
|
| 251 |
+
});
|
| 252 |
+
}
|
|
|
|
|
|
|
| 253 |
|
| 254 |
+
static async configOpt(params: Record<string, any>, modelConfig: any): Promise<Record<string, any> | null> {
|
| 255 |
+
if (!modelConfig.opt_max) return null;
|
|
|
|
|
|
|
|
|
|
| 256 |
|
| 257 |
+
const optionsMap = {
|
| 258 |
+
temperature: 'temperatureMax',
|
| 259 |
+
max_tokens: 'max_tokensMax',
|
| 260 |
+
presence_penalty: 'presence_penaltyMax',
|
| 261 |
+
frequency_penalty: 'frequency_penaltyMax',
|
| 262 |
+
top_p: 'top_pMax',
|
| 263 |
+
top_k: 'top_kMax'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
};
|
| 265 |
|
| 266 |
+
const constrainedParams = Object.fromEntries(
|
| 267 |
+
Object.entries(params)
|
| 268 |
+
.filter(([key, value]) => {
|
| 269 |
+
const maxKey = optionsMap[key as keyof typeof optionsMap];
|
| 270 |
+
return maxKey &&
|
| 271 |
+
modelConfig.opt_max[maxKey] &&
|
| 272 |
+
value !== null &&
|
| 273 |
+
value !== undefined;
|
| 274 |
+
})
|
| 275 |
+
.map(([key, value]) => {
|
| 276 |
+
const maxKey = optionsMap[key as keyof typeof optionsMap];
|
| 277 |
+
return [key, Math.min(value as number, modelConfig.opt_max[maxKey])];
|
| 278 |
+
})
|
| 279 |
+
);
|
| 280 |
+
|
| 281 |
+
return constrainedParams;
|
| 282 |
+
}
|
| 283 |
+
}
|
| 284 |
|
| 285 |
+
// API客户端类
|
| 286 |
+
class ApiClient {
|
| 287 |
+
private modelConfig: any;
|
| 288 |
+
private requestId: string;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 289 |
|
| 290 |
+
constructor(modelId: string, requestId: string = '') {
|
| 291 |
+
if (!CONFIG.MODEL_CONFIG[modelId]) {
|
| 292 |
+
throw new Error(`不支持的模型: ${modelId}`);
|
|
|
|
|
|
|
|
|
|
| 293 |
}
|
| 294 |
+
this.modelConfig = CONFIG.MODEL_CONFIG[modelId];
|
| 295 |
+
this.requestId = requestId;
|
| 296 |
+
}
|
| 297 |
|
| 298 |
+
processMessageContent(content: any): string | null {
|
| 299 |
+
if (typeof content === 'string') return content;
|
| 300 |
+
if (Array.isArray(content)) {
|
| 301 |
+
return content
|
| 302 |
+
.filter(item => item.type === 'text')
|
| 303 |
+
.map(item => item.text)
|
| 304 |
+
.join('\n');
|
|
|
|
| 305 |
}
|
| 306 |
|
| 307 |
+
if (typeof content === 'object') return content.text || null;
|
| 308 |
+
return null;
|
|
|
|
|
|
|
| 309 |
}
|
|
|
|
| 310 |
|
| 311 |
+
async prepareChatRequest(request: any, config: any) {
|
| 312 |
+
Logger.info(`[${this.requestId}] 准备聊天请求, 模型: ${this.modelConfig.name}, 消息数: ${request.messages?.length || 0}`);
|
| 313 |
+
|
| 314 |
+
const optConfig = config || { model: this.modelConfig.id };
|
| 315 |
+
const transformedMessages = await this.transformMessages(request);
|
| 316 |
+
|
| 317 |
+
Logger.info(`[${this.requestId}] 转换后的消息数量: ${transformedMessages.length}`);
|
| 318 |
+
|
| 319 |
+
return {
|
| 320 |
+
userID: Utils.uuidv4(),
|
| 321 |
+
messages: transformedMessages,
|
| 322 |
+
template: {
|
| 323 |
+
text: {
|
| 324 |
+
name: CONFIG.MODEL_PROMPT,
|
| 325 |
+
lib: [""],
|
| 326 |
+
file: "pages/ChatWithUsers.txt",
|
| 327 |
+
instructions: this.modelConfig.Systemprompt,
|
| 328 |
+
port: null
|
| 329 |
+
}
|
| 330 |
},
|
| 331 |
+
model: {
|
| 332 |
+
id: this.modelConfig.id,
|
| 333 |
+
provider: this.modelConfig.provider,
|
| 334 |
+
providerId: this.modelConfig.providerId,
|
| 335 |
+
name: this.modelConfig.name,
|
| 336 |
+
multiModal: this.modelConfig.multiModal
|
| 337 |
+
},
|
| 338 |
+
config: optConfig
|
| 339 |
+
};
|
| 340 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 341 |
|
| 342 |
+
async transformMessages(request: any) {
|
| 343 |
+
const mergedMessages = request.messages.reduce((acc: any[], current: any) => {
|
| 344 |
+
const lastMessage = acc[acc.length - 1];
|
| 345 |
+
const currentContent = this.processMessageContent(current.content);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 346 |
|
| 347 |
+
if (currentContent === null) return acc;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 348 |
|
| 349 |
+
if (lastMessage && current && (lastMessage.role == current.role)) {
|
| 350 |
+
const lastContent = this.processMessageContent(lastMessage.content);
|
| 351 |
+
if (lastContent !== null) {
|
| 352 |
+
lastMessage.content = `${lastContent}\n${currentContent}`;
|
| 353 |
+
return acc;
|
| 354 |
+
}
|
| 355 |
+
}
|
| 356 |
+
acc.push(current);
|
| 357 |
+
return acc;
|
| 358 |
+
}, []);
|
| 359 |
+
|
| 360 |
+
return mergedMessages.map((msg: any) => {
|
| 361 |
+
switch (msg.role) {
|
| 362 |
+
case "system":
|
| 363 |
+
case "user":
|
| 364 |
+
return {
|
| 365 |
+
role: "user",
|
| 366 |
+
content: [{
|
| 367 |
+
type: "text",
|
| 368 |
+
text: msg.content
|
| 369 |
+
}]
|
| 370 |
+
};
|
| 371 |
+
case "assistant":
|
| 372 |
+
return {
|
| 373 |
+
role: "assistant",
|
| 374 |
+
content: [{
|
| 375 |
+
type: "text",
|
| 376 |
+
text: msg.content
|
| 377 |
+
}]
|
| 378 |
+
};
|
| 379 |
+
default:
|
| 380 |
+
return msg;
|
| 381 |
+
}
|
| 382 |
+
});
|
| 383 |
+
}
|
| 384 |
}
|
| 385 |
|
| 386 |
+
// 响应处理类
|
| 387 |
+
class ResponseHandler {
|
| 388 |
+
static async handleStreamResponse(chat_message: string, model: string, requestId: string): Promise<Response> {
|
| 389 |
+
Logger.info(`[${requestId}] 处理流式响应,内容长度: ${chat_message.length} 字符`);
|
| 390 |
+
let index = 0;
|
| 391 |
+
const encoder = new TextEncoder();
|
| 392 |
+
const stream = new ReadableStream({
|
| 393 |
+
async start(controller) {
|
| 394 |
+
try {
|
| 395 |
+
const sendChunk = () => {
|
| 396 |
+
if (index >= chat_message.length) {
|
| 397 |
+
controller.enqueue(encoder.encode('data: [DONE]\n\n'));
|
| 398 |
+
controller.close();
|
| 399 |
+
Logger.info(`[${requestId}] 流式响应完成`);
|
| 400 |
+
return;
|
| 401 |
+
}
|
| 402 |
|
| 403 |
+
const chunkSize = Math.floor(Math.random() * (30 - 16)) + 15;
|
| 404 |
+
const chunk = chat_message.slice(index, index + chunkSize);
|
| 405 |
+
|
| 406 |
+
const eventData = {
|
| 407 |
+
id: Utils.uuidv4(),
|
| 408 |
+
object: 'chat.completion.chunk',
|
| 409 |
+
created: Math.floor(Date.now() / 1000),
|
| 410 |
+
model: model,
|
| 411 |
+
choices: [{
|
| 412 |
+
index: 0,
|
| 413 |
+
delta: { content: chunk },
|
| 414 |
+
finish_reason: index + chunkSize >= chat_message.length ? 'stop' : null
|
| 415 |
+
}]
|
| 416 |
+
};
|
| 417 |
+
|
| 418 |
+
try {
|
| 419 |
+
const payload = `data: ${JSON.stringify(eventData)}\n\n`;
|
| 420 |
+
controller.enqueue(encoder.encode(payload));
|
| 421 |
+
} catch (error) {
|
| 422 |
+
Logger.error(`[${requestId}] 流式响应JSON转换失败`, error);
|
| 423 |
+
throw new Error('json转换失败');
|
| 424 |
+
}
|
| 425 |
|
| 426 |
+
index += chunkSize;
|
| 427 |
+
setTimeout(sendChunk, 50);
|
| 428 |
+
};
|
| 429 |
|
| 430 |
+
sendChunk();
|
| 431 |
+
} catch (error) {
|
| 432 |
+
Logger.error(`[${requestId}] 处理流式响应时出错`, error);
|
| 433 |
+
throw new Error('Error in handleStreamResponse');
|
| 434 |
+
}
|
| 435 |
+
}
|
| 436 |
+
});
|
| 437 |
|
| 438 |
+
return new Response(stream, {
|
| 439 |
+
headers: {
|
| 440 |
+
'Content-Type': 'text/event-stream',
|
| 441 |
+
'Cache-Control': 'no-cache',
|
| 442 |
+
'Connection': 'keep-alive',
|
| 443 |
+
}
|
| 444 |
+
});
|
| 445 |
+
}
|
| 446 |
|
| 447 |
+
static async handleNormalResponse(chat_message: string, model: string, requestId: string): Promise<Response> {
|
| 448 |
+
Logger.info(`[${requestId}] 处理普通响应,内容长度: ${chat_message.length} 字符`);
|
| 449 |
+
|
| 450 |
+
const responseData = {
|
| 451 |
+
id: Utils.uuidv4(),
|
| 452 |
+
object: "chat.completion",
|
| 453 |
+
created: Math.floor(Date.now() / 1000),
|
| 454 |
+
model: model,
|
| 455 |
+
choices: [{
|
| 456 |
+
index: 0,
|
| 457 |
+
message: {
|
| 458 |
+
role: "assistant",
|
| 459 |
+
content: chat_message
|
| 460 |
+
},
|
| 461 |
+
finish_reason: "stop"
|
| 462 |
+
}],
|
| 463 |
+
usage: null
|
| 464 |
+
};
|
| 465 |
|
| 466 |
+
return new Response(JSON.stringify(responseData), {
|
| 467 |
+
headers: { 'Content-Type': 'application/json' }
|
| 468 |
+
});
|
| 469 |
+
}
|
|
|
|
| 470 |
}
|
| 471 |
|
| 472 |
+
// Deno 服务处理
|
| 473 |
+
Deno.serve(async (request: Request): Promise<Response> => {
|
| 474 |
+
const requestId = Utils.uuidv4();
|
| 475 |
+
const url = new URL(request.url);
|
| 476 |
+
|
| 477 |
+
Logger.info(`[${requestId}] 接收到请求: ${request.method} ${url.pathname}`);
|
| 478 |
+
|
| 479 |
+
// 处理 CORS 预检请求
|
| 480 |
+
if (request.method === 'OPTIONS') {
|
| 481 |
+
Logger.info(`[${requestId}] 处理CORS预检请求`);
|
| 482 |
+
return new Response(null, {
|
| 483 |
+
headers: {
|
| 484 |
+
'Access-Control-Allow-Origin': '*',
|
| 485 |
+
'Access-Control-Allow-Methods': 'GET,POST,OPTIONS',
|
| 486 |
+
'Access-Control-Allow-Headers': '*'
|
| 487 |
+
}
|
| 488 |
+
});
|
| 489 |
+
}
|
| 490 |
|
| 491 |
+
// Models endpoint
|
| 492 |
+
if (url.pathname === '/hf/v1/models' && request.method === 'GET') {
|
| 493 |
+
Logger.info(`[${requestId}] 获取模型列表`);
|
| 494 |
+
|
| 495 |
+
const response = new Response(JSON.stringify({
|
| 496 |
+
object: "list",
|
| 497 |
+
data: Object.keys(CONFIG.MODEL_CONFIG).map((model) => ({
|
| 498 |
+
id: model,
|
| 499 |
+
object: "model",
|
| 500 |
+
created: Math.floor(Date.now() / 1000),
|
| 501 |
+
owned_by: "e2b",
|
| 502 |
+
})),
|
| 503 |
+
}), {
|
| 504 |
+
headers: {
|
| 505 |
+
'Content-Type': 'application/json',
|
| 506 |
+
'Access-Control-Allow-Origin': '*'
|
| 507 |
+
}
|
| 508 |
+
});
|
| 509 |
+
|
| 510 |
+
Logger.info(`[${requestId}] 模型列表返回成功,模型数量: ${Object.keys(CONFIG.MODEL_CONFIG).length}`);
|
| 511 |
+
return response;
|
| 512 |
+
}
|
| 513 |
|
| 514 |
+
// Chat completions endpoint
|
| 515 |
+
if (url.pathname === '/hf/v1/chat/completions' && request.method === 'POST') {
|
| 516 |
+
try {
|
| 517 |
+
Logger.info(`[${requestId}] 处理聊天完成请求`);
|
| 518 |
+
|
| 519 |
+
const authToken = request.headers.get('authorization')?.replace('Bearer ', '');
|
| 520 |
+
if (authToken !== CONFIG.API.API_KEY) {
|
| 521 |
+
Logger.error(`[${requestId}] 认证失败,提供的令牌: ${authToken?.substring(0, 8)}...`);
|
| 522 |
+
return new Response(JSON.stringify({ error: "Unauthorized" }), {
|
| 523 |
+
status: 401,
|
| 524 |
+
headers: { 'Content-Type': 'application/json' }
|
| 525 |
+
});
|
| 526 |
+
}
|
| 527 |
|
| 528 |
+
// 克隆请求以便读取其内容而不消耗原始请求
|
| 529 |
+
const requestClone = request.clone();
|
| 530 |
+
const requestBody = await requestClone.json();
|
| 531 |
+
Logger.info(`[${requestId}] 用户请求体:`, {
|
| 532 |
+
model: requestBody.model,
|
| 533 |
+
messages_count: requestBody.messages?.length,
|
| 534 |
+
stream: requestBody.stream,
|
| 535 |
+
temperature: requestBody.temperature,
|
| 536 |
+
max_tokens: requestBody.max_tokens
|
| 537 |
+
});
|
| 538 |
|
| 539 |
+
const {
|
| 540 |
+
model,
|
| 541 |
+
temperature,
|
| 542 |
+
max_tokens,
|
| 543 |
+
presence_penalty,
|
| 544 |
+
frequency_penalty,
|
| 545 |
+
top_p,
|
| 546 |
+
top_k,
|
| 547 |
+
stream
|
| 548 |
+
} = requestBody;
|
| 549 |
+
|
| 550 |
+
const configOpt = await Utils.configOpt({
|
| 551 |
+
temperature,
|
| 552 |
+
max_tokens,
|
| 553 |
+
presence_penalty,
|
| 554 |
+
frequency_penalty,
|
| 555 |
+
top_p,
|
| 556 |
+
top_k
|
| 557 |
+
}, CONFIG.MODEL_CONFIG[model]);
|
| 558 |
+
|
| 559 |
+
const apiClient = new ApiClient(model, requestId);
|
| 560 |
+
const requestPayload = await apiClient.prepareChatRequest(requestBody, configOpt);
|
| 561 |
+
|
| 562 |
+
Logger.info(`[${requestId}] 发送到E2B的请求:`, {
|
| 563 |
+
model: requestPayload.model.name,
|
| 564 |
+
messages_count: requestPayload.messages?.length,
|
| 565 |
+
config: requestPayload.config
|
| 566 |
+
});
|
| 567 |
|
| 568 |
+
const fetchStartTime = Date.now();
|
| 569 |
+
const fetchResponse = await fetch(`${CONFIG.API.BASE_URL}/api/chat`, {
|
| 570 |
+
method: "POST",
|
| 571 |
+
headers: CONFIG.DEFAULT_HEADERS,
|
| 572 |
+
body: JSON.stringify(requestPayload)
|
| 573 |
+
});
|
| 574 |
+
const fetchEndTime = Date.now();
|
| 575 |
+
|
| 576 |
+
const responseData = await fetchResponse.json();
|
| 577 |
+
Logger.info(`[${requestId}] 收到E2B的响应: ${fetchResponse.status}, 耗时: ${fetchEndTime - fetchStartTime}ms`, {
|
| 578 |
+
status: fetchResponse.status,
|
| 579 |
+
has_code: !!responseData?.code,
|
| 580 |
+
has_text: !!responseData?.text,
|
| 581 |
+
response_preview: (responseData?.code || responseData?.text || '')?.substring(0, 100) + '...'
|
| 582 |
+
});
|
|
|
|
|
|
|
| 583 |
|
| 584 |
+
const chat_message = responseData?.code?.trim() ??
|
| 585 |
+
responseData?.text?.trim() ??
|
| 586 |
+
responseData?.trim() ??
|
| 587 |
+
null;
|
| 588 |
|
| 589 |
+
if (!chat_message) {
|
| 590 |
+
Logger.error(`[${requestId}] E2B没有返回有效响应`);
|
| 591 |
+
throw new Error('No response from upstream service');
|
| 592 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 593 |
|
| 594 |
+
let response;
|
| 595 |
+
if (stream) {
|
| 596 |
+
response = await ResponseHandler.handleStreamResponse(chat_message, model, requestId);
|
| 597 |
+
} else {
|
| 598 |
+
response = await ResponseHandler.handleNormalResponse(chat_message, model, requestId);
|
| 599 |
+
}
|
| 600 |
+
|
| 601 |
+
return response;
|
| 602 |
+
|
| 603 |
+
} catch (error) {
|
| 604 |
+
Logger.error(`[${requestId}] 处理请求时出错:`, error);
|
| 605 |
+
|
| 606 |
+
return new Response(JSON.stringify({
|
| 607 |
+
error: {
|
| 608 |
+
message: `${error.message} 请求失败,可能是上下文超出限制或其他错误,请稍后重试。`,
|
| 609 |
+
type: 'server_error',
|
| 610 |
+
param: null,
|
| 611 |
+
code: null
|
| 612 |
+
}
|
| 613 |
+
}), {
|
| 614 |
+
status: 500,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 615 |
headers: {
|
| 616 |
'Content-Type': 'application/json',
|
| 617 |
+
'Access-Control-Allow-Origin': '*'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 618 |
}
|
| 619 |
+
});
|
|
|
|
|
|
|
| 620 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 621 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 622 |
|
| 623 |
+
// 404 处理
|
| 624 |
+
Logger.info(`[${requestId}] 未找到路径: ${url.pathname}`);
|
| 625 |
+
return new Response('服务运行成功,请使用正确请求路径', {
|
| 626 |
+
status: 404,
|
| 627 |
+
headers: { 'Access-Control-Allow-Origin': '*' }
|
| 628 |
+
});
|
| 629 |
+
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|