librechat-data-provider 0.2.5 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.es.js CHANGED
@@ -1,1215 +1,2 @@
1
- import axios from 'axios';
2
- import { z } from 'zod';
3
- import { useQueryClient, useMutation, useQuery } from '@tanstack/react-query';
4
-
5
- /******************************************************************************
6
- Copyright (c) Microsoft Corporation.
7
-
8
- Permission to use, copy, modify, and/or distribute this software for any
9
- purpose with or without fee is hereby granted.
10
-
11
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
12
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
14
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
15
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
16
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
17
- PERFORMANCE OF THIS SOFTWARE.
18
- ***************************************************************************** */
19
- /* global Reflect, Promise, SuppressedError, Symbol */
20
-
21
-
22
- var __assign = function() {
23
- __assign = Object.assign || function __assign(t) {
24
- for (var s, i = 1, n = arguments.length; i < n; i++) {
25
- s = arguments[i];
26
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
27
- }
28
- return t;
29
- };
30
- return __assign.apply(this, arguments);
31
- };
32
-
33
- function __awaiter(thisArg, _arguments, P, generator) {
34
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
35
- return new (P || (P = Promise))(function (resolve, reject) {
36
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
37
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
38
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
39
- step((generator = generator.apply(thisArg, _arguments || [])).next());
40
- });
41
- }
42
-
43
- function __generator(thisArg, body) {
44
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
45
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
46
- function verb(n) { return function (v) { return step([n, v]); }; }
47
- function step(op) {
48
- if (f) throw new TypeError("Generator is already executing.");
49
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
50
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
51
- if (y = 0, t) op = [op[0] & 2, t.value];
52
- switch (op[0]) {
53
- case 0: case 1: t = op; break;
54
- case 4: _.label++; return { value: op[1], done: false };
55
- case 5: _.label++; y = op[1]; op = [0]; continue;
56
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
57
- default:
58
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
59
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
60
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
61
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
62
- if (t[2]) _.ops.pop();
63
- _.trys.pop(); continue;
64
- }
65
- op = body.call(thisArg, _);
66
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
67
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
68
- }
69
- }
70
-
71
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
72
- var e = new Error(message);
73
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
74
- };
75
-
76
- function setAcceptLanguageHeader(value) {
77
- axios.defaults.headers.common['Accept-Language'] = value;
78
- }
79
- function setTokenHeader(token) {
80
- axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
81
- }
82
-
83
- var isRefreshing = false;
84
- var failedQueue = [];
85
- var processQueue = function (error, token) {
86
- if (token === void 0) { token = null; }
87
- failedQueue.forEach(function (prom) {
88
- if (error) {
89
- prom.reject(error);
90
- }
91
- else {
92
- prom.resolve(token);
93
- }
94
- });
95
- failedQueue = [];
96
- };
97
- axios.interceptors.response.use(function (response) { return response; }, function (error) { return __awaiter(void 0, void 0, void 0, function () {
98
- var originalRequest, token, err_1, token, err_2;
99
- var _a;
100
- return __generator(this, function (_b) {
101
- switch (_b.label) {
102
- case 0:
103
- originalRequest = error.config;
104
- if (!(error.response.status === 401 && !originalRequest._retry)) return [3 /*break*/, 13];
105
- originalRequest._retry = true;
106
- if (!isRefreshing) return [3 /*break*/, 5];
107
- _b.label = 1;
108
- case 1:
109
- _b.trys.push([1, 4, , 5]);
110
- return [4 /*yield*/, new Promise(function (resolve, reject) {
111
- failedQueue.push({ resolve: resolve, reject: reject });
112
- })];
113
- case 2:
114
- token = _b.sent();
115
- originalRequest.headers['Authorization'] = 'Bearer ' + token;
116
- return [4 /*yield*/, axios(originalRequest)];
117
- case 3: return [2 /*return*/, _b.sent()];
118
- case 4:
119
- err_1 = _b.sent();
120
- return [2 /*return*/, Promise.reject(err_1)];
121
- case 5:
122
- isRefreshing = true;
123
- _b.label = 6;
124
- case 6:
125
- _b.trys.push([6, 11, 12, 13]);
126
- return [4 /*yield*/, refreshToken(
127
- // Handle edge case where we get a blank screen if the initial 401 error is from a refresh token request
128
- ((_a = originalRequest.url) === null || _a === void 0 ? void 0 : _a.includes('api/auth/refresh')) ? true : false)];
129
- case 7:
130
- token = (_b.sent()).token;
131
- if (!token) return [3 /*break*/, 9];
132
- originalRequest.headers['Authorization'] = 'Bearer ' + token;
133
- setTokenHeader(token);
134
- window.dispatchEvent(new CustomEvent('tokenUpdated', { detail: token }));
135
- processQueue(null, token);
136
- return [4 /*yield*/, axios(originalRequest)];
137
- case 8: return [2 /*return*/, _b.sent()];
138
- case 9:
139
- window.location.href = '/login';
140
- _b.label = 10;
141
- case 10: return [3 /*break*/, 13];
142
- case 11:
143
- err_2 = _b.sent();
144
- processQueue(err_2, null);
145
- return [2 /*return*/, Promise.reject(err_2)];
146
- case 12:
147
- isRefreshing = false;
148
- return [7 /*endfinally*/];
149
- case 13: return [2 /*return*/, Promise.reject(error)];
150
- }
151
- });
152
- }); });
153
- function _get(url, options) {
154
- return __awaiter(this, void 0, void 0, function () {
155
- var response;
156
- return __generator(this, function (_a) {
157
- switch (_a.label) {
158
- case 0: return [4 /*yield*/, axios.get(url, __assign({}, options))];
159
- case 1:
160
- response = _a.sent();
161
- return [2 /*return*/, response.data];
162
- }
163
- });
164
- });
165
- }
166
- function _post(url, data) {
167
- return __awaiter(this, void 0, void 0, function () {
168
- var response;
169
- return __generator(this, function (_a) {
170
- switch (_a.label) {
171
- case 0: return [4 /*yield*/, axios.post(url, JSON.stringify(data), {
172
- headers: { 'Content-Type': 'application/json' },
173
- })];
174
- case 1:
175
- response = _a.sent();
176
- return [2 /*return*/, response.data];
177
- }
178
- });
179
- });
180
- }
181
- function _postMultiPart(url, formData, options) {
182
- return __awaiter(this, void 0, void 0, function () {
183
- var response;
184
- return __generator(this, function (_a) {
185
- switch (_a.label) {
186
- case 0: return [4 /*yield*/, axios.post(url, formData, __assign(__assign({}, options), { headers: { 'Content-Type': 'multipart/form-data' } }))];
187
- case 1:
188
- response = _a.sent();
189
- return [2 /*return*/, response.data];
190
- }
191
- });
192
- });
193
- }
194
- function _put(url, data) {
195
- return __awaiter(this, void 0, void 0, function () {
196
- var response;
197
- return __generator(this, function (_a) {
198
- switch (_a.label) {
199
- case 0: return [4 /*yield*/, axios.put(url, JSON.stringify(data), {
200
- headers: { 'Content-Type': 'application/json' },
201
- })];
202
- case 1:
203
- response = _a.sent();
204
- return [2 /*return*/, response.data];
205
- }
206
- });
207
- });
208
- }
209
- function _delete(url) {
210
- return __awaiter(this, void 0, void 0, function () {
211
- var response;
212
- return __generator(this, function (_a) {
213
- switch (_a.label) {
214
- case 0: return [4 /*yield*/, axios.delete(url)];
215
- case 1:
216
- response = _a.sent();
217
- return [2 /*return*/, response.data];
218
- }
219
- });
220
- });
221
- }
222
- function _deleteWithOptions(url, options) {
223
- return __awaiter(this, void 0, void 0, function () {
224
- var response;
225
- return __generator(this, function (_a) {
226
- switch (_a.label) {
227
- case 0: return [4 /*yield*/, axios.delete(url, __assign({}, options))];
228
- case 1:
229
- response = _a.sent();
230
- return [2 /*return*/, response.data];
231
- }
232
- });
233
- });
234
- }
235
- function _patch(url, data) {
236
- return __awaiter(this, void 0, void 0, function () {
237
- var response;
238
- return __generator(this, function (_a) {
239
- switch (_a.label) {
240
- case 0: return [4 /*yield*/, axios.patch(url, JSON.stringify(data), {
241
- headers: { 'Content-Type': 'application/json' },
242
- })];
243
- case 1:
244
- response = _a.sent();
245
- return [2 /*return*/, response.data];
246
- }
247
- });
248
- });
249
- }
250
- var request = {
251
- get: _get,
252
- post: _post,
253
- postMultiPart: _postMultiPart,
254
- put: _put,
255
- delete: _delete,
256
- deleteWithOptions: _deleteWithOptions,
257
- patch: _patch,
258
- };
259
-
260
- var user = function () { return '/api/user'; };
261
- var balance = function () { return '/api/balance'; };
262
- var userPlugins = function () { return '/api/user/plugins'; };
263
- var messages = function (conversationId, messageId) {
264
- return "/api/messages/".concat(conversationId).concat(messageId ? "/".concat(messageId) : '');
265
- };
266
- var keysEndpoint = '/api/keys';
267
- var keys = function () { return keysEndpoint; };
268
- var userKeyQuery$1 = function (name) { return "".concat(keysEndpoint, "?name=").concat(name); };
269
- var revokeUserKey$1 = function (name) { return "".concat(keysEndpoint, "/").concat(name); };
270
- var revokeAllUserKeys$1 = function () { return "".concat(keysEndpoint, "?all=true"); };
271
- var abortRequest = function (endpoint) { return "/api/ask/".concat(endpoint, "/abort"); };
272
- var conversations = function (pageNumber) { return "/api/convos?pageNumber=".concat(pageNumber); };
273
- var conversationById = function (id) { return "/api/convos/".concat(id); };
274
- var updateConversation$1 = function () { return '/api/convos/update'; };
275
- var deleteConversation$1 = function () { return '/api/convos/clear'; };
276
- var search = function (q, pageNumber) {
277
- return "/api/search?q=".concat(q, "&pageNumber=").concat(pageNumber);
278
- };
279
- var searchEnabled = function () { return '/api/search/enable'; };
280
- var presets = function () { return '/api/presets'; };
281
- var deletePreset$1 = function () { return '/api/presets/delete'; };
282
- var aiEndpoints = function () { return '/api/endpoints'; };
283
- var models = function () { return '/api/models'; };
284
- var tokenizer = function () { return '/api/tokenizer'; };
285
- var login$1 = function () { return '/api/auth/login'; };
286
- var logout$1 = function () { return '/api/auth/logout'; };
287
- var register$1 = function () { return '/api/auth/register'; };
288
- var loginGoogle = function () { return '/api/auth/google'; };
289
- var refreshToken$1 = function (retry) { return "/api/auth/refresh".concat(retry ? '?retry=true' : ''); };
290
- var requestPasswordReset$1 = function () { return '/api/auth/requestPasswordReset'; };
291
- var resetPassword$1 = function () { return '/api/auth/resetPassword'; };
292
- var plugins = function () { return '/api/plugins'; };
293
- var config = function () { return '/api/config'; };
294
-
295
- function getConversations(pageNumber) {
296
- return request.get(conversations(pageNumber));
297
- }
298
- function abortRequestWithMessage(endpoint, abortKey, message) {
299
- return request.post(abortRequest(endpoint), { arg: { abortKey: abortKey, message: message } });
300
- }
301
- function deleteConversation(payload) {
302
- //todo: this should be a DELETE request
303
- return request.post(deleteConversation$1(), { arg: payload });
304
- }
305
- function clearAllConversations() {
306
- return request.post(deleteConversation$1(), { arg: {} });
307
- }
308
- function revokeUserKey(name) {
309
- return request.delete(revokeUserKey$1(name));
310
- }
311
- function revokeAllUserKeys() {
312
- return request.delete(revokeAllUserKeys$1());
313
- }
314
- function getMessagesByConvoId(conversationId) {
315
- return request.get(messages(conversationId));
316
- }
317
- function getConversationById(id) {
318
- return request.get(conversationById(id));
319
- }
320
- function updateConversation(payload) {
321
- return request.post(updateConversation$1(), { arg: payload });
322
- }
323
- function updateMessage(payload) {
324
- var conversationId = payload.conversationId, messageId = payload.messageId, text = payload.text;
325
- if (!conversationId) {
326
- throw new Error('conversationId is required');
327
- }
328
- return request.put(messages(conversationId, messageId), { text: text });
329
- }
330
- function updateUserKey(payload) {
331
- var value = payload.value;
332
- if (!value) {
333
- throw new Error('value is required');
334
- }
335
- return request.put(keys(), payload);
336
- }
337
- function getPresets() {
338
- return request.get(presets());
339
- }
340
- function createPreset(payload) {
341
- return request.post(presets(), payload);
342
- }
343
- function updatePreset(payload) {
344
- return request.post(presets(), payload);
345
- }
346
- function deletePreset(arg) {
347
- return request.post(deletePreset$1(), arg);
348
- }
349
- function getSearchEnabled() {
350
- return request.get(searchEnabled());
351
- }
352
- function getUser() {
353
- return request.get(user());
354
- }
355
- function getUserBalance() {
356
- return request.get(balance());
357
- }
358
- var searchConversations = function (q, pageNumber) { return __awaiter(void 0, void 0, void 0, function () {
359
- return __generator(this, function (_a) {
360
- return [2 /*return*/, request.get(search(q, pageNumber))];
361
- });
362
- }); };
363
- var getAIEndpoints = function () {
364
- return request.get(aiEndpoints());
365
- };
366
- var getModels = function () { return __awaiter(void 0, void 0, void 0, function () {
367
- return __generator(this, function (_a) {
368
- return [2 /*return*/, request.get(models())];
369
- });
370
- }); };
371
- var updateTokenCount = function (text) {
372
- return request.post(tokenizer(), { arg: text });
373
- };
374
- var login = function (payload) {
375
- return request.post(login$1(), payload);
376
- };
377
- var logout = function () {
378
- return request.post(logout$1());
379
- };
380
- var register = function (payload) {
381
- return request.post(register$1(), payload);
382
- };
383
- var refreshToken = function (retry) { return request.post(refreshToken$1(retry)); };
384
- var userKeyQuery = function (name) {
385
- return request.get(userKeyQuery$1(name));
386
- };
387
- var getLoginGoogle = function () {
388
- return request.get(loginGoogle());
389
- };
390
- var requestPasswordReset = function (payload) {
391
- return request.post(requestPasswordReset$1(), payload);
392
- };
393
- var resetPassword = function (payload) {
394
- return request.post(resetPassword$1(), payload);
395
- };
396
- var getAvailablePlugins = function () {
397
- return request.get(plugins());
398
- };
399
- var updateUserPlugins = function (payload) {
400
- return request.post(userPlugins(), payload);
401
- };
402
- var getStartupConfig = function () {
403
- return request.get(config());
404
- };
405
-
406
- var EModelEndpoint;
407
- (function (EModelEndpoint) {
408
- EModelEndpoint["azureOpenAI"] = "azureOpenAI";
409
- EModelEndpoint["openAI"] = "openAI";
410
- EModelEndpoint["bingAI"] = "bingAI";
411
- EModelEndpoint["chatGPTBrowser"] = "chatGPTBrowser";
412
- EModelEndpoint["google"] = "google";
413
- EModelEndpoint["gptPlugins"] = "gptPlugins";
414
- EModelEndpoint["anthropic"] = "anthropic";
415
- })(EModelEndpoint || (EModelEndpoint = {}));
416
- var eModelEndpointSchema = z.nativeEnum(EModelEndpoint);
417
- var tPluginAuthConfigSchema = z.object({
418
- authField: z.string(),
419
- label: z.string(),
420
- description: z.string(),
421
- });
422
- var tPluginSchema = z.object({
423
- name: z.string(),
424
- pluginKey: z.string(),
425
- description: z.string(),
426
- icon: z.string(),
427
- authConfig: z.array(tPluginAuthConfigSchema),
428
- authenticated: z.boolean().optional(),
429
- isButton: z.boolean().optional(),
430
- });
431
- var tExampleSchema = z.object({
432
- input: z.object({
433
- content: z.string(),
434
- }),
435
- output: z.object({
436
- content: z.string(),
437
- }),
438
- });
439
- var tAgentOptionsSchema = z.object({
440
- agent: z.string(),
441
- skipCompletion: z.boolean(),
442
- model: z.string(),
443
- temperature: z.number(),
444
- });
445
- var tMessageSchema = z.object({
446
- messageId: z.string(),
447
- clientId: z.string().nullable().optional(),
448
- conversationId: z.string().nullable(),
449
- parentMessageId: z.string().nullable(),
450
- responseMessageId: z.string().nullable().optional(),
451
- overrideParentMessageId: z.string().nullable().optional(),
452
- bg: z.string().nullable().optional(),
453
- model: z.string().nullable().optional(),
454
- title: z.string().nullable().or(z.literal('New Chat')).default('New Chat'),
455
- sender: z.string(),
456
- text: z.string(),
457
- generation: z.string().nullable().optional(),
458
- isEdited: z.boolean().optional(),
459
- isCreatedByUser: z.boolean(),
460
- error: z.boolean(),
461
- createdAt: z
462
- .string()
463
- .optional()
464
- .default(function () { return new Date().toISOString(); }),
465
- updatedAt: z
466
- .string()
467
- .optional()
468
- .default(function () { return new Date().toISOString(); }),
469
- current: z.boolean().optional(),
470
- unfinished: z.boolean().optional(),
471
- submitting: z.boolean().optional(),
472
- searchResult: z.boolean().optional(),
473
- finish_reason: z.string().optional(),
474
- });
475
- var tConversationSchema = z.object({
476
- conversationId: z.string().nullable(),
477
- title: z.string().nullable().or(z.literal('New Chat')).default('New Chat'),
478
- user: z.string().optional(),
479
- endpoint: eModelEndpointSchema.nullable(),
480
- suggestions: z.array(z.string()).optional(),
481
- messages: z.array(z.string()).optional(),
482
- tools: z.array(tPluginSchema).optional(),
483
- createdAt: z.string(),
484
- updatedAt: z.string(),
485
- systemMessage: z.string().nullable().optional(),
486
- modelLabel: z.string().nullable().optional(),
487
- examples: z.array(tExampleSchema).optional(),
488
- chatGptLabel: z.string().nullable().optional(),
489
- userLabel: z.string().optional(),
490
- model: z.string().nullable().optional(),
491
- promptPrefix: z.string().nullable().optional(),
492
- temperature: z.number().optional(),
493
- topP: z.number().optional(),
494
- topK: z.number().optional(),
495
- context: z.string().nullable().optional(),
496
- top_p: z.number().optional(),
497
- frequency_penalty: z.number().optional(),
498
- presence_penalty: z.number().optional(),
499
- jailbreak: z.boolean().optional(),
500
- jailbreakConversationId: z.string().nullable().optional(),
501
- conversationSignature: z.string().nullable().optional(),
502
- parentMessageId: z.string().optional(),
503
- clientId: z.string().nullable().optional(),
504
- invocationId: z.number().nullable().optional(),
505
- toneStyle: z.string().nullable().optional(),
506
- maxOutputTokens: z.number().optional(),
507
- agentOptions: tAgentOptionsSchema.nullable().optional(),
508
- });
509
- var tPresetSchema = tConversationSchema
510
- .omit({
511
- conversationId: true,
512
- createdAt: true,
513
- updatedAt: true,
514
- title: true,
515
- })
516
- .merge(z.object({
517
- conversationId: z.string().optional(),
518
- presetId: z.string().nullable().optional(),
519
- title: z.string().nullable().optional(),
520
- }));
521
- var openAISchema = tConversationSchema
522
- .pick({
523
- model: true,
524
- chatGptLabel: true,
525
- promptPrefix: true,
526
- temperature: true,
527
- top_p: true,
528
- presence_penalty: true,
529
- frequency_penalty: true,
530
- })
531
- .transform(function (obj) {
532
- var _a, _b, _c, _d, _e, _f, _g;
533
- return (__assign(__assign({}, obj), { model: (_a = obj.model) !== null && _a !== void 0 ? _a : 'gpt-3.5-turbo', chatGptLabel: (_b = obj.chatGptLabel) !== null && _b !== void 0 ? _b : null, promptPrefix: (_c = obj.promptPrefix) !== null && _c !== void 0 ? _c : null, temperature: (_d = obj.temperature) !== null && _d !== void 0 ? _d : 1, top_p: (_e = obj.top_p) !== null && _e !== void 0 ? _e : 1, presence_penalty: (_f = obj.presence_penalty) !== null && _f !== void 0 ? _f : 0, frequency_penalty: (_g = obj.frequency_penalty) !== null && _g !== void 0 ? _g : 0 }));
534
- })
535
- .catch(function () { return ({
536
- model: 'gpt-3.5-turbo',
537
- chatGptLabel: null,
538
- promptPrefix: null,
539
- temperature: 1,
540
- top_p: 1,
541
- presence_penalty: 0,
542
- frequency_penalty: 0,
543
- }); });
544
- var googleSchema = tConversationSchema
545
- .pick({
546
- model: true,
547
- modelLabel: true,
548
- promptPrefix: true,
549
- examples: true,
550
- temperature: true,
551
- maxOutputTokens: true,
552
- topP: true,
553
- topK: true,
554
- })
555
- .transform(function (obj) {
556
- var _a, _b, _c, _d, _e, _f, _g;
557
- return (__assign(__assign({}, obj), { model: (_a = obj.model) !== null && _a !== void 0 ? _a : 'chat-bison', modelLabel: (_b = obj.modelLabel) !== null && _b !== void 0 ? _b : null, promptPrefix: (_c = obj.promptPrefix) !== null && _c !== void 0 ? _c : null, temperature: (_d = obj.temperature) !== null && _d !== void 0 ? _d : 0.2, maxOutputTokens: (_e = obj.maxOutputTokens) !== null && _e !== void 0 ? _e : 1024, topP: (_f = obj.topP) !== null && _f !== void 0 ? _f : 0.95, topK: (_g = obj.topK) !== null && _g !== void 0 ? _g : 40 }));
558
- })
559
- .catch(function () { return ({
560
- model: 'chat-bison',
561
- modelLabel: null,
562
- promptPrefix: null,
563
- temperature: 0.2,
564
- maxOutputTokens: 1024,
565
- topP: 0.95,
566
- topK: 40,
567
- }); });
568
- var bingAISchema = tConversationSchema
569
- .pick({
570
- jailbreak: true,
571
- systemMessage: true,
572
- context: true,
573
- toneStyle: true,
574
- jailbreakConversationId: true,
575
- conversationSignature: true,
576
- clientId: true,
577
- invocationId: true,
578
- })
579
- .transform(function (obj) {
580
- var _a, _b, _c, _d, _e, _f, _g, _h;
581
- return (__assign(__assign({}, obj), { model: '', jailbreak: (_a = obj.jailbreak) !== null && _a !== void 0 ? _a : false, systemMessage: (_b = obj.systemMessage) !== null && _b !== void 0 ? _b : null, context: (_c = obj.context) !== null && _c !== void 0 ? _c : null, toneStyle: (_d = obj.toneStyle) !== null && _d !== void 0 ? _d : 'creative', jailbreakConversationId: (_e = obj.jailbreakConversationId) !== null && _e !== void 0 ? _e : null, conversationSignature: (_f = obj.conversationSignature) !== null && _f !== void 0 ? _f : null, clientId: (_g = obj.clientId) !== null && _g !== void 0 ? _g : null, invocationId: (_h = obj.invocationId) !== null && _h !== void 0 ? _h : 1 }));
582
- })
583
- .catch(function () { return ({
584
- model: '',
585
- jailbreak: false,
586
- systemMessage: null,
587
- context: null,
588
- toneStyle: 'creative',
589
- jailbreakConversationId: null,
590
- conversationSignature: null,
591
- clientId: null,
592
- invocationId: 1,
593
- }); });
594
- var anthropicSchema = tConversationSchema
595
- .pick({
596
- model: true,
597
- modelLabel: true,
598
- promptPrefix: true,
599
- temperature: true,
600
- maxOutputTokens: true,
601
- topP: true,
602
- topK: true,
603
- })
604
- .transform(function (obj) {
605
- var _a, _b, _c, _d, _e, _f, _g;
606
- return (__assign(__assign({}, obj), { model: (_a = obj.model) !== null && _a !== void 0 ? _a : 'claude-1', modelLabel: (_b = obj.modelLabel) !== null && _b !== void 0 ? _b : null, promptPrefix: (_c = obj.promptPrefix) !== null && _c !== void 0 ? _c : null, temperature: (_d = obj.temperature) !== null && _d !== void 0 ? _d : 1, maxOutputTokens: (_e = obj.maxOutputTokens) !== null && _e !== void 0 ? _e : 4000, topP: (_f = obj.topP) !== null && _f !== void 0 ? _f : 0.7, topK: (_g = obj.topK) !== null && _g !== void 0 ? _g : 5 }));
607
- })
608
- .catch(function () { return ({
609
- model: 'claude-1',
610
- modelLabel: null,
611
- promptPrefix: null,
612
- temperature: 1,
613
- maxOutputTokens: 4000,
614
- topP: 0.7,
615
- topK: 5,
616
- }); });
617
- var chatGPTBrowserSchema = tConversationSchema
618
- .pick({
619
- model: true,
620
- })
621
- .transform(function (obj) {
622
- var _a;
623
- return (__assign(__assign({}, obj), { model: (_a = obj.model) !== null && _a !== void 0 ? _a : 'text-davinci-002-render-sha' }));
624
- })
625
- .catch(function () { return ({
626
- model: 'text-davinci-002-render-sha',
627
- }); });
628
- var gptPluginsSchema = tConversationSchema
629
- .pick({
630
- model: true,
631
- chatGptLabel: true,
632
- promptPrefix: true,
633
- temperature: true,
634
- top_p: true,
635
- presence_penalty: true,
636
- frequency_penalty: true,
637
- tools: true,
638
- agentOptions: true,
639
- })
640
- .transform(function (obj) {
641
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
642
- return (__assign(__assign({}, obj), { model: (_a = obj.model) !== null && _a !== void 0 ? _a : 'gpt-3.5-turbo', chatGptLabel: (_b = obj.chatGptLabel) !== null && _b !== void 0 ? _b : null, promptPrefix: (_c = obj.promptPrefix) !== null && _c !== void 0 ? _c : null, temperature: (_d = obj.temperature) !== null && _d !== void 0 ? _d : 0.8, top_p: (_e = obj.top_p) !== null && _e !== void 0 ? _e : 1, presence_penalty: (_f = obj.presence_penalty) !== null && _f !== void 0 ? _f : 0, frequency_penalty: (_g = obj.frequency_penalty) !== null && _g !== void 0 ? _g : 0, tools: (_h = obj.tools) !== null && _h !== void 0 ? _h : [], agentOptions: (_j = obj.agentOptions) !== null && _j !== void 0 ? _j : {
643
- agent: 'functions',
644
- skipCompletion: true,
645
- model: 'gpt-3.5-turbo',
646
- temperature: 0,
647
- } }));
648
- })
649
- .catch(function () { return ({
650
- model: 'gpt-3.5-turbo',
651
- chatGptLabel: null,
652
- promptPrefix: null,
653
- temperature: 0.8,
654
- top_p: 1,
655
- presence_penalty: 0,
656
- frequency_penalty: 0,
657
- tools: [],
658
- agentOptions: {
659
- agent: 'functions',
660
- skipCompletion: true,
661
- model: 'gpt-3.5-turbo',
662
- temperature: 0,
663
- },
664
- }); });
665
- var endpointSchemas = {
666
- openAI: openAISchema,
667
- azureOpenAI: openAISchema,
668
- google: googleSchema,
669
- bingAI: bingAISchema,
670
- anthropic: anthropicSchema,
671
- chatGPTBrowser: chatGPTBrowserSchema,
672
- gptPlugins: gptPluginsSchema,
673
- };
674
- function getFirstDefinedValue(possibleValues) {
675
- var returnValue;
676
- for (var _i = 0, possibleValues_1 = possibleValues; _i < possibleValues_1.length; _i++) {
677
- var value = possibleValues_1[_i];
678
- if (value) {
679
- returnValue = value;
680
- break;
681
- }
682
- }
683
- return returnValue;
684
- }
685
- var parseConvo = function (endpoint, conversation, possibleValues) {
686
- var _a, _b;
687
- var schema = endpointSchemas[endpoint];
688
- if (!schema) {
689
- throw new Error("Unknown endpoint: ".concat(endpoint));
690
- }
691
- var convo = schema.parse(conversation);
692
- var _c = possibleValues !== null && possibleValues !== void 0 ? possibleValues : {}, models = _c.models, secondaryModels = _c.secondaryModels;
693
- if (models && convo) {
694
- convo.model = (_a = getFirstDefinedValue(models)) !== null && _a !== void 0 ? _a : convo.model;
695
- }
696
- if (secondaryModels && convo.agentOptions) {
697
- convo.agentOptions.model = (_b = getFirstDefinedValue(secondaryModels)) !== null && _b !== void 0 ? _b : convo.agentOptions.model;
698
- }
699
- return convo;
700
- };
701
- var getResponseSender = function (endpointOption) {
702
- var endpoint = endpointOption.endpoint, chatGptLabel = endpointOption.chatGptLabel, modelLabel = endpointOption.modelLabel, jailbreak = endpointOption.jailbreak;
703
- if (['openAI', 'azureOpenAI', 'gptPlugins', 'chatGPTBrowser'].includes(endpoint)) {
704
- return chatGptLabel !== null && chatGptLabel !== void 0 ? chatGptLabel : 'ChatGPT';
705
- }
706
- if (endpoint === 'bingAI') {
707
- return jailbreak ? 'Sydney' : 'BingAI';
708
- }
709
- if (endpoint === 'anthropic') {
710
- return modelLabel !== null && modelLabel !== void 0 ? modelLabel : 'Anthropic';
711
- }
712
- if (endpoint === 'google') {
713
- return modelLabel !== null && modelLabel !== void 0 ? modelLabel : 'PaLM2';
714
- }
715
- return '';
716
- };
717
-
718
- var QueryKeys;
719
- (function (QueryKeys) {
720
- QueryKeys["messages"] = "messages";
721
- QueryKeys["allConversations"] = "allConversations";
722
- QueryKeys["conversation"] = "conversation";
723
- QueryKeys["searchEnabled"] = "searchEnabled";
724
- QueryKeys["user"] = "user";
725
- QueryKeys["name"] = "name";
726
- QueryKeys["models"] = "models";
727
- QueryKeys["balance"] = "balance";
728
- QueryKeys["endpoints"] = "endpoints";
729
- QueryKeys["presets"] = "presets";
730
- QueryKeys["searchResults"] = "searchResults";
731
- QueryKeys["tokenCount"] = "tokenCount";
732
- QueryKeys["availablePlugins"] = "availablePlugins";
733
- QueryKeys["startupConfig"] = "startupConfig";
734
- })(QueryKeys || (QueryKeys = {}));
735
- var useAbortRequestWithMessage = function () {
736
- var queryClient = useQueryClient();
737
- return useMutation(function (_a) {
738
- var endpoint = _a.endpoint, abortKey = _a.abortKey, message = _a.message;
739
- return abortRequestWithMessage(endpoint, abortKey, message);
740
- }, {
741
- onSuccess: function () {
742
- queryClient.invalidateQueries([QueryKeys.balance]);
743
- },
744
- });
745
- };
746
- var useGetUserQuery = function (config) {
747
- return useQuery([QueryKeys.user], function () { return getUser(); }, __assign({ refetchOnWindowFocus: false, refetchOnReconnect: false, refetchOnMount: false, retry: false }, config));
748
- };
749
- var useGetMessagesByConvoId = function (id, config) {
750
- return useQuery([QueryKeys.messages, id], function () { return getMessagesByConvoId(id); }, __assign({ refetchOnWindowFocus: false, refetchOnReconnect: false, refetchOnMount: false }, config));
751
- };
752
- var useGetUserBalance = function (config) {
753
- return useQuery([QueryKeys.balance], function () { return getUserBalance(); }, __assign({ refetchOnWindowFocus: true, refetchOnReconnect: true, refetchOnMount: true }, config));
754
- };
755
- var useGetConversationByIdQuery = function (id, config) {
756
- return useQuery([QueryKeys.conversation, id], function () { return getConversationById(id); }, __assign({ refetchOnWindowFocus: false, refetchOnReconnect: false, refetchOnMount: false }, config));
757
- };
758
- //This isn't ideal because its just a query and we're using mutation, but it was the only way
759
- //to make it work with how the Chat component is structured
760
- var useGetConversationByIdMutation = function (id) {
761
- var queryClient = useQueryClient();
762
- return useMutation(function () { return getConversationById(id); }, {
763
- // onSuccess: (res: s.TConversation) => {
764
- onSuccess: function () {
765
- queryClient.invalidateQueries([QueryKeys.conversation, id]);
766
- },
767
- });
768
- };
769
- var useUpdateConversationMutation = function (id) {
770
- var queryClient = useQueryClient();
771
- return useMutation(function (payload) { return updateConversation(payload); }, {
772
- onSuccess: function () {
773
- queryClient.invalidateQueries([QueryKeys.conversation, id]);
774
- queryClient.invalidateQueries([QueryKeys.allConversations]);
775
- },
776
- });
777
- };
778
- var useUpdateMessageMutation = function (id) {
779
- var queryClient = useQueryClient();
780
- return useMutation(function (payload) { return updateMessage(payload); }, {
781
- onSuccess: function () {
782
- queryClient.invalidateQueries([QueryKeys.messages, id]);
783
- },
784
- });
785
- };
786
- var useUpdateUserKeysMutation = function () {
787
- var queryClient = useQueryClient();
788
- return useMutation(function (payload) { return updateUserKey(payload); }, {
789
- onSuccess: function () {
790
- queryClient.invalidateQueries([QueryKeys.name]);
791
- },
792
- });
793
- };
794
- var useDeleteConversationMutation = function (id) {
795
- var queryClient = useQueryClient();
796
- return useMutation(function (payload) { return deleteConversation(payload); }, {
797
- onSuccess: function () {
798
- queryClient.invalidateQueries([QueryKeys.conversation, id]);
799
- queryClient.invalidateQueries([QueryKeys.allConversations]);
800
- },
801
- });
802
- };
803
- var useClearConversationsMutation = function () {
804
- var queryClient = useQueryClient();
805
- return useMutation(function () { return clearAllConversations(); }, {
806
- onSuccess: function () {
807
- queryClient.invalidateQueries([QueryKeys.allConversations]);
808
- },
809
- });
810
- };
811
- var useRevokeUserKeyMutation = function (name) {
812
- var queryClient = useQueryClient();
813
- return useMutation(function () { return revokeUserKey(name); }, {
814
- onSuccess: function () {
815
- queryClient.invalidateQueries([QueryKeys.name]);
816
- },
817
- });
818
- };
819
- var useRevokeAllUserKeysMutation = function () {
820
- var queryClient = useQueryClient();
821
- return useMutation(function () { return revokeAllUserKeys(); }, {
822
- onSuccess: function () {
823
- queryClient.invalidateQueries([QueryKeys.name]);
824
- },
825
- });
826
- };
827
- var useGetConversationsQuery = function (pageNumber, config) {
828
- return useQuery([QueryKeys.allConversations, pageNumber], function () { return getConversations(pageNumber); }, __assign({ refetchOnReconnect: false, refetchOnMount: false, retry: 1 }, config));
829
- };
830
- var useGetSearchEnabledQuery = function (config) {
831
- return useQuery([QueryKeys.searchEnabled], function () { return getSearchEnabled(); }, __assign({ refetchOnWindowFocus: false, refetchOnReconnect: false, refetchOnMount: false }, config));
832
- };
833
- var useGetEndpointsQuery = function (config) {
834
- return useQuery([QueryKeys.endpoints], function () { return getAIEndpoints(); }, __assign({ refetchOnWindowFocus: false, refetchOnReconnect: false, refetchOnMount: false }, config));
835
- };
836
- var useGetModelsQuery = function (config) {
837
- return useQuery([QueryKeys.models], function () { return getModels(); }, __assign({ refetchOnWindowFocus: false, refetchOnReconnect: false, refetchOnMount: false }, config));
838
- };
839
- var useCreatePresetMutation = function () {
840
- var queryClient = useQueryClient();
841
- return useMutation(function (payload) { return createPreset(payload); }, {
842
- onSuccess: function () {
843
- queryClient.invalidateQueries([QueryKeys.presets]);
844
- },
845
- });
846
- };
847
- var useUpdatePresetMutation = function () {
848
- var queryClient = useQueryClient();
849
- return useMutation(function (payload) { return updatePreset(payload); }, {
850
- onSuccess: function () {
851
- queryClient.invalidateQueries([QueryKeys.presets]);
852
- },
853
- });
854
- };
855
- var useGetPresetsQuery = function (config) {
856
- return useQuery([QueryKeys.presets], function () { return getPresets(); }, __assign({ refetchOnWindowFocus: false, refetchOnReconnect: false, refetchOnMount: false }, config));
857
- };
858
- var useDeletePresetMutation = function () {
859
- var queryClient = useQueryClient();
860
- return useMutation(function (payload) { return deletePreset(payload); }, {
861
- onSuccess: function () {
862
- queryClient.invalidateQueries([QueryKeys.presets]);
863
- },
864
- });
865
- };
866
- var useSearchQuery = function (searchQuery, pageNumber, config) {
867
- return useQuery([QueryKeys.searchResults, pageNumber, searchQuery], function () { return searchConversations(searchQuery, pageNumber); }, __assign({ refetchOnWindowFocus: false, refetchOnReconnect: false, refetchOnMount: false }, config));
868
- };
869
- var useUpdateTokenCountMutation = function () {
870
- var queryClient = useQueryClient();
871
- return useMutation(function (_a) {
872
- var text = _a.text;
873
- return updateTokenCount(text);
874
- }, {
875
- onSuccess: function () {
876
- queryClient.invalidateQueries([QueryKeys.tokenCount]);
877
- },
878
- });
879
- };
880
- var useLoginUserMutation = function () {
881
- var queryClient = useQueryClient();
882
- return useMutation(function (payload) { return login(payload); }, {
883
- onSuccess: function () {
884
- queryClient.invalidateQueries([QueryKeys.user]);
885
- },
886
- onMutate: function () {
887
- queryClient.invalidateQueries([QueryKeys.models]);
888
- },
889
- });
890
- };
891
- var useRegisterUserMutation = function () {
892
- var queryClient = useQueryClient();
893
- return useMutation(function (payload) { return register(payload); }, {
894
- onSuccess: function () {
895
- queryClient.invalidateQueries([QueryKeys.user]);
896
- },
897
- });
898
- };
899
- var useLogoutUserMutation = function () {
900
- var queryClient = useQueryClient();
901
- return useMutation(function () { return logout(); }, {
902
- onSuccess: function () {
903
- queryClient.invalidateQueries([QueryKeys.user]);
904
- },
905
- });
906
- };
907
- var useRefreshTokenMutation = function () {
908
- var queryClient = useQueryClient();
909
- return useMutation(function () { return refreshToken(); }, {
910
- onMutate: function () {
911
- queryClient.invalidateQueries([QueryKeys.models]);
912
- },
913
- });
914
- };
915
- var useUserKeyQuery = function (name, config) {
916
- return useQuery([QueryKeys.name, name], function () {
917
- if (!name) {
918
- return Promise.resolve({ expiresAt: '' });
919
- }
920
- return userKeyQuery(name);
921
- }, __assign({ refetchOnWindowFocus: false, refetchOnReconnect: false, refetchOnMount: false, retry: false }, config));
922
- };
923
- var useRequestPasswordResetMutation = function () {
924
- return useMutation(function (payload) {
925
- return requestPasswordReset(payload);
926
- });
927
- };
928
- var useResetPasswordMutation = function () {
929
- return useMutation(function (payload) { return resetPassword(payload); });
930
- };
931
- var useAvailablePluginsQuery = function () {
932
- return useQuery([QueryKeys.availablePlugins], function () { return getAvailablePlugins(); }, {
933
- refetchOnWindowFocus: false,
934
- refetchOnReconnect: false,
935
- refetchOnMount: false,
936
- });
937
- };
938
- var useUpdateUserPluginsMutation = function () {
939
- var queryClient = useQueryClient();
940
- return useMutation(function (payload) { return updateUserPlugins(payload); }, {
941
- onSuccess: function () {
942
- queryClient.invalidateQueries([QueryKeys.user]);
943
- },
944
- });
945
- };
946
- var useGetStartupConfig = function () {
947
- return useQuery([QueryKeys.startupConfig], function () { return getStartupConfig(); }, {
948
- refetchOnWindowFocus: false,
949
- refetchOnReconnect: false,
950
- refetchOnMount: false,
951
- });
952
- };
953
-
954
- /* eslint-disable */
955
- /**
956
- * Copyright (C) 2016 Maxime Petazzoni <maxime.petazzoni@bulix.org>.
957
- * All rights reserved.
958
- */
959
-
960
-
961
- var SSE = function (url, options) {
962
- if (!(this instanceof SSE)) {
963
- return new SSE(url, options);
964
- }
965
-
966
- this.INITIALIZING = -1;
967
- this.CONNECTING = 0;
968
- this.OPEN = 1;
969
- this.CLOSED = 2;
970
-
971
- this.url = url;
972
-
973
- options = options || {};
974
- this.headers = options.headers || {};
975
- this.payload = options.payload !== undefined ? options.payload : '';
976
- this.method = options.method || (this.payload && 'POST') || 'GET';
977
- this.withCredentials = !!options.withCredentials;
978
-
979
- this.FIELD_SEPARATOR = ':';
980
- this.listeners = {};
981
-
982
- this.xhr = null;
983
- this.readyState = this.INITIALIZING;
984
- this.progress = 0;
985
- this.chunk = '';
986
-
987
- this.addEventListener = function (type, listener) {
988
- if (this.listeners[type] === undefined) {
989
- this.listeners[type] = [];
990
- }
991
-
992
- if (this.listeners[type].indexOf(listener) === -1) {
993
- this.listeners[type].push(listener);
994
- }
995
- };
996
-
997
- this.removeEventListener = function (type, listener) {
998
- if (this.listeners[type] === undefined) {
999
- return;
1000
- }
1001
-
1002
- var filtered = [];
1003
- this.listeners[type].forEach(function (element) {
1004
- if (element !== listener) {
1005
- filtered.push(element);
1006
- }
1007
- });
1008
- if (filtered.length === 0) {
1009
- delete this.listeners[type];
1010
- } else {
1011
- this.listeners[type] = filtered;
1012
- }
1013
- };
1014
-
1015
- this.dispatchEvent = function (e) {
1016
- if (!e) {
1017
- return true;
1018
- }
1019
-
1020
- e.source = this;
1021
-
1022
- var onHandler = 'on' + e.type;
1023
- if (this.hasOwnProperty(onHandler)) {
1024
- this[onHandler].call(this, e);
1025
- if (e.defaultPrevented) {
1026
- return false;
1027
- }
1028
- }
1029
-
1030
- if (this.listeners[e.type]) {
1031
- return this.listeners[e.type].every(function (callback) {
1032
- callback(e);
1033
- return !e.defaultPrevented;
1034
- });
1035
- }
1036
-
1037
- return true;
1038
- };
1039
-
1040
- this._setReadyState = function (state) {
1041
- var event = new CustomEvent('readystatechange');
1042
- event.readyState = state;
1043
- this.readyState = state;
1044
- this.dispatchEvent(event);
1045
- };
1046
-
1047
- this._onStreamFailure = function (e) {
1048
- var event = new CustomEvent('error');
1049
- event.data = e.currentTarget.response;
1050
- this.dispatchEvent(event);
1051
- this.close();
1052
- };
1053
-
1054
- this._onStreamAbort = function (e) {
1055
- this.dispatchEvent(new CustomEvent('abort'));
1056
- this.close();
1057
- };
1058
-
1059
- this._onStreamProgress = async function (e) {
1060
- if (!this.xhr) {
1061
- return;
1062
- }
1063
-
1064
- if (this.xhr.status === 401 && !this._retry) {
1065
- this._retry = true;
1066
- try {
1067
- const refreshResponse = await refreshToken();
1068
- this.headers = {
1069
- 'Content-Type': 'application/json',
1070
- Authorization: `Bearer ${refreshResponse.token}`,
1071
- };
1072
- setTokenHeader(refreshResponse.token);
1073
- window.dispatchEvent(new CustomEvent('tokenUpdated', { detail: refreshResponse.token }));
1074
- this.stream();
1075
- } catch (err) {
1076
- this._onStreamFailure(e);
1077
- return;
1078
- }
1079
- } else if (this.xhr.status !== 200) {
1080
- this._onStreamFailure(e);
1081
- return;
1082
- }
1083
-
1084
- if (this.readyState == this.CONNECTING) {
1085
- this.dispatchEvent(new CustomEvent('open'));
1086
- this._setReadyState(this.OPEN);
1087
- }
1088
-
1089
- var data = this.xhr.responseText.substring(this.progress);
1090
- this.progress += data.length;
1091
- data.split(/(\r\n|\r|\n){2}/g).forEach(
1092
- function (part) {
1093
- if (part.trim().length === 0) {
1094
- this.dispatchEvent(this._parseEventChunk(this.chunk.trim()));
1095
- this.chunk = '';
1096
- } else {
1097
- this.chunk += part;
1098
- }
1099
- }.bind(this),
1100
- );
1101
- };
1102
-
1103
- this._onStreamLoaded = function (e) {
1104
- this._onStreamProgress(e);
1105
-
1106
- // Parse the last chunk.
1107
- this.dispatchEvent(this._parseEventChunk(this.chunk));
1108
- this.chunk = '';
1109
- };
1110
-
1111
- /**
1112
- * Parse a received SSE event chunk into a constructed event object.
1113
- */
1114
- this._parseEventChunk = function (chunk) {
1115
- if (!chunk || chunk.length === 0) {
1116
- return null;
1117
- }
1118
-
1119
- var e = { id: null, retry: null, data: '', event: 'message' };
1120
- chunk.split(/\n|\r\n|\r/).forEach(
1121
- function (line) {
1122
- line = line.trimRight();
1123
- var index = line.indexOf(this.FIELD_SEPARATOR);
1124
- if (index <= 0) {
1125
- // Line was either empty, or started with a separator and is a comment.
1126
- // Either way, ignore.
1127
- return;
1128
- }
1129
-
1130
- var field = line.substring(0, index);
1131
- if (!(field in e)) {
1132
- return;
1133
- }
1134
-
1135
- var value = line.substring(index + 1).trimLeft();
1136
- if (field === 'data') {
1137
- e[field] += value;
1138
- } else {
1139
- e[field] = value;
1140
- }
1141
- }.bind(this),
1142
- );
1143
-
1144
- var event = new CustomEvent(e.event);
1145
- event.data = e.data;
1146
- event.id = e.id;
1147
- return event;
1148
- };
1149
-
1150
- this._checkStreamClosed = function () {
1151
- if (!this.xhr) {
1152
- return;
1153
- }
1154
-
1155
- if (this.xhr.readyState === XMLHttpRequest.DONE) {
1156
- this._setReadyState(this.CLOSED);
1157
- }
1158
- };
1159
-
1160
- this.stream = function () {
1161
- this._setReadyState(this.CONNECTING);
1162
-
1163
- this.xhr = new XMLHttpRequest();
1164
- this.xhr.addEventListener('progress', this._onStreamProgress.bind(this));
1165
- this.xhr.addEventListener('load', this._onStreamLoaded.bind(this));
1166
- this.xhr.addEventListener('readystatechange', this._checkStreamClosed.bind(this));
1167
- this.xhr.addEventListener('error', this._onStreamFailure.bind(this));
1168
- this.xhr.addEventListener('abort', this._onStreamAbort.bind(this));
1169
- this.xhr.open(this.method, this.url);
1170
- for (var header in this.headers) {
1171
- this.xhr.setRequestHeader(header, this.headers[header]);
1172
- }
1173
- this.xhr.withCredentials = this.withCredentials;
1174
- this.xhr.send(this.payload);
1175
- };
1176
-
1177
- this.close = function () {
1178
- if (this.readyState === this.CLOSED) {
1179
- return;
1180
- }
1181
-
1182
- this.xhr.abort();
1183
- this.xhr = null;
1184
- this._setReadyState(this.CLOSED);
1185
- };
1186
- };
1187
- // Export our SSE module for npm.js
1188
- // if (typeof exports !== 'undefined') {
1189
- // // exports.SSE = SSE;
1190
- // module.exports = { SSE };
1191
- // }
1192
-
1193
- function createPayload(submission) {
1194
- var conversation = submission.conversation, message = submission.message, endpointOption = submission.endpointOption, isEdited = submission.isEdited, isContinued = submission.isContinued;
1195
- var conversationId = tConversationSchema.parse(conversation).conversationId;
1196
- var endpoint = endpointOption.endpoint;
1197
- var endpointUrlMap = {
1198
- azureOpenAI: '/api/ask/azureOpenAI',
1199
- openAI: '/api/ask/openAI',
1200
- google: '/api/ask/google',
1201
- bingAI: '/api/ask/bingAI',
1202
- chatGPT: '/api/ask/chatGPT',
1203
- chatGPTBrowser: '/api/ask/chatGPTBrowser',
1204
- gptPlugins: '/api/ask/gptPlugins',
1205
- anthropic: '/api/ask/anthropic',
1206
- };
1207
- var server = endpointUrlMap[endpoint];
1208
- if (isEdited) {
1209
- server = server.replace('/ask/', '/edit/');
1210
- }
1211
- var payload = __assign(__assign(__assign({}, message), endpointOption), { isContinued: isEdited && isContinued, conversationId: conversationId });
1212
- return { server: server, payload: payload };
1213
- }
1214
-
1215
- export { EModelEndpoint, QueryKeys, SSE, abortRequestWithMessage, anthropicSchema, bingAISchema, chatGPTBrowserSchema, clearAllConversations, createPayload, createPreset, deleteConversation, deletePreset, eModelEndpointSchema, getAIEndpoints, getAvailablePlugins, getConversationById, getConversations, getLoginGoogle, getMessagesByConvoId, getModels, getPresets, getResponseSender, getSearchEnabled, getStartupConfig, getUser, getUserBalance, googleSchema, gptPluginsSchema, login, logout, openAISchema, parseConvo, refreshToken, register, request, requestPasswordReset, resetPassword, revokeAllUserKeys, revokeUserKey, searchConversations, setAcceptLanguageHeader, setTokenHeader, tAgentOptionsSchema, tConversationSchema, tExampleSchema, tMessageSchema, tPluginAuthConfigSchema, tPluginSchema, tPresetSchema, updateConversation, updateMessage, updatePreset, updateTokenCount, updateUserKey, updateUserPlugins, useAbortRequestWithMessage, useAvailablePluginsQuery, useClearConversationsMutation, useCreatePresetMutation, useDeleteConversationMutation, useDeletePresetMutation, useGetConversationByIdMutation, useGetConversationByIdQuery, useGetConversationsQuery, useGetEndpointsQuery, useGetMessagesByConvoId, useGetModelsQuery, useGetPresetsQuery, useGetSearchEnabledQuery, useGetStartupConfig, useGetUserBalance, useGetUserQuery, useLoginUserMutation, useLogoutUserMutation, useRefreshTokenMutation, useRegisterUserMutation, useRequestPasswordResetMutation, useResetPasswordMutation, useRevokeAllUserKeysMutation, useRevokeUserKeyMutation, useSearchQuery, useUpdateConversationMutation, useUpdateMessageMutation, useUpdatePresetMutation, useUpdateTokenCountMutation, useUpdateUserKeysMutation, useUpdateUserPluginsMutation, useUserKeyQuery, userKeyQuery };
1
+ import{z as t}from"zod";import e from"axios";var n,r,o,i,a,s,l=function(){return l=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var o in e=arguments[n])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},l.apply(this,arguments)};function u(t,e,n,r){return new(n||(n=Promise))((function(o,i){function a(t){try{l(r.next(t))}catch(t){i(t)}}function s(t){try{l(r.throw(t))}catch(t){i(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,s)}l((r=r.apply(t,e||[])).next())}))}function p(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(s){return function(l){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i&&(i=0,s[0]&&(a=0)),a;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!(o=a.trys,(o=o.length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){a.label=s[1];break}if(6===s[0]&&a.label<o[1]){a.label=o[1],o=s;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(s);break}o[2]&&a.ops.pop(),a.trys.pop();continue}s=e.call(t,a)}catch(t){s=[6,t],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,l])}}}"function"==typeof SuppressedError&&SuppressedError,function(t){t.azureOpenAI="azureOpenAI",t.openAI="openAI",t.bingAI="bingAI",t.chatGPTBrowser="chatGPTBrowser",t.google="google",t.gptPlugins="gptPlugins",t.anthropic="anthropic",t.assistant="assistant"}(s||(s={}));var c=[s.openAI,s.assistant,s.azureOpenAI,s.bingAI,s.chatGPTBrowser,s.gptPlugins,s.google,s.anthropic],d=((n={})[s.openAI]="OpenAI",n[s.assistant]="Assistants",n[s.azureOpenAI]="Azure OpenAI",n[s.bingAI]="Bing",n[s.chatGPTBrowser]="ChatGPT",n[s.gptPlugins]="Plugins",n[s.google]="Google",n[s.anthropic]="Anthropic",n),h=((r={})[s.google]={model:{default:"chat-bison"},maxOutputTokens:{min:1,max:2048,step:1,default:1024},temperature:{min:0,max:1,step:.01,default:.2},topP:{min:0,max:1,step:.01,default:.8},topK:{min:1,max:40,step:.01,default:40}},r),f=h[s.google],g=((o={})[s.azureOpenAI]="/api/ask/azureOpenAI",o[s.openAI]="/api/ask/openAI",o[s.bingAI]="/api/ask/bingAI",o[s.chatGPTBrowser]="/api/ask/chatGPTBrowser",o[s.google]="/api/ask/google",o[s.gptPlugins]="/api/ask/gptPlugins",o[s.anthropic]="/api/ask/anthropic",o[s.assistant]="/api/assistants/chat",o),m=new Set([s.gptPlugins,s.anthropic,s.google,s.openAI]),v=((i={})[s.openAI]=!0,i[s.assistant]=!0,i),b=["gpt-3.5-turbo-16k-0613","gpt-3.5-turbo-16k","gpt-4-1106-preview","gpt-3.5-turbo","gpt-3.5-turbo-1106","gpt-4-vision-preview","gpt-4","gpt-3.5-turbo-instruct-0914","gpt-3.5-turbo-0613","gpt-3.5-turbo-0301","gpt-3.5-turbo-instruct","gpt-4-0613","text-davinci-003","gpt-4-0314"],y=["gpt-4-vision","llava-13b"],P=t.nativeEnum(s),x=t.object({authField:t.string(),label:t.string(),description:t.string()}),k=t.object({name:t.string(),pluginKey:t.string(),description:t.string(),icon:t.string(),authConfig:t.array(x),authenticated:t.boolean().optional(),isButton:t.boolean().optional()}),I=t.object({input:t.object({content:t.string()}),output:t.object({content:t.string()})}),_=t.object({agent:t.string(),skipCompletion:t.boolean(),model:t.string(),temperature:t.number()}),O=t.object({messageId:t.string(),clientId:t.string().nullable().optional(),conversationId:t.string().nullable(),parentMessageId:t.string().nullable(),responseMessageId:t.string().nullable().optional(),overrideParentMessageId:t.string().nullable().optional(),bg:t.string().nullable().optional(),model:t.string().nullable().optional(),title:t.string().nullable().or(t.literal("New Chat")).default("New Chat"),sender:t.string(),text:t.string(),generation:t.string().nullable().optional(),isEdited:t.boolean().optional(),isCreatedByUser:t.boolean(),error:t.boolean(),createdAt:t.string().optional().default((function(){return(new Date).toISOString()})),updatedAt:t.string().optional().default((function(){return(new Date).toISOString()})),current:t.boolean().optional(),unfinished:t.boolean().optional(),submitting:t.boolean().optional(),searchResult:t.boolean().optional(),finish_reason:t.string().optional()}),w=t.object({conversationId:t.string().nullable(),title:t.string().nullable().or(t.literal("New Chat")).default("New Chat"),user:t.string().optional(),endpoint:P.nullable(),suggestions:t.array(t.string()).optional(),messages:t.array(t.string()).optional(),tools:t.array(k).optional(),createdAt:t.string(),updatedAt:t.string(),systemMessage:t.string().nullable().optional(),modelLabel:t.string().nullable().optional(),examples:t.array(I).optional(),chatGptLabel:t.string().nullable().optional(),userLabel:t.string().optional(),model:t.string().nullable().optional(),promptPrefix:t.string().nullable().optional(),temperature:t.number().optional(),topP:t.number().optional(),topK:t.number().optional(),context:t.string().nullable().optional(),top_p:t.number().optional(),frequency_penalty:t.number().optional(),presence_penalty:t.number().optional(),jailbreak:t.boolean().optional(),jailbreakConversationId:t.string().nullable().optional(),conversationSignature:t.string().nullable().optional(),parentMessageId:t.string().optional(),clientId:t.string().nullable().optional(),invocationId:t.number().nullable().optional(),toneStyle:t.string().nullable().optional(),maxOutputTokens:t.number().optional(),agentOptions:_.nullable().optional(),assistant_id:t.string().optional(),thread_id:t.string().optional()}),C=w.omit({conversationId:!0,createdAt:!0,updatedAt:!0,title:!0}).merge(t.object({conversationId:t.string().optional(),presetId:t.string().nullable().optional(),title:t.string().nullable().optional(),defaultPreset:t.boolean().optional(),order:t.number().optional()})),A=w.pick({model:!0,chatGptLabel:!0,promptPrefix:!0,temperature:!0,top_p:!0,presence_penalty:!0,frequency_penalty:!0}).transform((function(t){var e,n,r,o,i,a,s;return l(l({},t),{model:null!==(e=t.model)&&void 0!==e?e:"gpt-3.5-turbo",chatGptLabel:null!==(n=t.chatGptLabel)&&void 0!==n?n:null,promptPrefix:null!==(r=t.promptPrefix)&&void 0!==r?r:null,temperature:null!==(o=t.temperature)&&void 0!==o?o:1,top_p:null!==(i=t.top_p)&&void 0!==i?i:1,presence_penalty:null!==(a=t.presence_penalty)&&void 0!==a?a:0,frequency_penalty:null!==(s=t.frequency_penalty)&&void 0!==s?s:0})})).catch((function(){return{model:"gpt-3.5-turbo",chatGptLabel:null,promptPrefix:null,temperature:1,top_p:1,presence_penalty:0,frequency_penalty:0}})),E=w.pick({model:!0,modelLabel:!0,promptPrefix:!0,examples:!0,temperature:!0,maxOutputTokens:!0,topP:!0,topK:!0}).transform((function(t){var e,n,r,o,i,a,s,u;return l(l({},t),{model:null!==(e=t.model)&&void 0!==e?e:f.model.default,modelLabel:null!==(n=t.modelLabel)&&void 0!==n?n:null,promptPrefix:null!==(r=t.promptPrefix)&&void 0!==r?r:null,examples:null!==(o=t.examples)&&void 0!==o?o:[{input:{content:""},output:{content:""}}],temperature:null!==(i=t.temperature)&&void 0!==i?i:f.temperature.default,maxOutputTokens:null!==(a=t.maxOutputTokens)&&void 0!==a?a:f.maxOutputTokens.default,topP:null!==(s=t.topP)&&void 0!==s?s:f.topP.default,topK:null!==(u=t.topK)&&void 0!==u?u:f.topK.default})})).catch((function(){return{model:f.model.default,modelLabel:null,promptPrefix:null,examples:[{input:{content:""},output:{content:""}}],temperature:f.temperature.default,maxOutputTokens:f.maxOutputTokens.default,topP:f.topP.default,topK:f.topK.default}})),S=w.pick({jailbreak:!0,systemMessage:!0,context:!0,toneStyle:!0,jailbreakConversationId:!0,conversationSignature:!0,clientId:!0,invocationId:!0}).transform((function(t){var e,n,r,o,i,a,s,u;return l(l({},t),{model:"",jailbreak:null!==(e=t.jailbreak)&&void 0!==e&&e,systemMessage:null!==(n=t.systemMessage)&&void 0!==n?n:null,context:null!==(r=t.context)&&void 0!==r?r:null,toneStyle:null!==(o=t.toneStyle)&&void 0!==o?o:"creative",jailbreakConversationId:null!==(i=t.jailbreakConversationId)&&void 0!==i?i:null,conversationSignature:null!==(a=t.conversationSignature)&&void 0!==a?a:null,clientId:null!==(s=t.clientId)&&void 0!==s?s:null,invocationId:null!==(u=t.invocationId)&&void 0!==u?u:1})})).catch((function(){return{model:"",jailbreak:!1,systemMessage:null,context:null,toneStyle:"creative",jailbreakConversationId:null,conversationSignature:null,clientId:null,invocationId:1}})),T=w.pick({model:!0,modelLabel:!0,promptPrefix:!0,temperature:!0,maxOutputTokens:!0,topP:!0,topK:!0}).transform((function(t){var e,n,r,o,i,a,s;return l(l({},t),{model:null!==(e=t.model)&&void 0!==e?e:"claude-1",modelLabel:null!==(n=t.modelLabel)&&void 0!==n?n:null,promptPrefix:null!==(r=t.promptPrefix)&&void 0!==r?r:null,temperature:null!==(o=t.temperature)&&void 0!==o?o:1,maxOutputTokens:null!==(i=t.maxOutputTokens)&&void 0!==i?i:4e3,topP:null!==(a=t.topP)&&void 0!==a?a:.7,topK:null!==(s=t.topK)&&void 0!==s?s:5})})).catch((function(){return{model:"claude-1",modelLabel:null,promptPrefix:null,temperature:1,maxOutputTokens:4e3,topP:.7,topK:5}})),L=w.pick({model:!0}).transform((function(t){var e;return l(l({},t),{model:null!==(e=t.model)&&void 0!==e?e:"text-davinci-002-render-sha"})})).catch((function(){return{model:"text-davinci-002-render-sha"}})),G=w.pick({model:!0,chatGptLabel:!0,promptPrefix:!0,temperature:!0,top_p:!0,presence_penalty:!0,frequency_penalty:!0,tools:!0,agentOptions:!0}).transform((function(t){var e,n,r,o,i,a,s,u,p;return l(l({},t),{model:null!==(e=t.model)&&void 0!==e?e:"gpt-3.5-turbo",chatGptLabel:null!==(n=t.chatGptLabel)&&void 0!==n?n:null,promptPrefix:null!==(r=t.promptPrefix)&&void 0!==r?r:null,temperature:null!==(o=t.temperature)&&void 0!==o?o:.8,top_p:null!==(i=t.top_p)&&void 0!==i?i:1,presence_penalty:null!==(a=t.presence_penalty)&&void 0!==a?a:0,frequency_penalty:null!==(s=t.frequency_penalty)&&void 0!==s?s:0,tools:null!==(u=t.tools)&&void 0!==u?u:[],agentOptions:null!==(p=t.agentOptions)&&void 0!==p?p:{agent:"functions",skipCompletion:!0,model:"gpt-3.5-turbo",temperature:0}})})).catch((function(){return{model:"gpt-3.5-turbo",chatGptLabel:null,promptPrefix:null,temperature:.8,top_p:1,presence_penalty:0,frequency_penalty:0,tools:[],agentOptions:{agent:"functions",skipCompletion:!0,model:"gpt-3.5-turbo",temperature:0}}}));function j(t){var e=l({},t);return Object.keys(e).forEach((function(t){void 0!==e[t]&&null!==e[t]&&""!==e[t]||delete e[t]})),e}var K=w.pick({model:!0,assistant_id:!0,thread_id:!0}).transform(j).catch((function(){return{}})),N=((a={})[s.openAI]=A,a[s.azureOpenAI]=A,a[s.google]=E,a[s.bingAI]=S,a[s.anthropic]=T,a[s.chatGPTBrowser]=L,a[s.gptPlugins]=G,a[s.assistant]=K,a);function q(t){for(var e,n=0,r=t;n<r.length;n++){var o=r[n];if(o){e=o;break}}return e}var B,M,R,z=function(t,e,n){var r,o,i=N[t];if(!i)throw new Error("Unknown endpoint: ".concat(t));var a=i.parse(e),s=null!=n?n:{},l=s.models,u=s.secondaryModels;return l&&a&&(a.model=null!==(r=q(l))&&void 0!==r?r:a.model),u&&a.agentOptions&&(a.agentOptions.model=null!==(o=q(u))&&void 0!==o?o:a.agentOptions.model),a},U=function(t){var e,n=t.model,r=t.endpoint,o=t.chatGptLabel,i=t.modelLabel,a=t.jailbreak;return[s.openAI,s.azureOpenAI,s.gptPlugins,s.chatGPTBrowser].includes(r)?o||(n&&n.includes("gpt-3")?"GPT-3.5":n&&n.includes("gpt-4")?"GPT-4":null!==(e=d[r])&&void 0!==e?e:"ChatGPT"):r===s.bingAI?a?"Sydney":"BingAI":r===s.anthropic?null!=i?i:"Claude":r===s.google?i||(n&&n.includes("code")?"Codey":"PaLM2"):""},D=w.pick({model:!0,chatGptLabel:!0,promptPrefix:!0,temperature:!0,top_p:!0,presence_penalty:!0,frequency_penalty:!0}).transform((function(t){var e=l({},t);return"gpt-3.5-turbo"===e.model&&delete e.model,1===e.temperature&&delete e.temperature,1===e.top_p&&delete e.top_p,0===e.presence_penalty&&delete e.presence_penalty,0===e.frequency_penalty&&delete e.frequency_penalty,j(e)})).catch((function(){return{}})),F=w.pick({model:!0,modelLabel:!0,promptPrefix:!0,examples:!0,temperature:!0,maxOutputTokens:!0,topP:!0,topK:!0}).transform((function(t){var e=l({},t);return e.model===f.model.default&&delete e.model,e.temperature===f.temperature.default&&delete e.temperature,e.maxOutputTokens===f.maxOutputTokens.default&&delete e.maxOutputTokens,e.topP===f.topP.default&&delete e.topP,e.topK===f.topK.default&&delete e.topK,j(e)})).catch((function(){return{}})),H=w.pick({model:!0,modelLabel:!0,promptPrefix:!0,temperature:!0,maxOutputTokens:!0,topP:!0,topK:!0}).transform((function(t){var e=l({},t);return"claude-1"===e.model&&delete e.model,1===e.temperature&&delete e.temperature,4e3===e.maxOutputTokens&&delete e.maxOutputTokens,.7===e.topP&&delete e.topP,5===e.topK&&delete e.topK,j(e)})).catch((function(){return{}})),J=w.pick({model:!0}).transform((function(t){var e=l({},t);return"text-davinci-002-render-sha"===e.model&&delete e.model,j(e)})).catch((function(){return{}})),W=w.pick({model:!0,chatGptLabel:!0,promptPrefix:!0,temperature:!0,top_p:!0,presence_penalty:!0,frequency_penalty:!0,tools:!0,agentOptions:!0}).transform((function(t){var e,n=l({},t);return"gpt-3.5-turbo"===n.model&&delete n.model,null===n.chatGptLabel&&delete n.chatGptLabel,null===n.promptPrefix&&delete n.promptPrefix,.8===n.temperature&&delete n.temperature,1===n.top_p&&delete n.top_p,0===n.presence_penalty&&delete n.presence_penalty,0===n.frequency_penalty&&delete n.frequency_penalty,0===(null===(e=n.tools)||void 0===e?void 0:e.length)&&delete n.tools,n.agentOptions&&"functions"===n.agentOptions.agent&&!0===n.agentOptions.skipCompletion&&"gpt-3.5-turbo"===n.agentOptions.model&&0===n.agentOptions.temperature&&delete n.agentOptions,j(n)})).catch((function(){return{}})),X={openAI:D,azureOpenAI:D,assistant:K,google:F,bingAI:S,anthropic:H,chatGPTBrowser:J,gptPlugins:W},Z=function(t,e,n){var r;if(!t)throw new Error("undefined endpoint: ".concat(t));var o=X[t];if(!o)throw new Error("Unknown endpoint: ".concat(t));var i=o.parse(e),a=(null!=n?n:{}).models;return a&&i&&(i.model=null!==(r=q(a))&&void 0!==r?r:i.model),i};function Q(t){e.defaults.headers.common["Accept-Language"]=t}function $(t){e.defaults.headers.common.Authorization="Bearer "+t}!function(t){t.code_interpreter="code_interpreter",t.retrieval="retrieval",t.function="function"}(B||(B={})),function(t){t.messages="messages",t.allConversations="allConversations",t.conversation="conversation",t.searchEnabled="searchEnabled",t.user="user",t.name="name",t.models="models",t.balance="balance",t.endpoints="endpoints",t.presets="presets",t.searchResults="searchResults",t.tokenCount="tokenCount",t.availablePlugins="availablePlugins",t.startupConfig="startupConfig",t.assistants="assistants",t.assistant="assistant",t.endpointsConfigOverride="endpointsConfigOverride"}(M||(M={})),function(t){t.imageUpload="imageUpload",t.fileDelete="fileDelete",t.updatePreset="updatePreset",t.deletePreset="deletePreset",t.logoutUser="logoutUser"}(R||(R={}));var V=function(t,e){return"/api/messages/".concat(t).concat(e?"/".concat(e):"")},Y="/api/keys",tt=function(t,e){return"/api/search?q=".concat(t,"&pageNumber=").concat(e)},et=function(t){return"/api/assistants".concat(t?"/".concat(t):"")};function nt(t,n){return u(this,void 0,void 0,(function(){return p(this,(function(r){switch(r.label){case 0:return[4,e.post(t,JSON.stringify(n),{headers:{"Content-Type":"application/json"}})];case 1:return[2,r.sent().data]}}))}))}var rt=!1,ot=[],it=function(t){return nt(function(t){return"/api/auth/refresh".concat(t?"?retry=true":"")}(t))},at=function(t,e){void 0===e&&(e=null),ot.forEach((function(n){t?n.reject(t):n.resolve(e)})),ot=[]};e.interceptors.response.use((function(t){return t}),(function(t){return u(void 0,void 0,void 0,(function(){var n,r,o,i,a;return p(this,(function(s){switch(s.label){case 0:if(n=t.config,401!==t.response.status||n._retry)return[3,13];if(n._retry=!0,!rt)return[3,5];s.label=1;case 1:return s.trys.push([1,4,,5]),[4,new Promise((function(t,e){ot.push({resolve:t,reject:e})}))];case 2:return o=s.sent(),n.headers.Authorization="Bearer "+o,[4,e(n)];case 3:return[2,s.sent()];case 4:return r=s.sent(),[2,Promise.reject(r)];case 5:rt=!0,s.label=6;case 6:return s.trys.push([6,11,12,13]),[4,it(!!(null===(a=n.url)||void 0===a?void 0:a.includes("api/auth/refresh")))];case 7:return(o=s.sent().token)?(n.headers.Authorization="Bearer "+o,$(o),window.dispatchEvent(new CustomEvent("tokenUpdated",{detail:o})),at(null,o),[4,e(n)]):[3,9];case 8:return[2,s.sent()];case 9:window.location.href="/login",s.label=10;case 10:return[3,13];case 11:return i=s.sent(),at(i,null),[2,Promise.reject(i)];case 12:return rt=!1,[7];case 13:return[2,Promise.reject(t)]}}))}))}));var st={get:function(t,n){return u(this,void 0,void 0,(function(){return p(this,(function(r){switch(r.label){case 0:return[4,e.get(t,l({},n))];case 1:return[2,r.sent().data]}}))}))},post:nt,postMultiPart:function(t,n,r){return u(this,void 0,void 0,(function(){return p(this,(function(o){switch(o.label){case 0:return[4,e.post(t,n,l(l({},r),{headers:{"Content-Type":"multipart/form-data"}}))];case 1:return[2,o.sent().data]}}))}))},put:function(t,n){return u(this,void 0,void 0,(function(){return p(this,(function(r){switch(r.label){case 0:return[4,e.put(t,JSON.stringify(n),{headers:{"Content-Type":"application/json"}})];case 1:return[2,r.sent().data]}}))}))},delete:function(t){return u(this,void 0,void 0,(function(){return p(this,(function(n){switch(n.label){case 0:return[4,e.delete(t)];case 1:return[2,n.sent().data]}}))}))},deleteWithOptions:function(t,n){return u(this,void 0,void 0,(function(){return p(this,(function(r){switch(r.label){case 0:return[4,e.delete(t,l({},n))];case 1:return[2,r.sent().data]}}))}))},patch:function(t,n){return u(this,void 0,void 0,(function(){return p(this,(function(r){switch(r.label){case 0:return[4,e.patch(t,JSON.stringify(n),{headers:{"Content-Type":"application/json"}})];case 1:return[2,r.sent().data]}}))}))},refreshToken:it};var lt=Object.freeze({__proto__:null,abortRequestWithMessage:function(t,e,n){return st.post(function(t){return"/api/ask/".concat(t,"/abort")}(t),{arg:{abortKey:e,message:n}})},clearAllConversations:function(){return st.post("/api/convos/clear",{arg:{}})},createAssistant:function(t){return st.post(et(),t)},createPreset:function(t){return st.post("/api/presets",t)},deleteAssistant:function(t){return st.delete(et(t))},deleteConversation:function(t){return st.post("/api/convos/clear",{arg:t})},deleteFiles:function(t){return u(void 0,void 0,void 0,(function(){return p(this,(function(e){return[2,st.deleteWithOptions("/api/files",{data:{files:t}})]}))}))},deletePreset:function(t){return st.post("/api/presets/delete",t)},getAIEndpoints:function(){return st.get("/api/endpoints")},getAssistantById:function(t){return st.get(et(t))},getAvailablePlugins:function(){return st.get("/api/plugins")},getConversationById:function(t){return st.get(function(t){return"/api/convos/".concat(t)}(t))},getConversations:function(t){return st.get(function(t){return"/api/convos?pageNumber=".concat(t)}(t))},getEndpointsConfigOverride:function(){return st.get("/api/endpoints/config/override")},getLoginGoogle:function(){return st.get("/api/auth/google")},getMessagesByConvoId:function(t){return"new"===t?Promise.resolve([]):st.get(V(t))},getModels:function(){return u(void 0,void 0,void 0,(function(){return p(this,(function(t){return[2,st.get("/api/models")]}))}))},getPresets:function(){return st.get("/api/presets")},getSearchEnabled:function(){return st.get("/api/search/enable")},getStartupConfig:function(){return st.get("/api/config")},getUser:function(){return st.get("/api/user")},getUserBalance:function(){return st.get("/api/balance")},listAssistants:function(t){return st.get(et(),{params:t})},login:function(t){return st.post("/api/auth/login",t)},logout:function(){return st.post("/api/auth/logout")},register:function(t){return st.post("/api/auth/register",t)},requestPasswordReset:function(t){return st.post("/api/auth/requestPasswordReset",t)},resetPassword:function(t){return st.post("/api/auth/resetPassword",t)},revokeAllUserKeys:function(){return st.delete("".concat(Y,"?all=true"))},revokeUserKey:function(t){return st.delete(function(t){return"".concat(Y,"/").concat(t)}(t))},searchConversations:function(t,e){return u(void 0,void 0,void 0,(function(){return p(this,(function(n){return[2,st.get(tt(t,e))]}))}))},updateAssistant:function(t,e){return st.patch(et(t),e)},updateConversation:function(t){return st.post("/api/convos/update",{arg:t})},updateMessage:function(t){var e=t.conversationId,n=t.messageId,r=t.text;if(!e)throw new Error("conversationId is required");return st.put(V(e,n),{text:r})},updatePreset:function(t){return st.post("/api/presets",t)},updateTokenCount:function(t){return st.post("/api/tokenizer",{arg:t})},updateUserKey:function(t){if(!t.value)throw new Error("value is required");return st.put(Y,t)},updateUserPlugins:function(t){return st.post("/api/user/plugins",t)},uploadImage:function(t){return st.postMultiPart("".concat("/api/files","/images"),t)},userKeyQuery:function(t){return st.get(function(t){return"".concat(Y,"?name=").concat(t)}(t))}}),ut=function(t,e){if(!(this instanceof ut))return new ut(t,e);this.INITIALIZING=-1,this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,this.url=t,e=e||{},this.headers=e.headers||{},this.payload=void 0!==e.payload?e.payload:"",this.method=e.method||this.payload&&"POST"||"GET",this.withCredentials=!!e.withCredentials,this.FIELD_SEPARATOR=":",this.listeners={},this.xhr=null,this.readyState=this.INITIALIZING,this.progress=0,this.chunk="",this.addEventListener=function(t,e){void 0===this.listeners[t]&&(this.listeners[t]=[]),-1===this.listeners[t].indexOf(e)&&this.listeners[t].push(e)},this.removeEventListener=function(t,e){if(void 0!==this.listeners[t]){var n=[];this.listeners[t].forEach((function(t){t!==e&&n.push(t)})),0===n.length?delete this.listeners[t]:this.listeners[t]=n}},this.dispatchEvent=function(t){if(!t)return!0;t.source=this;var e="on"+t.type;return(!this.hasOwnProperty(e)||(this[e].call(this,t),!t.defaultPrevented))&&(!this.listeners[t.type]||this.listeners[t.type].every((function(e){return e(t),!t.defaultPrevented})))},this._setReadyState=function(t){var e=new CustomEvent("readystatechange");e.readyState=t,this.readyState=t,this.dispatchEvent(e)},this._onStreamFailure=function(t){var e=new CustomEvent("error");e.data=t.currentTarget.response,this.dispatchEvent(e),this.close()},this._onStreamAbort=function(t){this.dispatchEvent(new CustomEvent("abort")),this.close()},this._onStreamProgress=async function(t){if(this.xhr){if(401!==this.xhr.status||this._retry){if(200!==this.xhr.status)return void this._onStreamFailure(t)}else{this._retry=!0;try{const t=await st.refreshToken();this.headers={"Content-Type":"application/json",Authorization:`Bearer ${t.token}`},$(t.token),window.dispatchEvent(new CustomEvent("tokenUpdated",{detail:t.token})),this.stream()}catch(e){return void this._onStreamFailure(t)}}this.readyState==this.CONNECTING&&(this.dispatchEvent(new CustomEvent("open")),this._setReadyState(this.OPEN));var e=this.xhr.responseText.substring(this.progress);this.progress+=e.length,e.split(/(\r\n|\r|\n){2}/g).forEach(function(t){0===t.trim().length?(this.dispatchEvent(this._parseEventChunk(this.chunk.trim())),this.chunk=""):this.chunk+=t}.bind(this))}},this._onStreamLoaded=function(t){this._onStreamProgress(t),this.dispatchEvent(this._parseEventChunk(this.chunk)),this.chunk=""},this._parseEventChunk=function(t){if(!t||0===t.length)return null;var e={id:null,retry:null,data:"",event:"message"};t.split(/\n|\r\n|\r/).forEach(function(t){var n=(t=t.trimRight()).indexOf(this.FIELD_SEPARATOR);if(!(n<=0)){var r=t.substring(0,n);if(r in e){var o=t.substring(n+1).trimLeft();"data"===r?e[r]+=o:e[r]=o}}}.bind(this));var n=new CustomEvent(e.event);return n.data=e.data,n.id=e.id,n},this._checkStreamClosed=function(){this.xhr&&this.xhr.readyState===XMLHttpRequest.DONE&&this._setReadyState(this.CLOSED)},this.stream=function(){for(var t in this._setReadyState(this.CONNECTING),this.xhr=new XMLHttpRequest,this.xhr.addEventListener("progress",this._onStreamProgress.bind(this)),this.xhr.addEventListener("load",this._onStreamLoaded.bind(this)),this.xhr.addEventListener("readystatechange",this._checkStreamClosed.bind(this)),this.xhr.addEventListener("error",this._onStreamFailure.bind(this)),this.xhr.addEventListener("abort",this._onStreamAbort.bind(this)),this.xhr.open(this.method,this.url),this.headers)this.xhr.setRequestHeader(t,this.headers[t]);this.xhr.withCredentials=this.withCredentials,this.xhr.send(this.payload)},this.close=function(){this.readyState!==this.CLOSED&&(this.xhr.abort(),this.xhr=null,this._setReadyState(this.CLOSED))}};function pt(t){var e=t.conversation,n=t.message,r=t.messages,o=t.endpointOption,i=t.isEdited,a=t.isContinued,u=w.parse(e).conversationId,p=o.endpoint,c=g[p];i&&p===s.assistant?c+="/modify":i&&(c=c.replace("/ask/","/edit/"));var d=l(l(l({},n),o),{isContinued:!(!i||!a),conversationId:u});return p===s.assistant&&(d.messages=r),{server:c,payload:d}}export{s as EModelEndpoint,g as EndpointURLs,R as MutationKeys,M as QueryKeys,ut as SSE,B as Tools,d as alternateName,T as anthropicSchema,K as assistantSchema,S as bingAISchema,L as chatGPTBrowserSchema,H as compactAnthropicSchema,J as compactChatGPTSchema,F as compactGoogleSchema,D as compactOpenAISchema,W as compactPluginsSchema,pt as createPayload,lt as dataService,c as defaultEndpoints,P as eModelEndpointSchema,h as endpointSettings,q as getFirstDefinedValue,U as getResponseSender,E as googleSchema,G as gptPluginsSchema,m as modularEndpoints,b as openAIModels,A as openAISchema,Z as parseCompactConvo,z as parseConvo,j as removeNullishValues,st as request,Q as setAcceptLanguageHeader,$ as setTokenHeader,v as supportsFiles,_ as tAgentOptionsSchema,w as tConversationSchema,I as tExampleSchema,O as tMessageSchema,x as tPluginAuthConfigSchema,k as tPluginSchema,C as tPresetSchema,y as visionModels};
2
+ //# sourceMappingURL=index.es.js.map