forked from xiangsx/gpt4free-ts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.ts
403 lines (388 loc) · 11 KB
/
router.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
import Koa, { Context, Middleware, Next } from 'koa';
import {
ChatRequest,
ChatResponse,
countMessagesToken,
Message,
ModelType,
Site,
} from './model/base';
import {
ClaudeEventStream,
ComError,
Event,
EventStream,
getTokenCount,
OpenaiEventStream,
parseJSON,
randomStr,
ThroughEventStream,
} from './utils';
import { ChatModelFactory } from './model';
import moment from 'moment/moment';
import cors from '@koa/cors';
import Router from 'koa-router';
import bodyParser from 'koa-bodyparser';
import { randomUUID } from 'crypto';
import { chatModel } from './model';
import { TraceLogger } from './utils/log';
import { end } from 'cheerio/lib/api/traversing';
import apm from 'elastic-apm-node';
const supportsHandler = async (ctx: Context) => {
const result: Support[] = [];
for (const key in Site) {
//@ts-ignore
const site = Site[key];
//@ts-ignore
const chat = chatModel.get(site);
const support: Support = { site: site, models: [] };
for (const mKey in ModelType) {
//@ts-ignore
const model = ModelType[mKey];
//@ts-ignore
if (chat?.support(model)) {
support.models.push(model);
}
}
result.push(support);
}
ctx.body = result;
};
const errorHandler = async (ctx: Context, next: Next) => {
try {
await next();
} catch (err: any) {
ctx.logger?.info(err.message, {
trace_label: 'error',
...(ctx.query as any),
...(ctx.request.body as any),
...(ctx.params as any),
});
ctx.body = { error: { message: err.message } };
ctx.status = err.status || ComError.Status.InternalServerError;
}
};
interface AskReq extends ChatRequest {
site: Site;
}
interface AskRes extends ChatResponse {}
async function checkApiKey(ctx: Context, next: Next) {
let secret = '';
const authorStr =
ctx.request.headers.authorization || ctx.request.headers['x-api-key'];
secret = ((authorStr as string) || '').replace(/Bearer /, '');
ctx.query = { ...ctx.query, secret };
if (!process.env.API_KEY) {
await next();
return;
}
if (secret !== process.env.API_KEY) {
throw new ComError('invalid api key', 401);
}
await next();
}
const AskHandle: Middleware = async (ctx) => {
const {
prompt,
model = ModelType.GPT3p5Turbo,
site = Site.You,
...rest
} = {
...(ctx.query as any),
...(ctx.request.body as any),
...(ctx.params as any),
} as AskReq;
if (model !== ModelType.GetGizmoInfo && !prompt) {
throw new ComError(`need prompt in query`, ComError.Status.BadRequest);
}
const chat = chatModel.get(site);
if (!chat) {
throw new ComError(`not support site: ${site} `, ComError.Status.NotFound);
}
let req: ChatRequest = {
...rest,
prompt,
messages: parseJSON<Message[]>(prompt, [{ role: 'user', content: prompt }]),
model,
};
if (typeof req.messages !== 'object') {
// 数值类型parseJSON后为number
req.messages = [{ role: 'user', content: prompt }];
}
req = await chat.preHandle(req);
const data = await chat.ask(req);
if (data && data.error) {
ctx.status = 500;
}
req.messages.push({ role: 'assistant', content: data.content || '' });
console.debug(req.messages);
ctx.body = data;
return req;
};
const AskStreamHandle: (ESType: new () => EventStream) => Middleware =
(ESType) => async (ctx) => {
const {
prompt,
model = ModelType.GPT3p5Turbo,
site = Site.You,
...rest
} = {
...(ctx.query as any),
...(ctx.request.body as any),
...(ctx.params as any),
} as AskReq;
apm.currentTransaction?.addLabels({ site, model }, true);
if (model !== ModelType.GetGizmoInfo && !prompt) {
throw new ComError(`need prompt in query`, ComError.Status.BadRequest);
}
const chat = chatModel.get(site);
if (!chat) {
throw new ComError(
`not support site: ${site} `,
ComError.Status.NotFound,
);
}
let req: ChatRequest = {
...rest,
prompt,
messages: parseJSON<Message[]>(prompt, [
{ role: 'user', content: prompt },
]),
model,
};
if (typeof req.messages !== 'object') {
req.messages = [{ role: 'user', content: prompt }];
}
let stream = new ESType();
stream.setModel(req.model);
req = await chat.preHandle(req, { stream });
ctx.logger.info('start', {
model,
req: ctx.req,
res: ctx.res,
trace_label: 'start',
});
let ok = true;
const timeout = setTimeout(() => {
stream.write(Event.error, { error: 'timeout' });
stream.write(Event.done, { content: '' });
stream.end();
}, 120 * 1000);
const input = req.messages;
let output = '';
return (() =>
new Promise<void>(async (resolve, reject) => {
try {
const es = new ThroughEventStream(
(event, data: any) => {
switch (event) {
case Event.error:
ctx.logger.info(data.error, {
req: ctx.req,
res: ctx.res,
trace_label: 'error',
});
clearTimeout(timeout);
if (data instanceof ComError) {
reject(data);
return;
}
ok = false;
reject(
new ComError(
(data as any)?.error || 'unknown error',
(data as any)?.status ||
ComError.Status.InternalServerError,
),
);
break;
default:
if (!ctx.body && !data.content) {
break;
}
clearTimeout(timeout);
if (!ok) {
break;
}
if (!ctx.body) {
ctx.set({
'Content-Type': 'text/event-stream;charset=utf-8',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
});
ctx.body = stream.stream();
ctx.logger.info('recv', {
model,
req: ctx.req,
res: ctx.res,
trace_label: 'recv',
});
}
resolve();
stream.write(event, data);
output += (data as any).content || '';
break;
}
},
() => {
if (!ok) {
return;
}
input.push({ role: 'assistant', content: output });
delete (req as any).prompt;
ctx.logger.info(JSON.stringify(req), {
model,
req: ctx.req,
res: ctx.res,
trace_label: 'end',
});
stream.end();
},
);
await chat.askStream(req, es).catch((err) => {
clearTimeout(timeout);
es.destroy();
reject(err);
});
} catch (e) {
reject(e);
}
}))();
};
interface OpenAIReq {
site: Site;
stream: boolean;
model: ModelType;
messages: Message[];
}
interface ClaudeReq {
site: Site;
stream: boolean;
model: ModelType;
prompt: string;
}
interface Support {
site: string;
models: string[];
}
const openAIHandle: Middleware = async (ctx, next) => {
const { stream, messages, model } = {
...(ctx.query as any),
...(ctx.request.body as any),
...(ctx.params as any),
} as OpenAIReq;
(ctx.request.body as any).prompt = JSON.stringify(
(ctx.request.body as any).messages,
);
if (stream) {
await AskStreamHandle(OpenaiEventStream)(ctx, next);
return;
}
const req: ChatRequest = await AskHandle(ctx, next);
let reqLen = countMessagesToken(messages);
const tileSize = 512;
const tokensPerTile = 170;
for (const v of req.images || []) {
const tilesForWidth = Math.ceil(v.width / tileSize);
const tilesForHeight = Math.ceil(v.height / tileSize);
const totalTiles = tilesForWidth * tilesForHeight;
const totalTokens = 85 + tokensPerTile * totalTiles;
reqLen += totalTokens;
}
const completion_tokens = getTokenCount(ctx.body.content || '');
ctx.body = {
id: 'chatcmpl-' + '89D' + randomStr(26),
object: 'chat.completion',
created: moment().unix(),
model,
choices: [
{
index: 0,
message: {
role: 'assistant',
...ctx.body,
},
finish_reason: 'stop',
},
],
usage: {
// 官方默认所有请求token都+7
prompt_tokens: 7 + reqLen,
completion_tokens,
total_tokens: reqLen + completion_tokens,
},
};
};
const claudeHandle: Middleware = async (ctx, next) => {
const { stream, model } = {
...(ctx.query as any),
...(ctx.request.body as any),
...(ctx.params as any),
} as ClaudeReq;
if (stream) {
await AskStreamHandle(ClaudeEventStream)(ctx, next);
return;
}
await AskHandle(ctx, next);
ctx.body = {
completion: ctx.body.content,
stop_reason: 'stop_sequence',
model: model,
stop: '\n\nHuman:',
log_id: randomStr(64).toLowerCase(),
};
};
const audioHandle: Middleware = async (ctx, next) => {
const { site, ...req } = {
...(ctx.query as any),
...(ctx.request.body as any),
...(ctx.params as any),
} as any;
const chat = chatModel.get(site);
if (!chat) {
throw new ComError(`not support site: ${site} `, ComError.Status.NotFound);
}
await chat.speech(ctx, req);
};
const imageGenHandle: Middleware = async (ctx, next) => {
const { site, ...req } = {
...(ctx.query as any),
...(ctx.request.body as any),
...(ctx.params as any),
} as any;
const chat = chatModel.get(site);
if (!chat) {
throw new ComError(`not support site: ${site} `, ComError.Status.NotFound);
}
await chat.generations(ctx, req);
};
export const registerApp = () => {
const app = new Koa();
app.use(cors());
const router = new Router();
app.use(async (ctx, next) => {
ctx.logger = new TraceLogger();
await next();
});
app.use(errorHandler);
app.use(bodyParser({ jsonLimit: '10mb' }));
app.use(checkApiKey);
router.get('/supports', supportsHandler);
router.get('/ask', AskHandle);
router.post('/ask', AskHandle);
router.get('/ask/stream', AskStreamHandle(EventStream));
router.post('/ask/stream', AskStreamHandle(EventStream));
router.post('/v1/chat/completions', openAIHandle);
router.post('/:site/v1/chat/completions', openAIHandle);
router.post('/v1/complete', claudeHandle);
router.post('/:site/v1/complete', claudeHandle);
router.post('/v1/audio/speech', audioHandle);
router.post('/:site/v1/audio/speech', audioHandle);
router.post('/:site/v1/images/generations', imageGenHandle);
app.use(router.routes());
const port = +(process.env.PORT || 3000);
const server = app.listen(port, () => {
console.log(`Now listening: 127.0.0.1:${port}`);
});
console.log(`Worker ${process.pid} started`);
};