-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathindex.js
341 lines (307 loc) · 9.15 KB
/
index.js
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
import express from 'express';
import cors from 'cors';
import IP from 'ip';
import swaggerJsdoc from 'swagger-jsdoc';
import swaggerUi from 'swagger-ui-express';
import { spawn } from 'child_process';
import modelsRoutes from './routes/modelsRoutes.js';
import chatRoutes from './routes/chatRoutes.js';
import chatRoutesGGML from './routes/chatRoutes-ggml.js';
import completionsRoutes from './routes/completionsRoutes.js';
import completionsRoutesGGML from './routes/completionsRoutes-ggml.js';
import embeddingsRoutes from './routes/embeddingsRoutes.js';
import { getHelpList, validateAndReturnUserArgs } from './defaults.js';
import { getInferenceEngine, getModelPath, stripAnsiCodes } from './utils.js';
import path from 'path';
const PORT = process.env.PORT || 443;
const isWin = process.platform === 'win32';
// Check that the user args are valid
const { errors, userArgs } = validateAndReturnUserArgs();
if (errors.length > 0) {
process.exit();
}
if (userArgs.includes('--help') || userArgs.includes('-h')) {
console.log('===== LIST OF AVAILABLE ARGS ======');
console.log(getHelpList);
console.log();
process.exit();
}
const getServerRunningMsg = () => {
const ipAddress = IP.address();
return `Server is listening on:
- http://localhost:${PORT}
- http://${ipAddress}:${PORT} (for other devices on the same network)
See Docs
- http://localhost:${PORT}/docs
Test your installation
- ${
isWin
? 'double click the scripts/test-installation.ps1 (powershell) or scripts/test-installation.bat (cmd) file'
: 'open another terminal window and run sh ./scripts/test-installation.sh'
}
See https://github.com/keldenl/gpt-llama.cpp#usage for more guidance.`;
};
const options = {
definition: {
openapi: '3.0.1',
info: {
title: 'gpt-llama.cpp',
version: '1.0.0',
description: 'Use llama.cpp in place of the OpenAi GPT API',
license: {
name: 'MIT',
url: 'https://spdx.org/licenses/MIT.html',
},
contact: {
name: 'Kelden',
url: 'https://github.com/keldenl',
},
},
basePath: '/',
components: {
securitySchemes: {
bearerAuth: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
},
},
},
security: [
{
bearerAuth: [],
},
],
servers: [
{
url: `http://localhost:${PORT}`,
},
],
},
apis: ['./routes/*.js'],
};
const specs = swaggerJsdoc(options);
global.serverBusy = false;
global.childProcess = undefined;
global.lastRequest = undefined;
const app = express();
app.use(cors());
app.use(express.json());
// MIDDLEWARE CODE TO LIMIT REQUESTS TO 1 AT A TIME
let requestQueue = [];
function processNextRequest() {
if (requestQueue.length === 0) {
return;
}
// check if server is currently processing a request
if (!global.serverBusy) {
let nextRequest = requestQueue.shift();
processRequest(nextRequest.req, nextRequest.res, nextRequest.next);
} else {
console.log('> SERVER BUSY, REQUEST QUEUED');
}
}
// create a function to process the requests
function processRequest(req, res, next) {
// do the work for this request here
console.log(`> PROCESSING NEXT REQUEST FOR ${req.url}`);
// call the next middleware
next();
}
// create a middleware function to handle incoming requests
function requestHandler(req, res, next) {
console.log('> REQUEST RECEIVED');
requestQueue.push({ req, res, next });
processNextRequest();
const jitter = Math.floor(Math.random() * 1000);
const busyInterval = setInterval(() => {
if (global.serverBusy) {
// still working on previos request
return;
}
console.log('> PROCESS COMPLETE');
clearInterval(busyInterval);
if (requestQueue.length > 0) {
console.log(
`> ${requestQueue.length} REQUEST(S) IN QUEUE. STARTING NEXT REQUEST...`
);
processNextRequest();
}
}, 2500 + jitter);
}
app.use(requestHandler);
app.use(
'/docs',
swaggerUi.serve,
swaggerUi.setup(specs, {
explorer: true,
})
);
app.use('/v1/models', modelsRoutes);
app.use('/v1/chat', (req, res, next) => {
const modelPath = getModelPath(req, res);
const inferenceEngine = getInferenceEngine(modelPath);
switch (inferenceEngine) {
case 'ggml':
console.log('> GGML DETECTED');
chatRoutesGGML(req, res, next);
break;
case 'llama.cpp':
console.log('> LLAMA.CPP DETECTED');
chatRoutes(req, res, next);
break;
default:
console.log('> NO INFERENCE ENGINE DETECTED, DEFAULTING TO LLAMA.CPP');
chatRoutes(req, res, next);
break;
}
});
app.use('/v1/completions', (req, res, next) => {
const modelPath = getModelPath(req, res);
const inferenceEngine = getInferenceEngine(modelPath);
switch (inferenceEngine) {
case 'ggml':
console.log('> GGML DETECTED');
completionsRoutesGGML(req, res, next);
break;
case 'llama.cpp':
console.log('> LLAMA.CPP DETECTED');
completionsRoutes(req, res, next);
break;
default:
console.log('> NO INFERENCE ENGINE DETECTED, DEFAULTING TO LLAMA.CPP');
completionsRoutes(req, res, next);
break;
}
});
app.use(/^\/v1(?:\/.+)?\/embeddings$/, embeddingsRoutes);
// app.post('/v1/images/generations', (req, res) => {
// global.serverBusy = true;
// // const modelId = req.body.model; // TODO: Implement model somehow
// const prompt = req.body.prompt;
// const scriptArgs = [
// '--resource-path',
// './models/Counterfeit-V3.0_split-einsum',
// ];
// const scriptPath = 'swift';
// // const prompt = 'red riding hood visiting grandma';
// const cwd = 'InferenceEngine/image/ml-stable-diffusion/';
// const seed = Math.floor(Math.random() * 10000);
// const commandArgs = [
// 'run',
// 'StableDiffusionSample',
// '--negative-prompt',
// 'EasyNegativeV2',
// '--guidance-scale',
// 10,
// '--step-count',
// 75,
// '--resource-path',
// 'models/Counterfeit-V3.0_split-einsum',
// '--seed',
// seed,
// prompt,
// ];
// global.childProcess = spawn(scriptPath, commandArgs, { cwd });
// console.log(`\n===== REQUEST =====`);
// console.log(`"${prompt}"`);
// let stdoutStream = global.childProcess.stdout;
// let stderrStream = global.childProcess.stderr;
// let lastErr = '';
// const stderr = new ReadableStream({
// start(controller) {
// const decoder = new TextDecoder();
// const onData = (chunk) => {
// const data = stripAnsiCodes(decoder.decode(chunk));
// lastErr = data;
// };
// const onClose = () => {
// console.error('\n===== STDERR =====');
// console.log('stderr Readable Stream: CLOSED');
// console.log(lastErr);
// controller.close();
// };
// const onError = (error) => {
// console.error('\n===== STDERR =====');
// console.log('stderr Readable Stream: ERROR');
// console.log(lastErr);
// console.log(error);
// controller.error(error);
// };
// stderrStream.on('data', onData);
// stderrStream.on('close', onClose);
// stderrStream.on('error', onError);
// },
// });
// const stdout = new ReadableStream({
// start(controller) {
// const decoder = new TextDecoder();
// const onData = (chunk) => {
// const data = stripAnsiCodes(decoder.decode(chunk));
// // process.stdout.write(data);
// // console.log(data)
// controller.enqueue(data);
// // if (!!data && data.includes('Saved')) {
// // const fileName = `${prompt.split(' ').join('_')}.${seed}.final.png`
// // console.log('filename: ', fileName)
// // console.log(data)
// // // console.log(data.split(' '))
// // // console.log(data.split(' ')[1])
// // }
// // controller.enqueue(
// // dataToCompletionResponse(data, promptTokens, completionTokens)
// // );
// };
// const onClose = () => {
// global.serverBusy = false;
// console.log('Readable Stream: CLOSED');
// controller.close();
// };
// const onError = (error) => {
// console.log('Readable Stream: ERROR');
// console.log(error);
// controller.error(error);
// };
// stdoutStream.on('data', onData);
// stdoutStream.on('close', onClose);
// stdoutStream.on('error', onError);
// },
// });
// const writable = new WritableStream({
// write(chunk) {
// // If we detect the stop prompt, stop generation
// if (!!chunk && chunk.includes('Saved')) {
// global.childProcess.kill('SIGINT');
// // const fileName = `${prompt.split(' ').join('_')}.${seed}.final.png`;
// console.log(`chunk: "${chunk}"`);
// console.log('Request DONE');
// const fileName = chunk.split("Saved ")[1].trim()
// console.log('filename: ', fileName);
// const dirName = path.resolve()
// res.status(200).json({
// data: [{ url: path.join(dirName, 'InferenceEngine', 'image', 'ml-stable-diffusion', fileName) }],
// });
// res.end();
// global.lastRequest = {
// type: 'image',
// prompt: prompt,
// };
// global.serverBusy = false;
// stdoutStream.removeAllListeners();
// } else {
// console.log('chunk: ', chunk);
// }
// },
// });
// stdout.pipeTo(writable);
// });
app.get('/', (req, res) =>
res.type('text/plain').send(`
################################################################################
### WELCOME TO GPT-LLAMA!!
################################################################################
${getServerRunningMsg()}`)
);
app.listen(PORT, () => {
console.log(getServerRunningMsg());
});