Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
392 lines (343 loc) · 14.1 KB
/
Copy pathindex.js
File metadata and controls
392 lines (343 loc) · 14.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
/**
* Qwen2API - 统一入口
*
* 支持: Docker (Express) / Vercel / Netlify
*/
const { handleModels, handleChatCompletions, handleChatCompletionsWithLogs, handleImageGenerations, handleRoot, handleChatPage, createResponse, validateToken, uuidv4, mapUpstreamDeltaToOpenAI, tryParseUpstreamErrorPayload, createExpressStreamHandler, createExpressLogStreamHandler } = require('./core.js');
function tryParseJson(text) {
if (typeof text !== 'string') return null;
const trimmed = text.trim();
if (!trimmed) return null;
try {
return JSON.parse(trimmed);
} catch {
return null;
}
}
function tryParseLooseJson(text) {
// Best-effort recovery for PowerShell/curl quoting issues where JSON quotes are stripped,
// e.g. {prompt:test} or {model:qwen3.5-plus,n:2}.
// This keeps strict JSON behavior for normal clients, while making local debugging less painful.
if (typeof text !== 'string') return null;
let s = text.trim();
if (!s) return null;
if (!((s.startsWith('{') && s.endsWith('}')) || (s.startsWith('[') && s.endsWith(']')))) return null;
// Quote unquoted object keys: {a:1, b:2} -> {"a":1, "b":2}
s = s.replace(/([,{]\s*)([A-Za-z_][A-Za-z0-9_]*)(\s*:)/g, '$1"$2"$3');
// Quote bare values after ':' when they are not valid JSON primitives.
s = s.replace(/(:\s*)([^\s"\[{][^,}\]]*)/g, (match, prefix, rawValue) => {
const value = String(rawValue || '').trim();
if (!value) return match;
if (value.startsWith('"') || value.startsWith('{') || value.startsWith('[')) return match;
const lowered = value.toLowerCase();
if (lowered === 'true' || lowered === 'false' || lowered === 'null') return `${prefix}${lowered}`;
if (/^-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(value)) return `${prefix}${value}`;
return `${prefix}${JSON.stringify(value)}`;
});
return tryParseJson(s);
}
function logRequestPathBegin(runtime, path) {
console.log(`[qwen2api][${runtime}][request.begin] path=${path}`);
}
function isHuggingFaceRuntime() {
const hasPrimarySpaceId = Boolean(process.env.SPACE_ID);
const hasAuthorRepo = Boolean(process.env.SPACE_AUTHOR_NAME && process.env.SPACE_REPO_NAME);
const hasCreatorId = Boolean(process.env.SPACES_CREATOR_USER_ID);
return Boolean(
hasPrimarySpaceId ||
hasAuthorRepo ||
hasCreatorId ||
process.env.HF_SPACE_ID ||
process.env.HF_HOME ||
process.env.HUGGINGFACE_SPACE_ID
);
}
function patchDnsForHuggingFace() {
if (!isHuggingFaceRuntime()) return;
if (process.platform !== 'linux') return;
const fs = require('fs');
const resolvPath = '/etc/resolv.conf';
const backupPath = '/etc/resolv.conf.bak';
try {
if (!fs.existsSync(resolvPath)) {
console.log('[qwen2api][startup][dns] /etc/resolv.conf 不存在,跳过');
return;
}
const stat = fs.lstatSync(resolvPath);
if (!stat.isFile()) {
console.log('[qwen2api][startup][dns] /etc/resolv.conf 非普通文件,跳过');
return;
}
const original = fs.readFileSync(resolvPath, 'utf8');
if (!fs.existsSync(backupPath)) {
fs.writeFileSync(backupPath, original, 'utf8');
console.log('✅ 已备份 /etc/resolv.conf 到 /etc/resolv.conf.bak');
}
let resolvContent = original;
let changed = false;
if (!/\b8\.8\.8\.8\b/.test(resolvContent)) {
resolvContent = `nameserver 8.8.8.8\n${resolvContent}`;
changed = true;
console.log('✅ 已添加 DNS 8.8.8.8');
}
if (!/\b8\.8\.4\.4\b/.test(resolvContent)) {
const lines = resolvContent.split(/\r?\n/);
lines.splice(1, 0, 'nameserver 8.8.4.4');
resolvContent = lines.join('\n');
changed = true;
console.log('✅ 已添加 DNS 8.8.4.4');
}
if (!changed) {
console.log('[qwen2api][startup][dns] DNS 已包含 8.8.8.8 / 8.8.4.4,无需修改');
return;
}
if (!resolvContent.endsWith('\n')) {
resolvContent += '\n';
}
fs.writeFileSync(resolvPath, resolvContent, 'utf8');
} catch (err) {
console.log(`[qwen2api][startup][dns] 跳过 DNS 配置: ${err && err.message ? err.message : String(err)}`);
}
}
// ============================================
// Serverless Handler (Vercel / Netlify)
// ============================================
async function serverlessHandler(req, res) {
if (req.method === 'OPTIONS') {
if (res) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
return res.status(200).end();
}
return createResponse('', 200);
}
const authHeader = req.headers?.authorization || req.headers?.Authorization || '';
const path = req.url || req.path || '';
let pathname = path;
try {
pathname = new URL(path, 'http://localhost').pathname;
} catch {}
const netlifyFnPrefix = '/.netlify/functions/api';
const apiPrefix = '/api';
const strippedFnPath = pathname === netlifyFnPrefix
? '/'
: (pathname.startsWith(netlifyFnPrefix + '/') ? pathname.slice(netlifyFnPrefix.length) : pathname);
const normalizedPathname = strippedFnPath === apiPrefix
? '/'
: (strippedFnPath.startsWith(apiPrefix + '/') ? strippedFnPath.slice(apiPrefix.length) : strippedFnPath);
if (req.method === 'GET' && normalizedPathname === '/v1/models') {
const result = await handleModels(authHeader);
if (res) return res.status(result.statusCode).set(result.headers).send(result.body);
return result;
}
if (req.method === 'POST' && normalizedPathname === '/v1/chat/completions/log') {
logRequestPathBegin('serverless', normalizedPathname);
let body;
try {
if (typeof req.body === 'string') {
body = tryParseJson(req.body) || tryParseLooseJson(req.body) || {};
} else {
body = req.body || {};
}
} catch {
const bad = createResponse({ error: { message: 'Invalid JSON body.', type: 'invalid_request_error' } }, 400);
if (res) return res.status(bad.statusCode).set(bad.headers).send(bad.body);
return bad;
}
const result = await handleChatCompletionsWithLogs(body, authHeader);
if (res) {
if (result && result.body && result.headers && String(result.headers['Content-Type'] || '').indexOf('text/event-stream') === 0) {
res.status(result.statusCode).set(result.headers).send(result.body);
return;
}
return res.status(result.statusCode).set(result.headers).send(result.body);
}
return result;
}
if (req.method === 'POST' && normalizedPathname === '/v1/chat/completions') {
logRequestPathBegin('serverless', normalizedPathname);
let body;
try {
if (typeof req.body === 'string') {
body = tryParseJson(req.body) || tryParseLooseJson(req.body) || {};
} else {
body = req.body || {};
}
} catch {
const bad = createResponse({ error: { message: 'Invalid JSON body.', type: 'invalid_request_error' } }, 400);
if (res) return res.status(bad.statusCode).set(bad.headers).send(bad.body);
return bad;
}
const result = await handleChatCompletions(body, authHeader);
if (res) {
if (result && result.body && result.headers && String(result.headers['Content-Type'] || '').indexOf('text/event-stream') === 0) {
res.status(result.statusCode).set(result.headers).send(result.body);
return;
}
return res.status(result.statusCode).set(result.headers).send(result.body);
}
return result;
}
if (req.method === 'POST' && normalizedPathname === '/v1/images/generations') {
logRequestPathBegin('serverless', normalizedPathname);
let body;
try {
if (typeof req.body === 'string') {
body = tryParseJson(req.body) || tryParseLooseJson(req.body) || {};
} else {
body = req.body || {};
}
} catch {
const bad = createResponse({ error: { message: 'Invalid JSON body.', type: 'invalid_request_error' } }, 400);
if (res) return res.status(bad.statusCode).set(bad.headers).send(bad.body);
return bad;
}
const result = await handleImageGenerations(body, authHeader);
if (res) return res.status(result.statusCode).set(result.headers).send(result.body);
return result;
}
if (req.method === 'GET' && (normalizedPathname === '/chat' || normalizedPathname === '/chat/')) {
const result = handleChatPage();
if (res) return res.status(200).set(result.headers).send(result.body);
return result;
}
if (req.method === 'GET' && normalizedPathname === '/') {
const result = handleRoot();
if (res) return res.status(200).set(result.headers).send(result.body);
return result;
}
return res ? res.status(404).json({ error: { message: 'Not found', type: 'invalid_request_error' } }) : createResponse({ error: { message: 'Not found', type: 'invalid_request_error' } }, 404);
}
// ============================================
// Express Server (Docker / 本地开发)
// ============================================
function startExpressServer() {
patchDnsForHuggingFace();
const express = require('express');
const app = express();
const jsonLimit = process.env.JSON_BODY_LIMIT || '100mb';
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
if (req.method === 'OPTIONS') {
return res.status(200).end();
}
next();
});
app.use(express.json({
limit: jsonLimit,
verify: (req, res, buf) => {
try {
req.rawBody = buf ? buf.toString('utf8') : '';
} catch {
req.rawBody = '';
}
}
}));
// req.rawBody is captured via express.json verify.
app.use((error, req, res, next) => {
if (!error) return next();
if (error.type === 'entity.too.large' || error.status === 413) {
return res.status(413).json({
error: {
message: `Payload too large. Current JSON body limit is ${jsonLimit}. You can increase it with JSON_BODY_LIMIT.`,
type: 'invalid_request_error',
},
});
}
if (error.type === 'entity.parse.failed' || error.status === 400) {
const raw = typeof req.rawBody === 'string' ? req.rawBody : '';
const salvaged = tryParseLooseJson(raw);
if (salvaged && typeof salvaged === 'object') {
// Replace body and continue to route handler.
req.body = salvaged;
return next();
}
return res.status(400).json({
error: {
message: 'Invalid JSON body.',
type: 'invalid_request_error',
},
});
}
return next(error);
});
// Token 验证中间件
function authMiddleware(req, res, next) {
if (!validateToken(req.headers.authorization)) {
return res.status(401).json({ error: { message: 'Incorrect API key provided.', type: 'invalid_request_error' } });
}
next();
}
app.get('/v1/models', authMiddleware, async (req, res) => {
const result = await handleModels(req.headers.authorization);
res.status(result.statusCode).set(result.headers).send(result.body);
});
app.post('/v1/chat/completions', authMiddleware, async (req, res) => {
logRequestPathBegin('express', req.path || '/v1/chat/completions');
const result = await handleChatCompletions(req.body, req.headers.authorization, null, createExpressStreamHandler(res));
if (result && typeof result.statusCode === 'number') {
res.status(result.statusCode).set(result.headers).send(result.body);
}
});
app.post('/v1/chat/completions/log', authMiddleware, async (req, res) => {
logRequestPathBegin('express', req.path || '/v1/chat/completions/log');
const result = await handleChatCompletionsWithLogs(req.body, req.headers.authorization, null, createExpressLogStreamHandler(res));
if (res.headersSent) {
if (!res.writableEnded && result && typeof result.statusCode === 'number') {
let payload = { error: { message: `HTTP ${result.statusCode}`, type: 'api_error' } };
try {
const parsed = typeof result.body === 'string' ? JSON.parse(result.body) : result.body;
if (parsed && parsed.error) {
payload = parsed;
} else if (result.statusCode >= 200 && result.statusCode < 300 && parsed) {
// 非流式成功响应(stream 未传或为 false):日志事件已开始 SSE,
// 将完整 completion 作为 data 事件输出,保证内容仍能送达。
payload = parsed;
}
} catch {}
res.write(`data: ${JSON.stringify(payload)}\n\n`);
res.write('data: [DONE]\n\n');
res.end();
}
return;
}
if (result && typeof result.statusCode === 'number') {
res.status(result.statusCode).set(result.headers).send(result.body);
}
});
app.post('/v1/images/generations', authMiddleware, async (req, res) => {
logRequestPathBegin('express', req.path || '/v1/images/generations');
const result = await handleImageGenerations(req.body, req.headers.authorization);
res.status(result.statusCode).set(result.headers).send(result.body);
});
app.get('/', (req, res) => {
const result = handleRoot();
res.status(200).set(result.headers).send(result.body);
});
app.get('/chat', (req, res) => {
const result = handleChatPage();
res.status(200).set(result.headers).send(result.body);
});
app.get('/chat/', (req, res) => {
const result = handleChatPage();
res.status(200).set(result.headers).send(result.body);
});
const PORT = process.env.PORT || 8765;
app.listen(PORT, '0.0.0.0', () => console.log(`Qwen2API server running on port ${PORT}`));
}
// ============================================
// 导出 & 入口判断
// ============================================
module.exports = serverlessHandler;
module.exports.handleModels = handleModels;
module.exports.handleChatCompletions = handleChatCompletions;
module.exports.handleChatCompletionsWithLogs = handleChatCompletionsWithLogs;
module.exports.handleRoot = handleRoot;
module.exports.createResponse = createResponse;
const isServerless = process.env.VERCEL === '1' || process.env.NETLIFY === 'true';
if (!isServerless && require.main === module) {
startExpressServer();
}