-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy.js
330 lines (290 loc) · 9.01 KB
/
proxy.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
const express = require('express');
const path = require('path');
const fs = require('fs');
const { randomUUID } = require('crypto');
const app = express();
const port = 3006;
const OLLAMA_URL = 'http://localhost:11434';
app.use(express.json())
app.post('/v1/models', (req, res) => {
// fetch ollama models
if(checkAuth(req, res)) {
fetch(OLLAMA_URL + '/api/tags')
.then((data) => {
res.status(200).json(data);
})
.catch((error) => {
res.status(500).json(error);
});
}
})
app.post('/api/chat', (req, res) => {
// rebuild the body to ensure everything is there.
const body = {
model: req.body.model,
messages: req.body.messages
}
if(req.body.format)
{
body.format = req.body.format
}
if(req.body.stream)
{
body.stream = req.body.stream
} else {
body.stream = false
}
if(req.body.max_tokens)
{
body.max_tokens = req.body.max_tokens
} else {
body.max_tokens = 4096
}
if(req.body.temperature)
{
body.temperature = req.body.temperature
} else {
body.temperature = 0.75
}
if(req.body.stop)
{
body.stop = req.body.stop
}
if(req.body.system)
{
body.system = req.body.system
} else {
body.system = 'You are a helpful AI assistant'
}
if(checkAuth(req, res)) {
fetchOllama(OLLAMA_URL+'/api/chat', body)
.then((data) => {
if (body.stream === true) {
// Send the chunks back to the client directly
res.write(data);
res.end(); // Make sure to end the response after the stream is complete
} else {
// JSON response for non-streaming case
res.status(200).json(data);
}
})
.catch((error) => {
console.error('Error:', error);
res.status(500).send('Internal Server Error');
});
} else {
res.status(401).send('Unauthorized');
}
});
app.post('/v1/chat/completions', (req, res) => {
// rebuild the body to ensure everything is there.
const body = {
model: req.body.model,
messages: req.body.messages
}
if(req.body.format)
{
body.format = req.body.format
}
if(req.body.stream)
{
body.stream = req.body.stream
} else {
body.stream = false
}
if(req.body.max_tokens)
{
body.max_tokens = req.body.max_tokens
} else {
body.max_tokens = 4096
}
if(req.body.temperature)
{
body.temperature = req.body.temperature
} else {
body.temperature = 0.75
}
if(req.body.stop)
{
body.stop = req.body.stop
}
if(req.body.system)
{
body.system = req.body.system
} else {
body.system = 'You are a helpful AI assistant'
}
if(checkAuth(req, res)) {
fetchOllama(OLLAMA_URL+'/v1/chat/completions', body)
.then((data) => {
if (body.stream === true) {
// Send the chunks back to the client directly
res.write(data);
res.end(); // Make sure to end the response after the stream is complete
} else {
// JSON response for non-streaming case
res.status(200).json(data);
}
})
.catch((error) => {
console.error('Error:', error);
res.status(500).send('Internal Server Error');
});
} else {
res.status(401).send('Unauthorized');
}
});
app.post('/api/generate', (req, res) => {
if(checkAuth(req, res)) {
const body = {
prompt: req.body.prompt,
model: req.body.model
}
if(req.body.format)
{
body.format = req.body.format
}
if(req.body.stream)
{
body.stream = req.body.stream
} else {
body.stream = false
}
if(req.body.max_tokens)
{
body.max_tokens = req.body.max_tokens
} else {
body.max_tokens = 4096
}
if(req.body.temperature)
{
body.temperature = req.body.temperature
} else {
body.temperature = 0.75
}
if(req.body.stop)
{
body.stop = req.body.stop
}
if(req.body.system)
{
body.system = req.body.system
} else {
body.system = 'You are a helpful AI assistant'
}
const url = OLLAMA_URL + '/api/generate';
fetchOllama(url, body)
.then((data) => {
if (req.body.stream === true) {
res.status(200).setHeader('Content-Type', 'application/json'); // Or adjust the Content-Type based on your needs
// In case of a streamed response, data is already emitted in chunks
// Send the chunks back to the client directly
res.write(data);
res.end(); // Make sure to end the response after the stream is complete
} else {
// JSON response for non-streaming case
res.status(200).json(data);
}
})
.catch((error) => {
console.error('Error:', error);
res.status(500).send('Internal Server Error');
});
} else {
res.status(401).send('Unauthorized');
}
})
// start your servers
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
async function checkAuth(req, res) {
// get token from req header "Authorization Bearer <token>"
const token = req.headers.authorization.split(' ')[1];
// trim up the whitespace around token
function trim(str) {
return str.replace(/^\s+|\s+$/g, '');
}
console.log("Token: ", token);
if (token) {
// check token
// look at authTokens.json
const authTokens = JSON.parse(fs.readFileSync(path.join(__dirname, 'authTokens.json'), 'utf8'));
if (authTokens.includes(trim(token))) {
// token is valid
return true;
} else {
res.status(401).send('Unauthorized');
}
} else {
res.status(401).send('Unauthorized');
}
}
async function fetchOllama(url, body) {
let isStreaming = false;
if(body.stream === true)
{
isStreaming = true;
}
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
});
if (isStreaming===false) {
// Just parse the full response if streaming is not required
// check body to see if `format` exists
if(body.format) {
return await response.text();
} else {
return await response.json();
}
} else {
// Handle streaming response
console.log("Guess we're streaming...");
const reader = response.body.getReader();
const decoder = new TextDecoder();
let result = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
// Decode the stream chunk and process it
result += decoder.decode(value, { stream: true });
console.log('Received chunk:', result); // Handle chunk here
}
// Process or return the full result when done
return result;
}
} catch (error) {
console.error('Error:', error);
return null;
}
}
// let's add a function, not using express that allows CLI input to generate API keys and puts them in authTokens.json
async function generateAPIKey() {
const uuid = randomUUID();
const key = `OLLAMA-${uuid}`;
const authTokens = JSON.parse(fs.readFileSync(path.join(__dirname, 'authTokens.json'), 'utf8'));
authTokens.push(key);
fs.writeFileSync(path.join(__dirname, 'authTokens.json'), JSON.stringify(authTokens));
console.log(`API key generated: ${key}`);
return key;
}
// start looking for commands from the CLI
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.on('line', (input) => {
if (input === 'exit') {
process.exit();
} else if (input === 'generateAPIKey') {
generateAPIKey();
} else {
console.log('Invalid command');
}
});