-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.js
More file actions
2067 lines (1780 loc) · 74.2 KB
/
app.js
File metadata and controls
2067 lines (1780 loc) · 74.2 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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Get DOM elements
const landingBtn = document.getElementById("landingBtn");
const currentChatBtn = document.getElementById("threadsBtn");
const settingsBtn = document.getElementById("settingsBtn");
const userSettings = document.getElementById("userSettings");
const settingsModal = document.getElementById("settingsModal");
const apiKeyForm = document.getElementById("apiKeyForm");
const messageInput = document.getElementById("messageInput");
const sendBtn = document.getElementById("sendBtn");
const chatMessages = document.getElementById("chatMessages");
const createCharacterBtn = document.getElementById("createCharacterBtn");
const characterModal = document.getElementById("characterModal");
const characterForm = document.getElementById("characterForm");
const modelSettingsBtn = document.getElementById('modelSettingsBtn');
const modelSettingsModal = document.getElementById('modelSettingsModal');
const modelSettingsForm = document.getElementById('modelSettingsForm');
// Toggle left column visibility
const toggleSidebar = document.getElementById('toggleSidebar');
const leftColumn = document.querySelector('.left-column');
const expandSidebar = document.getElementById('expandSidebar');
const purgeDataBtn = document.getElementById('purgeDataBtn');
const middleColumn = document.querySelector('.middle-column'); // Add this line to your script
import {
$,
$$,
delay,
showEl,
hideEl,
prompt2,
sanitizeHtml,
textToSpeech,
} from "./utils.js";
import models from "./models.js";
import modelSettings from './modelSettings.js';
import { renderMarkdown } from './markdown.js';
import starterCharacters from './starterCharacters.js';
let db = new Dexie("GrimDBAlpha");
db.version(95).stores({
characters:
"++id,name,systemMessage,modelVersion,preset,temp,preamble,initialMessages,avatarUrl,creationTime,additionalParameters,cfg_uc,max_length,lastMessageTime,sceneBackground",
threads: "++id,name,characterId,creationTime,lastMessageTime,conversationHistory",
messages: "++id,threadId,message,characterId,creationTime",
misc: "key,value",
settings: "++id,claudeKey,gptKey", // Make sure this line is correctly defined
modelSettings: "++id,name,settings",
presets: '++id, name, modelName, settings',
});
window.db = db;
// Set up MutationObserver to monitor changes in the #chatMessages container
const chatMessagesObserver = new MutationObserver((mutations) => {
console.log("MutationObserver triggered"); // Log when observer is triggered
mutations.forEach((mutation) => {
console.log("Mutation type:", mutation.type); // Log mutation type
if (mutation.type === 'childList' || mutation.type === 'subtree') {
const chatMessagesContainer = document.getElementById('chatMessages');
// Scroll to the bottom of the container
chatMessagesContainer.scrollTop = chatMessagesContainer.scrollHeight;
console.log("Scrolled to bottom:", chatMessagesContainer.scrollTop, chatMessagesContainer.scrollHeight); // Log scroll action
}
});
});
// Start observing the #chatMessages container
const chatMessagesContainer = document.getElementById('chatMessages');
if (chatMessagesContainer) {
console.log("#chatMessages element found, starting observer"); // Log if the element is found
chatMessagesObserver.observe(chatMessagesContainer, {
childList: true,
subtree: true,
});
} else {
console.error("#chatMessages element not found, observer not started"); // Log if the element is not found
}
// Event listeners
landingBtn.addEventListener("click", showLandingPage);
settingsBtn.addEventListener("click", showUserSettings);
// Update the event listener for the "Current Chat" button
currentChatBtn.addEventListener("click", showCurrentChat);
toggleSidebar.addEventListener('click', () => {
leftColumn.classList.add('collapsed');
middleColumn.style.width = '100%'; // Adjust to use full width when left column is collapsed
});
expandSidebar.addEventListener('click', () => {
leftColumn.classList.remove('collapsed');
middleColumn.style.width = 'calc(100% - 300px)'; // Reset width when left column is expanded
});
function closeEditCharacterModal() {
document.getElementById('editCharacterModal').style.display = 'none';
}
function showLandingPage() {
document.getElementById("landingPage").style.display = "grid";
document.getElementById("currentChat").style.display = "none";
displayCharacters(); // Call displayCharacters here
displayStarterCharacters();
}
function showCurrentChat() {
let currentThreadId = getCurrentThreadId();
console.log("Current Thread ID on showCurrentChat:", currentThreadId);
// Hide the landing page and character cards
document.getElementById("landingPage").style.display = "none";
// Show the current chat
document.getElementById("currentChat").style.display = "flex";
if (currentThreadId === null) {
db.misc
.get("lastUsedThreadId")
.then((lastUsedThreadId) => {
if (lastUsedThreadId) {
currentThreadId = lastUsedThreadId.value;
console.log("Last used thread ID retrieved:", currentThreadId);
setCurrentThreadId(currentThreadId);
displayMessagesForThread(currentThreadId);
} else {
chatMessages.innerHTML =
"No thread selected. Please select a thread from the thread list.";
}
})
.catch((error) => {
console.error("Error retrieving last used thread ID:", error);
});
} else {
displayMessagesForThread(currentThreadId);
}
}
function setCurrentThreadId(threadId) {
currentThreadId = threadId;
}
// Call displayThreads after the database is opened successfully
db.open()
.then(() => {
console.log("Database opened successfully");
console.log(
"Available tables:",
db.tables.map((table) => table.name)
);
// Load model settings from the database
console.log("Loading model settings");
loadModelSettings()
.then(() => {
console.log("Model settings loaded successfully");
// Retrieve the last used thread ID from the misc table
db.misc
.get("lastUsedThreadId")
.then((lastUsedThreadId) => {
console.log("Retrieving last used thread ID");
if (lastUsedThreadId) {
setCurrentThreadId(lastUsedThreadId.value); // Set the current thread ID
console.log("Last used thread ID retrieved:", currentThreadId);
} else {
console.log("No last used thread ID found");
}
displayMessages(currentThreadId);
// Remove the displayCharacters() call from here
displayThreads();
})
.catch((error) => {
console.error("Error retrieving last used thread ID:", error);
});
})
.catch((error) => {
console.error("Error loading model settings:", error);
});
})
.catch((e) => {
console.error("Failed to open database: " + e.message);
})
.finally(() => {
showLandingPage(); // Call showLandingPage here
});
function showUserSettings() {
document.getElementById("landingPage").style.display = "none";
document.getElementById("currentChat").style.display = "none";
showSettingsModal(); // Show the settings modal instead of the user settings div
// Load and display the user avatar
db.settings
.get(1)
.then((settings) => {
if (settings && settings.avatar) {
updateAvatarDisplay(settings.avatar);
} else {
updateAvatarDisplay("default-character-avatar.png"); // Fall back to the default avatar
}
})
.catch((error) => {
console.error("Error retrieving user settings:", error);
updateAvatarDisplay("default-character-avatar.png"); // Fall back to the default avatar
});
}
// Function to display threads
function displayThreads() {
const threadList = document.getElementById("threadList");
console.log("Thread List element:", threadList);
if (threadList) {
threadList.innerHTML = "";
db.threads
.toArray()
.then((threads) => {
console.log("Threads array:", threads);
threads.forEach((thread) => {
const threadElement = document.createElement("div");
threadElement.classList.add("thread");
if (thread.id === currentThreadId) {
threadElement.classList.add("active");
}
db.characters
.get(thread.characterId)
.then((character) => {
const characterName = character ? character.name : "Unknown Character";
const characterAvatar = character ? character.avatar : "default-character-avatar.png";
const avatarElement = document.createElement("img");
avatarElement.classList.add("thread-avatar");
avatarElement.src = characterAvatar;
avatarElement.alt = `${characterName} avatar`;
threadElement.appendChild(avatarElement);
const threadInfoElement = document.createElement("div");
threadInfoElement.classList.add("thread-info");
const characterNameElement = document.createElement("div");
characterNameElement.classList.add("character-name");
characterNameElement.textContent = characterName;
const threadActionsElement = document.createElement("div");
threadActionsElement.classList.add("thread-actions");
const editCharacterButton = document.createElement("button");
editCharacterButton.classList.add("edit-character-btn");
editCharacterButton.textContent = "Edit";
editCharacterButton.addEventListener("click", (event) => {
event.stopPropagation(); // Prevent the thread click event from triggering
showEditCharacterModal(thread.characterId);
});
threadActionsElement.appendChild(editCharacterButton);
characterNameElement.appendChild(threadActionsElement);
threadInfoElement.appendChild(characterNameElement);
const threadIdElement = document.createElement("div");
threadIdElement.classList.add("thread-id");
threadIdElement.textContent = `Thread #${thread.id}`;
const deleteThreadButton = document.createElement("button");
deleteThreadButton.classList.add("delete-thread-btn");
deleteThreadButton.textContent = "Delete";
deleteThreadButton.addEventListener("click", (event) => {
event.stopPropagation(); // Prevent the thread click event from triggering
deleteThread(thread.id);
});
threadIdElement.appendChild(deleteThreadButton);
threadInfoElement.appendChild(threadIdElement);
threadElement.appendChild(threadInfoElement);
threadElement.onclick = () => {
currentThreadId = thread.id;
db.misc
.put({ key: "lastUsedThreadId", value: thread.id })
.then(() => {
console.log("Last used thread ID saved:", thread.id);
setCurrentThreadId(currentThreadId);
showCurrentChat();
displayThreads();
})
.catch((error) => {
console.error("Error saving last used thread ID:", error);
});
};
threadList.appendChild(threadElement);
})
.catch((error) => {
console.error("Error retrieving character:", error);
});
});
})
.catch((error) => {
console.error("Error retrieving threads:", error);
});
} else {
console.error("Thread List element not found.");
}
}
function showSettingsModal() {
settingsModal.style.display = "block";
// Add event listener to the close button
const closeButton = settingsModal.querySelector('.close');
closeButton.addEventListener('click', hideSettingsModal);
// Load and display the user avatar
db.settings
.get(1)
.then((settings) => {
if (settings && settings.avatar) {
updateAvatarDisplay(settings.avatar);
} else {
updateAvatarDisplay("default-character-avatar.png"); // Fall back to the default avatar
}
})
.catch((error) => {
console.error("Error retrieving user settings:", error);
updateAvatarDisplay("default-character-avatar.png"); // Fall back to the default avatar
});
}
// Function to hide the settings modal
function hideSettingsModal() {
settingsModal.style.display = "none";
}
// Event listener for the settings button
settingsBtn.addEventListener("click", showSettingsModal);
// Event listener for the API key form submission
document.addEventListener("DOMContentLoaded", function () {
apiKeyForm.addEventListener("submit", saveApiKeys);
});
document.addEventListener('DOMContentLoaded', () => {
const urlParams = new URLSearchParams(window.location.search);
const characterData = urlParams.get('character');
if (characterData) {
try {
const parsedCharacterData = JSON.parse(decodeURIComponent(characterData));
importCharacter(parsedCharacterData);
} catch (error) {
console.error('Error parsing character data:', error);
}
}
});
let conversationHistory = [];
console.log("Script loaded and initializing event listeners");
function saveApiKeys(event) {
event.preventDefault();
const claudeKey = document.getElementById("claudeKey").value;
const gptKey = document.getElementById("gptKey").value;
const cohereKey = document.getElementById("cohereKey").value;
const userName = document.getElementById("userName").value;
console.log(
"Values retrieved - Claude Key:",
claudeKey,
"GPT Key:",
gptKey,
"User Name:",
userName
); // Log the values
// Handle avatar upload
const fileInput = document.getElementById("avatarInput");
const file = fileInput.files[0];
let avatarData = null;
if (file) {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
avatarData = reader.result;
saveSettings(claudeKey, gptKey, userName, avatarData);
};
reader.onerror = function (error) {
console.error("Error reading file:", error);
saveSettings(claudeKey, gptKey, userName, null);
};
} else {
saveSettings(claudeKey, gptKey, cohereKey, userName, null);
}
}
function saveSettings(claudeKey, gptKey, cohereKey, userName, avatarData) {
const id = 1;
const settings = { id, claudeKey, gptKey, cohereKey, userName };
if (avatarData) {
settings.avatar = avatarData;
}
db.settings
.put(settings)
.then(() => {
console.log("Settings saved successfully");
hideSettingsModal();
updateAvatarDisplay(avatarData || "default-avatar.png");
})
.catch((error) => {
console.error("Error saving settings:", error);
});
}
function appendMessage(content, type, senderName, senderAvatar) {
const messageElement = document.createElement("div");
messageElement.classList.add(type === "user" ? "user-message" : "ai-message");
const avatarElement = document.createElement("img");
avatarElement.classList.add("message-avatar");
avatarElement.src = senderAvatar;
avatarElement.alt = type === "user" ? "user avatar" : "character avatar";
messageElement.appendChild(avatarElement);
const messageContentWrapper = document.createElement("div");
messageContentWrapper.classList.add("message-content-wrapper");
const messageHeader = document.createElement("div");
messageHeader.classList.add("message-header");
const senderNameElement = document.createElement("strong");
senderNameElement.textContent = senderName;
messageHeader.appendChild(senderNameElement);
const actionButtons = document.createElement("div");
actionButtons.classList.add("message-action-buttons");
const editButton = document.createElement("button");
editButton.classList.add("edit-message-btn");
editButton.textContent = "Edit";
actionButtons.appendChild(editButton);
const deleteButton = document.createElement("button");
deleteButton.classList.add("delete-message-btn");
deleteButton.textContent = "Delete";
actionButtons.appendChild(deleteButton);
if (type === "ai") {
const rerollButton = document.createElement("button");
rerollButton.classList.add("reroll-message-btn");
rerollButton.textContent = "Reroll";
actionButtons.appendChild(rerollButton);
}
messageHeader.appendChild(actionButtons);
const messageContent = document.createElement("div");
messageContent.classList.add("message-content");
messageContent.innerHTML = renderMarkdown(content);
messageContentWrapper.appendChild(messageHeader);
messageContentWrapper.appendChild(messageContent);
messageElement.appendChild(messageContentWrapper);
chatMessages.appendChild(messageElement);
chatMessages.scrollTop = chatMessages.scrollHeight;
}
// Function to send a message
function sendMessage() {
const content = messageInput.value.trim();
const selectedModel = modelSelect.value;
const threadId = getCurrentThreadId(); // Get the current thread ID
if (content !== "") {
const timestamp = new Date().toISOString();
db.settings
.get(1)
.then((settings) => {
const userAvatar = settings?.avatar || "default-avatar.png";
db.messages
.add({ content, timestamp, model: selectedModel, threadId, type: "user" })
.then(() => {
console.log("Message sent successfully");
messageInput.value = "";
appendMessage(content, "user", "User", userAvatar);
sendMessageToAPI(selectedModel, content);
})
.catch((error) => {
console.error("Error sending message:", error);
});
})
.catch((error) => {
console.error("Error retrieving user settings:", error);
});
}
}
// Event listener for the send button
sendBtn.addEventListener("click", sendMessage);
// Function to automatically adjust the height of the textarea
function adjustTextareaHeight() {
const textarea = document.querySelector("#messageInput");
textarea.style.height = "auto";
textarea.style.height = `${textarea.scrollHeight}px`;
}
// Utility function to calculate word count
function getWordCount(text) {
return text.trim().split(/\s+/).length;
}
// Function to trim conversation history based on context limit
function trimConversationHistory(conversationHistory, contextLimit) {
let totalWords = 0;
let trimmedHistory = [];
for (let i = conversationHistory.length - 1; i >= 0; i--) {
const message = conversationHistory[i];
const wordCount = getWordCount(message.content);
if (totalWords + wordCount > contextLimit) {
break;
}
trimmedHistory.unshift(message);
totalWords += wordCount;
}
return trimmedHistory;
}
// Function to send a message to the API. Updated to accept optional threadId and isReroll flag.
function sendMessageToAPI(model, content, threadId = getCurrentThreadId(), isReroll = false) {
db.settings
.get(1)
.then(function (settings) {
const apiKey = settings[model + "Key"];
console.log("Using " + model.toUpperCase() + " API Key:", apiKey);
if (!apiKey) {
console.error("API key not found for model:", model);
showErrorModal("API key not found. Please make sure you have entered a valid API key for the selected model in the settings.");
return;
}
db.threads
.get(threadId)
.then(function (thread) {
if (thread && thread.characterId) {
// Retrieve the conversation history from the thread, or initialize it as an empty array
const conversationHistory = thread.conversationHistory || [];
db.characters
.get(thread.characterId)
.then(function (character) {
if (character) {
const characterId = character.id;
const characterInstruction = character.instruction;
const characterReminder = character.reminder;
const characterInitialMessage = character.initialMessage;
const characterName = character.name;
const characterAvatar = character.avatar || "default-character-avatar.png";
Promise.all([
replacePlaceholders(characterInstruction, characterId),
replacePlaceholders(characterReminder, characterId),
replacePlaceholders(characterInitialMessage, characterId),
])
.then(function ([instruction, reminder, initialMessage]) {
// Seed conversation history with the initial message if it's empty.
if (conversationHistory.length === 0) {
conversationHistory.push({
role: "assistant",
content: initialMessage,
});
}
if (isReroll) {
// On a reroll, remove only the last assistant message.
if (
conversationHistory.length > 0 &&
conversationHistory[conversationHistory.length - 1].role === "assistant"
) {
conversationHistory.pop();
}
// Do not add a new user message; use the existing one.
} else {
// Normal flow: add the new user message.
conversationHistory.push({
role: "user",
content: instruction + "\n\n" + content + "\n\n" + reminder,
});
}
console.log("Conversation history:", conversationHistory);
const selectedModel = models[model];
if (selectedModel) {
const endpoint = selectedModel.endpoint;
const apiKeyField = selectedModel.apiKeyField;
// Retrieve the context limit based on the model
const contextLimit = selectedModel.contextLimits[selectedModel.requestBody.model];
// Trim the conversation history to fit within the context limit
const trimmedHistory = trimConversationHistory(conversationHistory, contextLimit);
const conversationHistoryFormatted = selectedModel.formatConversationHistory(trimmedHistory, character.name);
// Create a copy of the requestBody using transformRequestBody if available
let requestBody;
if (model === "gpt" && typeof selectedModel.transformRequestBody === "function") {
requestBody = selectedModel.transformRequestBody();
} else {
requestBody = JSON.parse(JSON.stringify(selectedModel.requestBody));
}
// Set the messageField in the requestBody based on the model
if (model === "claude") {
requestBody["prompt"] = conversationHistoryFormatted;
} else if (model === "gpt") {
requestBody["messages"] = conversationHistoryFormatted;
} else if (model === "cohere") {
requestBody["message"] = conversationHistoryFormatted.message;
requestBody["chat_history"] = conversationHistoryFormatted.chat_history;
requestBody["connectors"] = conversationHistoryFormatted.connectors;
}
console.log("Request Details for " + model.toUpperCase() + ":");
console.log("Endpoint:", endpoint);
console.log("API Key Field:", apiKeyField);
console.log("API Key:", selectedModel.apiKeyPrefix + apiKey);
console.log("Request Body:", requestBody);
const timeout = setTimeout(function () {
console.error("API request timed out after 60 seconds.");
showErrorModal("We had an error retrieving your message. Please check your API key and funding. If this issue persists, send this error report to Eli on Discord.");
}, 60000);
console.log("Complete Request Details for " + model.toUpperCase() + ":", {
endpoint: endpoint,
apiKey: selectedModel.apiKeyPrefix + apiKey,
requestBody: requestBody,
});
fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
[apiKeyField]: selectedModel.apiKeyPrefix + apiKey,
},
body: JSON.stringify(requestBody),
})
.then(function (response) {
clearTimeout(timeout);
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json();
})
.then(function (data) {
console.log(model.toUpperCase() + " API response:", data);
if (data.type === "error") {
console.error("Error response from " + model.toUpperCase() + " API:", data);
showErrorModal("We had an error retrieving your message. Please check your API key and funding. If this issue persists, send this error report to Eli on Discord.");
} else {
const responseContent = model === "cohere" ? data.text : selectedModel.extractResponseContent(data);
if (responseContent) {
const timestamp = new Date().toISOString();
conversationHistory.push({
role: "assistant",
content: responseContent,
});
console.log("Updated conversation history:", conversationHistory);
db.threads
.update(threadId, { conversationHistory: conversationHistory })
.then(function () {
db.messages
.add({
content: responseContent,
timestamp: timestamp,
model: model,
threadId: threadId,
type: "ai",
})
.then(function () {
appendMessage(responseContent, "ai", characterName, characterAvatar);
});
});
}
}
})
.catch(function (error) {
console.error("Error sending message to " + model.toUpperCase() + " API:", error);
showErrorModal("We had an error retrieving your message. Please check your API key and funding. If this issue persists, send this error report to Eli on Discord.");
});
} else {
console.error("Unsupported model:", model);
}
})
.catch(function (error) {
console.error("Error replacing placeholders:", error);
});
} else {
console.error("Character not found for the current thread ID:", threadId);
}
})
.catch(function (error) {
console.error("Failed to retrieve character:", error);
});
} else {
console.error("Thread not found or character ID not set for thread ID:", threadId);
}
})
.catch(function (error) {
console.error("Failed to retrieve thread:", error);
});
})
.catch(function (error) {
console.error("Failed to retrieve API keys:", error);
if (error.message.includes("Cannot read properties of undefined")) {
showErrorModal("API key not found. Please make sure you have entered a valid API key for the selected model in the settings.");
}
});
// Note: Removed any call to smoothScrollToBottom as per previous comments.
}
document.addEventListener('DOMContentLoaded', () => {
// Close button functionality for error modal
const errorModalCloseBtn = document.querySelector('#errorModal .close');
if (errorModalCloseBtn) {
errorModalCloseBtn.addEventListener('click', hideErrorModal);
}
});
// Capture the latest console error
let latestConsoleError = '';
(function() {
const originalError = console.error;
console.error = function(...args) {
latestConsoleError = args.map(arg => {
if (arg instanceof Error) {
return arg.message + "\n" + arg.stack;
} else if (typeof arg === 'object') {
// If it's an object (like the one returned from the GPT API), try to include its details.
try {
return JSON.stringify(arg, null, 2);
} catch (e) {
return arg.toString();
}
}
return arg;
}).join(' ');
originalError.apply(console, args);
};
})();
// Function to show the error modal with error message and latest console error
function showErrorModal(errorMessage) {
const errorModal = document.getElementById("errorModal");
const errorMessageElement = document.getElementById("errorMessage");
const errorLogsElement = document.getElementById("errorLogs");
// Display the error message
errorMessageElement.textContent = errorMessage;
// Display the latest console error
errorLogsElement.textContent = latestConsoleError;
errorModal.style.display = "block";
}
// Function to hide the error modal
function hideErrorModal() {
const errorModal = document.getElementById("errorModal");
errorModal.style.display = "none";
}
// Function to copy error logs to clipboard
function copyErrorLogs() {
const errorMessageElement = document.getElementById("errorMessage").textContent;
const errorLogsElement = document.getElementById("errorLogs").textContent;
const combinedMessage = `${errorMessageElement}\n\nConsole Logs:\n${errorLogsElement}`;
const tempTextArea = document.createElement("textarea");
tempTextArea.value = combinedMessage;
document.body.appendChild(tempTextArea);
tempTextArea.select();
document.execCommand("copy");
document.body.removeChild(tempTextArea);
alert("Error details copied to clipboard!");
}
// Attach the function to the window object to make it globally accessible
window.hideErrorModal = hideErrorModal;
window.copyErrorLogs = copyErrorLogs;
// Attach the function to the window object to make it globally accessible
window.hideErrorModal = hideErrorModal;
// Function to show the model settings modal
function showModelSettings() {
const selectedModel = modelSelect.value;
const settings = modelSettings[selectedModel];
// Populate the preset dropdown
const presetSelect = document.getElementById('presetSelect');
presetSelect.innerHTML = '<option value="">Select a preset</option>';
db.presets
.where('modelName')
.equals(selectedModel)
.each((preset) => {
const option = document.createElement('option');
option.value = preset.id;
option.textContent = preset.name;
presetSelect.appendChild(option);
})
.catch((error) => {
console.error('Error retrieving presets:', error);
});
// Clear the form
modelSettingsForm.innerHTML = "";
// Generate input fields based on the model settings
settings.fields.forEach((field) => {
const label = document.createElement('label');
label.textContent = field.name;
let input;
if (field.type === 'select') {
input = document.createElement('select');
field.options.forEach((option) => {
const optionElement = document.createElement('option');
optionElement.value = option;
optionElement.textContent = option;
input.appendChild(optionElement);
});
} else {
input = document.createElement('input');
input.type = field.type;
input.step = field.step;
input.min = field.min;
input.max = field.max;
}
input.name = field.name;
const value = models[selectedModel].requestBody[field.name];
input.value = value !== null ? value : field.default; // Use default value if value is null
input.readOnly = field.readonly;
modelSettingsForm.appendChild(label);
modelSettingsForm.appendChild(input);
});
// Add the save button
const saveButton = document.createElement("button");
saveButton.type = "submit";
saveButton.className = "btn";
saveButton.textContent = "Save";
modelSettingsForm.appendChild(saveButton);
// Add event listener to the close button
const closeButton = modelSettingsModal.querySelector('.close');
closeButton.addEventListener('click', hideModelSettings);
// Show the modal
modelSettingsModal.style.display = "block";
}
// Function to hide the model settings modal
function hideModelSettings() {
modelSettingsModal.style.display = 'none';
}
const presetSelect = document.getElementById('presetSelect');
presetSelect.addEventListener('change', (event) => {
const presetId = event.target.value;
if (presetId) {
db.presets
.get(Number(presetId))
.then((preset) => {
if (preset) {
// Load the preset settings into the form
Object.entries(preset.settings).forEach(([key, value]) => {
const input = modelSettingsForm.elements[key];
if (input) {
input.value = value;
}
});
}
})
.catch((error) => {
console.error('Error loading preset:', error);
});
}
});
const savePresetBtn = document.getElementById('savePresetBtn');
savePresetBtn.addEventListener('click', () => {
const presetName = prompt('Enter a name for the preset:');
if (presetName) {
const selectedModel = modelSelect.value;
const formData = new FormData(modelSettingsForm);
const settings = Object.fromEntries(formData.entries());
db.presets
.add({
name: presetName,
modelName: selectedModel,
settings: settings,
})
.then(() => {
console.log('Preset saved successfully');
showModelSettings(); // Refresh the preset dropdown
})
.catch((error) => {
console.error('Error saving preset:', error);
});
}
});
// Event listener for the model settings form submission
modelSettingsForm.addEventListener('submit', (event) => {
event.preventDefault();
const formData = new FormData(modelSettingsForm);
const settings = Object.fromEntries(formData.entries());
console.log('Model settings:', settings);
// Update the models object with the new settings
const selectedModel = modelSelect.value;
updateModelSettings(selectedModel, settings);
hideModelSettings();
});
// Event listener for the model settings button
modelSettingsBtn.addEventListener('click', showModelSettings);
async function loadModelSettings() {
console.log("Starting to load model settings from the database...");
for (const modelName of Object.keys(models)) {
console.log(`Checking database for settings of ${modelName}`);
try {
const savedSettings = await db.modelSettings.get({ name: modelName });
console.log(`Retrieved settings for ${modelName} from the database:`, savedSettings);
if (savedSettings && savedSettings.settings) {
console.log(`Applying saved settings for ${modelName}`);
models[modelName].requestBody = { ...applyDefaultSettings(modelName), ...savedSettings.settings };
console.log(`Settings for ${modelName} after merging:`, models[modelName].requestBody);
} else {
console.log(`No saved settings found for ${modelName}, applying default settings`);
models[modelName].requestBody = applyDefaultSettings(modelName);
}
} catch (error) {
console.error(`Error loading settings for ${modelName}:`, error);
}
}
}
function applyDefaultSettings(modelName) {
const modelConfig = modelSettings[modelName];
const defaults = modelConfig.fields.reduce((acc, field) => {
acc[field.name] = field.default;
return acc;
}, {});
console.log(`Default settings for ${modelName}:`, defaults);
return defaults;
}