forked from xiangsx/gpt4free-ts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
178 lines (164 loc) · 5.02 KB
/
index.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
import Koa, {Context, Middleware, Next} from 'koa';
import Router from 'koa-router'
import bodyParser from 'koa-bodyparser';
import cors from '@koa/cors'
import {ChatModelFactory, Site} from "./model";
import dotenv from 'dotenv';
import {ChatRequest, ChatResponse, Message, ModelType, PromptToString} from "./model/base";
import {Event, EventStream, getTokenSize, OpenaiEventStream, randomStr} from "./utils";
import moment from "moment";
process.setMaxListeners(30); // 将限制提高到20个
dotenv.config();
const app = new Koa();
app.use(cors())
const router = new Router();
const errorHandler = async (ctx: Context, next: Next) => {
try {
await next();
} catch (err: any) {
console.error(err);
ctx.body = JSON.stringify(err);
ctx.res.end();
}
};
app.use(errorHandler);
app.use(bodyParser({jsonLimit: '10mb'}));
const chatModel = new ChatModelFactory();
interface AskReq extends ChatRequest {
site: Site;
}
interface AskRes extends ChatResponse {
}
const AskHandle: Middleware = async (ctx) => {
const {
prompt,
model = ModelType.GPT3p5Turbo,
site = Site.You
} = {...ctx.query as any, ...ctx.request.body as any, ...ctx.params as any} as AskReq;
if (!prompt) {
ctx.body = {error: `need prompt in query`} as AskRes;
return;
}
const chat = chatModel.get(site);
if (!chat) {
ctx.body = {error: `not support site: ${site} `} as AskRes;
return;
}
const tokenLimit = chat.support(model);
if (!tokenLimit) {
ctx.body = {error: `${site} not support model ${model}`} as AskRes;
return;
}
ctx.body = await chat.ask({prompt: PromptToString(prompt, tokenLimit), model});
}
const AskStreamHandle: (ESType: new () => EventStream) => Middleware = (ESType) => async (ctx) => {
const {
prompt,
model = ModelType.GPT3p5Turbo,
site = Site.You
} = {...ctx.query as any, ...ctx.request.body as any, ...ctx.params as any} as AskReq;
ctx.set({
"Content-Type": "text/event-stream;charset=utf-8",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
});
let es = new ESType();
ctx.body = es.stream();
if (!prompt) {
es.write(Event.error, {error: 'need prompt in query'})
es.end();
return;
}
const chat = chatModel.get(site);
if (!chat) {
es.write(Event.error, {error: `not support site: ${site} `})
es.end();
return;
}
const tokenLimit = chat.support(model);
if (!tokenLimit) {
es.write(Event.error, {error: `${site} not support model ${model}`})
es.end();
return;
}
await chat.askStream({prompt: PromptToString(prompt, tokenLimit), model}, es);
ctx.body = es.stream();
}
interface OpenAIReq {
site: Site;
stream: boolean;
model: ModelType;
messages: Message[];
}
interface Support {
site: string;
models: string[];
}
router.get('/supports', (ctx) => {
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;
});
router.get('/ask', AskHandle);
router.post('/ask', AskHandle);
router.get('/ask/stream', AskStreamHandle(EventStream))
router.post('/ask/stream', AskStreamHandle(EventStream))
const openAIHandle: Middleware = async (ctx, next) => {
const {stream} = {...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) {
AskStreamHandle(OpenaiEventStream)(ctx, next);
return;
}
await AskHandle(ctx, next);
console.log(ctx.body);
ctx.body = {
"id": `chatcmpl-${randomStr()}`,
"object": "chat.completion",
"created": moment().unix(),
"choices": [{
"index": 0,
"message": {
"role": "assistant",
"content": ctx.body.content,
},
"finish_reason": "stop"
}],
"usage": {
"prompt_tokens": 100,
"completion_tokens": getTokenSize(ctx.body.content),
"total_tokens": 100 + getTokenSize(ctx.body.content)
}
}
};
router.post('/v1/chat/completions', openAIHandle)
router.post('/:site/v1/chat/completions', openAIHandle)
app.use(router.routes());
(async () => {
const server = app.listen(3000, () => {
console.log("Now listening: 127.0.0.1:3000");
});
process.on('SIGINT', () => {
server.close(() => {
process.exit(0);
});
});
process.on('uncaughtException', (e) => {
console.error(e);
})
})()