-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.mjs
More file actions
370 lines (313 loc) · 12.8 KB
/
index.mjs
File metadata and controls
370 lines (313 loc) · 12.8 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
import {
calculateTotalProperty,
decrypt,
hasCode,
fetchOnRequestHandler,
fetchOnResponseHandler,
buildSystemContent,
executeHandler,
verifyToken,
runDevServer,
send,
setHead,
warmup,
handleEmptyBody,
handleNoMessages,
getSearchResults,
getItemsAsString,
createChat,
listChats,
deleteChat,
getChatMessages,
chatAddMessages,
chatDeleteMessage,
updateChat,
chatEditMessage,
getAllUnreadMessages,
getUnreadMessages,
deleteUnreadMessages,
chatMessageAddReaction,
chatMessageRemoveReaction,
chatStream,
handleOnResponse,
sha256,
APIKeyPermissions,
encryptMessages,
getChat, ChatModels, createAPIKey, getAPIKeys, deleteAPIKey, loadEnv, loadChatModels
} from "./utils.mjs";
import jwt from "jsonwebtoken";
const CHAT_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEcERRIkiUsAMvF8n5WzZ4JUppCJGS
/u3p3yGMu1SbG2Knmu5biAC7sQk9lbGEvnWW8QwnU+GEe8dOjoDOCxchOQ==
-----END PUBLIC KEY-----`;
async function handleDefault(event, res) {
let start = +new Date();
if (event?.queryStringParameters?.warmup) return warmup(res)
if (!event.body) return await handleEmptyBody(res);
const params = JSON.parse(event.body);
let {
AESKey, injectedItems, token, chatPayload,
action, title, messages, chatId, msgId, content, emojiId,
limit, lastEvaluatedKey, predefinedAccountId, chatInstructions,
chatIcon, chatModel, instructionSuffix, rawPrompt,
injectedKBData, APIKeyName, apiKey, chatJWT
} = params;
let kbUserId = null;
let myUserId = null;
let kbId = null;
try {
if (params?.apiKey) {
// @Todo apiKey still requires injectedKBData for On Premises instance to support requests by apiKey
const [res] = await Promise.all([
APIKeyPermissions(params.kbId, sha256(params.apiKey)),
]);
if (res?.kbUserId && res?.permissions?.resources === '*') {
kbId = params.kbId
kbUserId = res?.kbUserId
myUserId = res?.kbUserId
AESKey = res?.AESKey;
if (messages && AESKey) messages = encryptMessages(messages, AESKey)
} else {
setHead(res, 403);
await send(res, { statusCode: 403, error: 'Insufficient API Permissions' });
return res.end();
}
} else if (chatJWT) {
const decoded = jwt.verify(chatJWT, CHAT_PUBLIC_KEY, { algorithms: ['ES256'] });
myUserId = decoded.kbUserId;
kbUserId = decoded.kbUserId;
kbId = decoded?.kbId;
} else {
const decoded = await verifyToken(token);
kbUserId = decoded.kbUserId
myUserId = decoded.myUserId
kbId = decoded.kbId
}
if (!kbUserId || !kbId) throw new Error('missing kbUserId or kbId');
} catch (e) {
setHead(res, 401);
await send(res, {statusCode: 401, error: params?.apiKey ? 'invalid apiKey' : 'invalid JWT'});
return res.end();
}
let kbDataLoadedBeforeAction = injectedKBData;
try {
const params = { kbId, chatId, myUserId };
const lastMessage = messages?.[messages.length - 1];
if (lastMessage?.content?.slice(-10)) params.content = lastMessage.content.slice(-10);
if (lastMessage?.role) params.role = lastMessage.role;
if (action) params.action = action;
if (params?.apiKey) params.fromAPI = true;
} catch (e) {}
/**
* Start of Actions APIs
*/
if (action === 'createChat') {
// ACL attribute_not_exists(chatId)
const data = await createChat({kbId, title, messages, chatId})
setHead(res, 200);
await send(res, {status: 200, data});
} else if (action === 'deleteChat') {
// ACL deleted by {kbId, chatId}
const data = await deleteChat({kbId, chatId})
setHead(res, 200);
await send(res, {status: 200, data});
} else if (action === 'listChats') {
// ACL listed by {kbId}
const data = await listChats(kbId)
setHead(res, 200);
await send(res, {status: 200, data});
} else if (action === 'getChat') {
// ACL listed by {kbId}
const data = await getChat(kbId, chatId)
setHead(res, 200);
await send(res, {status: 200, data});
}
else if (action === 'getChatMessages') {
// ACL listed by {chatId, kbId}
const data = await getChatMessages({chatId, kbId, myUserId, limit, lastEvaluatedKey})
setHead(res, 200);
await send(res, {status: 200, data});
} else if (action === 'chatAddMessages' && chatId) {
const data = await chatAddMessages({chatId, messages, kbId, kbDataLoadedBeforeAction})
setHead(res, 200);
await send(res, {status: 200, data});
} else if (action === 'chatDeleteMessage') {
// ACL ConditionExpression: 'kbId = :kbId'
const data = await chatDeleteMessage({chatId, msgId, kbId})
setHead(res, 200);
await send(res, {status: 200, data});
} else if (action === 'updateChat') {
const data = await updateChat({ kbId, title, chatId, chatInstructions, chatIcon, chatModel });
setHead(res, 200);
await send(res, { status: 200, data });
}
// ACL ConditionExpression: 'kbId = :kbIdVal',
else if (action === 'chatEditMessage') {
const data = await chatEditMessage({ kbId, chatId, msgId, content });
setHead(res, 200);
await send(res, { status: 200, data });
}
// ACL partition key `${userId}#${kbId}`,
else if (action === 'getAllUnreadMessages') {
const data = await getAllUnreadMessages(myUserId, kbId);
setHead(res, 200);
await send(res, { status: 200, data });
}
// ACL partition key `${userId}#${kbId}`,
else if (action === 'getUnreadMessages') {
const data = await getUnreadMessages(myUserId, kbId, chatId);
setHead(res, 200);
await send(res, { status: 200, data });
}
// ACL myUserId, kbId, chatId
else if (action === 'deleteUnreadMessages') {
const data = await deleteUnreadMessages(myUserId, kbId, chatId);
setHead(res, 200);
await send(res, { status: 200, data });
}
// ACL myUserId, kbId, chatId
else if (action === 'chatMessageAddReaction') {
const data = await chatMessageAddReaction({ kbId, chatId, msgId, userId: myUserId, emojiId });
setHead(res, 200);
await send(res, { status: 200, data });
}
// ACL myUserId, kbId, chatId
else if (action === 'chatMessageRemoveReaction') {
const data = await chatMessageRemoveReaction({ kbId, chatId, msgId, userId: myUserId, emojiId });
setHead(res, 200);
await send(res, { status: 200, data });
}
// ACL myUserId, kbId, chatId
else if (action === 'getOnPremisesChatModels') {
setHead(res, 200);
await send(res, { status: 200, data: ChatModels });
}
else if (action === 'createAPIKey') {
const data = await createAPIKey(kbId, APIKeyName, APIKeyPermissions, kbUserId, myUserId, AESKey);
setHead(res, 200);
await send(res, { status: 200, data });
}
else if (action === 'getAPIKeys') {
const data = await getAPIKeys(kbId);
setHead(res, 200);
await send(res, { status: 200, data });
}
else if (action === 'deleteAPIKey') {
const data = await deleteAPIKey(kbId, apiKey);
setHead(res, 200);
await send(res, { status: 200, data });
}
// console.log(`${action} overhead:`, +new Date() - start)
if (action) return res.end();
// End of Actions APIs
/**
* Chat Stream API Starts Here
*/
let payload = chatPayload;
let benchmarkData = {};
// Here to handle here instructions per chat
let promises = [
fetchOnRequestHandler(kbId),
fetchOnResponseHandler(kbId)
];
if (chatId) {
promises.push(getChat(kbId, chatId));
}
let [requestHandler, responseHandler, chatData] = await Promise.all(promises);
let kbData = injectedKBData;
// override chat model kbData
if (kbData?.model && payload?.model !== kbData?.model) payload.model = kbData.model
// override chat model chatData
if (chatData?.chatModel && payload?.model !== chatData?.chatModel) payload.model = chatData.chatModel
// console.log('overhead: ', +new Date() - start)
if (!kbData?.accountId || kbData?.accountId !== predefinedAccountId) throw new Error('accountId mismatch');
if (!kbData) throw new Error('unable to get KB');
benchmarkData.getKB = +new Date() - start;
let decryptedKBInstructions = '';
// append chat instructions
if (chatData?.chatInstructions) decryptedKBInstructions = await decrypt(chatData.chatInstructions, AESKey) + '\n\n'
decryptedKBInstructions += await decrypt(kbData.kbInstructions, AESKey);
let count = { id: 0 };
if (!rawPrompt && hasCode(requestHandler)) {
const currentId = ++count.id;
await send(res, { id: currentId, content: JSON.stringify({ _meta_type: 'EVENT_STARTED', metaEvent: 'onRequest' }), role: 'system' });
try {
let response = await executeHandler(requestHandler, { payload: {...payload, chatId} }, kbData, AESKey);
const currentId = ++count.id;
if (response?.type === 'CONTINUE') {
await send(res, { id: currentId, content: JSON.stringify({ type: 'CONTINUE', _meta_type: "EVENT_FINISHED", _event: 'onRequest' }), role: 'system' });
} else {
const content = typeof response === "string"
? JSON.stringify({type: "PLAIN_TEXT", data: response, _meta_type: "EVENT_FINISHED", _event: 'onRequest'})
: JSON.stringify({...response, _meta_type: "EVENT_FINISHED", _event: 'onRequest'})
const currentId = ++count.id;
await send(res, { id: currentId, content, role: 'system' });
await send(res, { done: currentId });
return res.end();
}
} catch (e) {
const currentId = ++count.id;
await send(res, { id: currentId, content: JSON.stringify({error: e.message, _meta_type: "EVENT_FINISHED", _event: 'onResponse'}), role: 'system' });
await send(res, { done: currentId });
return res.end()
}
}
if (!payload.messages[0]) return handleNoMessages(res)
let instructionSuffixString = null;
if (instructionSuffix) {
instructionSuffixString = instructionSuffix;
} else {
const {searchResults, filteredInjectedItems} = await getSearchResults({payload, injectedItems, token, kbId, kbUserId})
benchmarkData = {...benchmarkData, ...searchResults.benchmarkData}
if (searchResults.filtered.length) {
instructionSuffixString = await getItemsAsString({searchResults, kbId, filteredInjectedItems, AESKey, benchmarkData})
}
}
// put instructions and items to the prompt
payload.messages = [{ role: 'system', content: buildSystemContent(decryptedKBInstructions, instructionSuffixString, kbData) }, ...payload.messages,];
if (!rawPrompt) {
await send(res, {
benchmarkData: calculateTotalProperty(benchmarkData),
userId: kbUserId,
});
}
const sendMessages = [];
try {
await chatStream({payload, kbData},
// on_start
async () => {
console.log(payload.messages?.length + ' messages sent to ' + payload?.model)
const currentId = ++count.id; // Increment and get the current ID atomically
await send(res, { id: currentId, content: '', role: 'assistant' });
sendMessages.push({ id: currentId, content: '', role: 'assistant' });
// on_delta
}, async (data) => {
const currentId = ++count.id; // Increment and get the current ID atomically
await send(res, { ...data, id: currentId });
sendMessages.push({ ...data, id: currentId });
// on_stop
}, async ({inputTokens, outputTokens}) => {
if (!rawPrompt) {
await handleOnResponse({count, res, token, payload, sendMessages, responseHandler, kbData, AESKey, chatId})
}
await send(res, {done: count.id});
res.end();
},
(err) => {
console.error(err)
}, // on_error
() => {} // on_close
);
} catch (error) {
console.error('An error occurred during the chat stream:', error);
await send(res, { error: error.message });
res.end();
}
}
async function wsHandler(message, ws) {
}
(async () => {
await loadEnv();
await loadChatModels();
runDevServer(handleDefault, wsHandler)
})();