-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2315 lines (1993 loc) · 91.8 KB
/
script.js
File metadata and controls
2315 lines (1993 loc) · 91.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
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
class ChatApp {
constructor() {
this.conversations = [];
this.currentConversationId = null;
this.messageId = 0;
this.settings = {
provider: 'ollama',
ollamaUrl: 'http://localhost:11434',
openrouterKey: '',
openrouterUrl: 'https://openrouter.ai/api/v1',
customUrl: '',
customKey: '',
customModel: '',
model: ''
};
this.providerModels = {
ollama: [],
openrouter: [],
custom: []
};
this.modelsLoading = false;
this.hasConnectionError = false;
this.uploadedImages = [];
this.conversationToDelete = null;
this.chatItemToDelete = null;
this.streamingMessageId = null; // Track which message is currently streaming
this.initializeElements();
this.setupEventListeners();
this.loadSettings();
this.loadConversations();
this.adjustTextareaHeight();
this.updateProviderFieldsVisibility(); // Initialize provider visibility
this.initializeMarkdown(); // Initialize markdown parser
// Load models after settings are loaded to ensure correct provider is used
// Use setTimeout to ensure DOM is fully ready
setTimeout(() => {
console.log(`Loading models for provider: ${this.settings.provider}`);
this.loadModelsForCurrentProvider();
}, 100);
}
initializeElements() {
this.sidebar = document.getElementById('sidebar');
this.sidebarToggle = document.getElementById('sidebarToggle');
this.sidebarBackdrop = document.getElementById('sidebarBackdrop');
this.mainContent = document.querySelector('.main-content');
this.newChatBtn = document.getElementById('newChatBtn');
this.chatHistory = document.getElementById('chatHistory');
this.chatMessages = document.getElementById('chatMessages');
this.messageInput = document.getElementById('messageInput');
this.sendBtn = document.getElementById('sendBtn');
this.modelSelect = document.getElementById('modelSelect');
this.providerSelect = document.getElementById('providerSelect');
this.refreshModelsBtn = document.getElementById('refreshModelsBtn');
this.settingsBtn = document.getElementById('settingsBtn');
this.settingsModal = document.getElementById('settingsModal');
this.closeSettings = document.getElementById('closeSettings');
this.saveSettingsBtn = document.getElementById('saveSettings');
this.cancelSettings = document.getElementById('cancelSettings');
this.testConnection = document.getElementById('testConnection');
this.connectionStatus = document.getElementById('connectionStatus');
this.chatContainer = document.getElementById('chatContainer');
this.uploadBtn = document.getElementById('uploadBtn');
this.imageUpload = document.getElementById('imageUpload');
this.uploadedImagesContainer = document.getElementById('uploadedImages');
this.deleteModal = document.getElementById('deleteModal');
this.confirmDelete = document.getElementById('confirmDelete');
this.cancelDelete = document.getElementById('cancelDelete');
// Settings inputs
this.ollamaUrl = document.getElementById('ollamaUrl');
this.openrouterKey = document.getElementById('openrouterKey');
this.openrouterUrl = document.getElementById('openrouterUrl');
this.customUrl = document.getElementById('customUrl');
this.customKey = document.getElementById('customKey');
this.customModel = document.getElementById('customModel');
// Reset buttons
this.resetOllamaUrl = document.getElementById('resetOllamaUrl');
this.resetOpenrouterUrl = document.getElementById('resetOpenrouterUrl');
this.resetCustomUrl = document.getElementById('resetCustomUrl');
// Debug: Check if critical elements exist
console.log('Critical elements check:');
console.log('messageInput:', this.messageInput ? 'found' : 'NOT FOUND');
console.log('sendBtn:', this.sendBtn ? 'found' : 'NOT FOUND');
console.log('chatMessages:', this.chatMessages ? 'found' : 'NOT FOUND');
console.log('modelSelect:', this.modelSelect ? 'found' : 'NOT FOUND');
}
initializeMarkdown() {
// Configure marked.js for better formatting
if (typeof marked !== 'undefined') {
marked.setOptions({
breaks: true,
gfm: true,
highlight: function(code, lang) {
if (typeof hljs !== 'undefined' && lang && hljs.getLanguage(lang)) {
try {
return hljs.highlight(code, { language: lang }).value;
} catch (err) {
console.warn('Highlight.js error:', err);
}
}
return code;
}
});
}
}
setupEventListeners() {
// Sidebar toggle
this.sidebarToggle.addEventListener('click', () => {
this.toggleSidebar();
});
// Sidebar backdrop click (mobile)
this.sidebarBackdrop.addEventListener('click', () => {
this.closeSidebar();
});
// New chat button
this.newChatBtn.addEventListener('click', () => {
this.createNewConversation();
});
// Message input
this.messageInput.addEventListener('input', () => {
this.adjustTextareaHeight();
this.updateSendButton();
});
this.messageInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
this.sendMessage();
}
});
// Send button
this.sendBtn.addEventListener('click', () => {
console.log('Send button clicked!'); // Debug log
this.sendMessage();
});
// Provider selection
this.providerSelect.addEventListener('change', () => {
this.settings.provider = this.providerSelect.value;
this.updateProviderFieldsVisibility();
this.loadModelsForCurrentProvider();
this.saveSettings();
});
// Model selection
this.modelSelect.addEventListener('change', () => {
this.settings.model = this.modelSelect.value;
this.saveSettings();
});
// Refresh models button
this.refreshModelsBtn.addEventListener('click', () => {
this.refreshModels();
});
// Settings modal
this.settingsBtn.addEventListener('click', () => {
this.openSettingsModal();
});
this.closeSettings.addEventListener('click', () => {
this.closeSettingsModal();
});
this.cancelSettings.addEventListener('click', () => {
this.closeSettingsModal();
});
this.saveSettingsBtn.addEventListener('click', () => {
this.saveSettingsFromModal();
});
this.testConnection.addEventListener('click', () => {
this.testProviderConnection();
});
// Close modal on overlay click
this.settingsModal.addEventListener('click', (e) => {
if (e.target === this.settingsModal) {
this.closeSettingsModal();
}
});
// Example prompts
document.addEventListener('click', (e) => {
if (e.target.closest('.prompt-card')) {
const prompt = e.target.closest('.prompt-card').dataset.prompt;
this.messageInput.value = prompt;
this.updateSendButton();
this.adjustTextareaHeight();
this.messageInput.focus();
}
});
// Chat history clicks
this.chatHistory.addEventListener('click', (e) => {
// Ignore clicks on delete buttons
if (e.target.closest('.delete-chat-btn')) {
return;
}
if (e.target.closest('.chat-item')) {
const conversationId = e.target.closest('.chat-item').dataset.id;
this.loadConversation(conversationId);
}
});
// Auto-resize textarea
this.messageInput.addEventListener('input', () => {
this.adjustTextareaHeight();
});
// Image upload
this.uploadBtn.addEventListener('click', () => {
this.imageUpload.click();
});
this.imageUpload.addEventListener('change', (e) => {
this.handleImageUpload(e);
});
// Delete modal
this.cancelDelete.addEventListener('click', () => {
this.hideDeleteModal();
});
this.confirmDelete.addEventListener('click', () => {
this.confirmChatDeletion();
});
// Close delete modal on overlay click
this.deleteModal.addEventListener('click', (e) => {
if (e.target === this.deleteModal) {
this.hideDeleteModal();
}
});
// Window resize listener for responsive sidebar behavior
window.addEventListener('resize', () => {
this.handleResize();
});
// Reset button event listeners
this.resetOllamaUrl.addEventListener('click', () => {
this.resetUrlToDefault('ollama');
});
this.resetOpenrouterUrl.addEventListener('click', () => {
this.resetUrlToDefault('openrouter');
});
this.resetCustomUrl.addEventListener('click', () => {
this.resetUrlToDefault('custom');
});
// URL input change listeners to save settings in real-time
this.ollamaUrl.addEventListener('blur', () => {
const rawValue = this.ollamaUrl.value.trim() || 'http://localhost:11434';
const newValue = this.sanitizeUrl(rawValue);
if (this.settings.ollamaUrl !== newValue) {
console.log('Ollama URL changed from', this.settings.ollamaUrl, 'to', newValue);
this.settings.ollamaUrl = newValue;
this.ollamaUrl.value = newValue; // Update input field with sanitized value
this.saveSettings();
}
});
this.openrouterUrl.addEventListener('blur', () => {
const rawValue = this.openrouterUrl.value.trim() || 'https://openrouter.ai/api/v1';
const newValue = this.sanitizeUrl(rawValue);
if (this.settings.openrouterUrl !== newValue) {
console.log('OpenRouter URL changed from', this.settings.openrouterUrl, 'to', newValue);
this.settings.openrouterUrl = newValue;
this.openrouterUrl.value = newValue; // Update input field with sanitized value
this.saveSettings();
}
});
this.customUrl.addEventListener('blur', () => {
const rawValue = this.customUrl.value.trim();
const newValue = this.sanitizeUrl(rawValue);
if (this.settings.customUrl !== newValue) {
console.log('Custom URL changed from', this.settings.customUrl, 'to', newValue);
this.settings.customUrl = newValue;
this.customUrl.value = newValue; // Update input field with sanitized value
this.saveSettings();
}
});
}
// Utility method to sanitize URLs by removing trailing slashes
sanitizeUrl(url) {
if (!url) return url;
// Remove trailing slash(es) but keep the protocol part intact
return url.replace(/\/+$/, '');
}
adjustTextareaHeight() {
this.messageInput.style.height = 'auto';
this.messageInput.style.height = Math.min(this.messageInput.scrollHeight, 200) + 'px';
}
updateSendButton() {
const hasText = this.messageInput.value.trim().length > 0;
const hasImages = this.uploadedImages.length > 0;
this.sendBtn.disabled = !hasText && !hasImages;
}
updateSettingsButtonState() {
if (this.hasConnectionError) {
this.settingsBtn.classList.add('connection-error');
} else {
this.settingsBtn.classList.remove('connection-error');
}
}
resetUrlToDefault(provider) {
const defaults = {
ollama: 'http://localhost:11434',
openrouter: 'https://openrouter.ai/api/v1',
custom: '' // Custom URLs reset to empty
};
const urlFields = {
ollama: this.ollamaUrl,
openrouter: this.openrouterUrl,
custom: this.customUrl
};
const settingsKeys = {
ollama: 'ollamaUrl',
openrouter: 'openrouterUrl',
custom: 'customUrl'
};
if (urlFields[provider] && defaults.hasOwnProperty(provider)) {
urlFields[provider].value = defaults[provider];
this.settings[settingsKeys[provider]] = defaults[provider];
// Save settings immediately
this.saveSettings();
// Show visual feedback
const button = provider === 'ollama' ? this.resetOllamaUrl :
provider === 'openrouter' ? this.resetOpenrouterUrl :
this.resetCustomUrl;
const originalIcon = button.innerHTML;
button.innerHTML = '<i class="fas fa-check"></i>';
button.style.color = '#10a37f';
setTimeout(() => {
button.innerHTML = originalIcon;
button.style.color = '';
}, 1000);
}
}
async handleImageUpload(event) {
const files = Array.from(event.target.files);
for (const file of files) {
if (file.type.startsWith('image/')) {
const imageData = await this.processImage(file);
if (imageData) {
this.uploadedImages.push(imageData);
}
}
}
this.displayUploadedImages();
this.updateSendButton();
// Clear the file input
event.target.value = '';
}
async processImage(file) {
return new Promise((resolve) => {
const reader = new FileReader();
reader.onload = (e) => {
const img = new Image();
img.onload = () => {
// Create canvas to resize image if needed
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// Max dimensions for uploaded images
const maxWidth = 1024;
const maxHeight = 1024;
let { width, height } = img;
// Calculate new dimensions if image is too large
if (width > maxWidth || height > maxHeight) {
const ratio = Math.min(maxWidth / width, maxHeight / height);
width *= ratio;
height *= ratio;
}
canvas.width = width;
canvas.height = height;
// Draw and compress
ctx.drawImage(img, 0, 0, width, height);
const base64 = canvas.toDataURL('image/jpeg', 0.8);
resolve({
id: Date.now() + Math.random(),
name: file.name,
type: file.type,
base64: base64,
size: file.size
});
};
img.src = e.target.result;
};
reader.readAsDataURL(file);
});
}
displayUploadedImages() {
if (this.uploadedImages.length === 0) {
this.uploadedImagesContainer.style.display = 'none';
return;
}
this.uploadedImagesContainer.style.display = 'flex';
this.uploadedImagesContainer.innerHTML = '';
this.uploadedImages.forEach(image => {
const imageDiv = document.createElement('div');
imageDiv.className = 'uploaded-image';
imageDiv.innerHTML = `
<img src="${image.base64}" alt="${image.name}" title="${image.name}">
<button class="remove-image" onclick="chatApp.removeUploadedImage('${image.id}')">
<i class="fas fa-times"></i>
</button>
`;
this.uploadedImagesContainer.appendChild(imageDiv);
});
}
removeUploadedImage(imageId) {
this.uploadedImages = this.uploadedImages.filter(img => img.id !== imageId);
this.displayUploadedImages();
this.updateSendButton();
}
createNewConversation() {
const conversation = {
id: Date.now().toString(),
title: 'New chat',
messages: [],
timestamp: new Date()
};
this.conversations.unshift(conversation);
this.currentConversationId = conversation.id;
this.saveConversations();
this.renderChatHistory();
this.renderMessages();
this.hideWelcomeSection();
// Add animation to the new chat item
setTimeout(() => {
const newChatItem = document.querySelector(`[data-id="${conversation.id}"]`);
if (newChatItem) {
newChatItem.classList.add('new-chat');
// Remove the animation class after animation completes
setTimeout(() => {
newChatItem.classList.remove('new-chat');
}, 300);
}
}, 10);
}
async sendMessage() {
console.log('sendMessage called'); // Debug log
const text = this.messageInput.value.trim();
const hasImages = this.uploadedImages.length > 0;
console.log('Text:', text, 'HasImages:', hasImages); // Debug log
if (!text && !hasImages) {
console.log('No text or images, returning early'); // Debug log
return;
}
// Check if model is selected
if (!this.settings.model) {
console.log('No model selected'); // Debug log
alert('Please select a model first. You may need to refresh the models list or check your provider settings.');
return;
}
console.log('Model selected:', this.settings.model); // Debug log
// Ensure a conversation exists before proceeding
if (!this.currentConversationId) {
console.log('Creating new conversation'); // Debug log
this.createNewConversation();
}
// Always re-fetch after possible creation
let conversation = this.conversations.find(c => c.id === this.currentConversationId);
if (!conversation) {
// Try one more time in case the array hasn't updated yet
this.createNewConversation();
conversation = this.conversations.find(c => c.id === this.currentConversationId);
if (!conversation) {
alert('Failed to create or find a conversation. Please try again.');
return;
}
}
console.log('Conversation found:', conversation.id); // Debug log
// Add user message
const userMessage = {
id: this.messageId++,
role: 'user',
content: text,
images: hasImages ? [...this.uploadedImages] : null,
timestamp: new Date()
};
console.log('Adding user message:', userMessage); // Debug log
conversation.messages.push(userMessage);
// Update conversation title if it's the first message
if (conversation.messages.length === 1) {
conversation.title = this.generateTitle(text);
}
// Clear input and uploaded images
this.messageInput.value = '';
this.uploadedImages = [];
this.displayUploadedImages();
this.adjustTextareaHeight();
this.updateSendButton();
console.log('About to render messages'); // Debug log
// Render messages
this.renderMessages();
this.hideWelcomeSection();
console.log('About to show typing indicator'); // Debug log
// Show typing indicator
this.showTypingIndicator();
console.log('About to get AI response'); // Debug log
// Get AI response
try {
await this.getAIResponse(conversation);
} catch (error) {
console.error('Error getting AI response:', error);
this.hideTypingIndicator();
this.streamingMessageId = null; // Clear streaming state on error
// Remove the empty AI message that was added in getAIResponse
const lastMessage = conversation.messages[conversation.messages.length - 1];
if (lastMessage && lastMessage.role === 'assistant' && !lastMessage.content.trim()) {
conversation.messages.pop();
}
let errorMessage = error.message;
if (error.message.includes('Failed to fetch') || error.message.includes('NetworkError')) {
errorMessage = `Cannot connect to ${this.settings.provider}. Please check your connection and provider settings.`;
}
const errorResponse = {
id: this.messageId++,
role: 'assistant',
content: `❌ **Error**: ${errorMessage}\n\nPlease check:\n- Your provider settings\n- Internet connection\n- API key (if using OpenRouter)\n- That your chosen model is available`,
timestamp: new Date(),
metadata: {
provider: this.settings.provider,
model: this.settings.model,
startTime: Date.now(),
endTime: Date.now(),
responseTime: 0,
tokens: 0
}
};
conversation.messages.push(errorResponse);
this.renderMessages();
}
this.saveConversations();
this.renderChatHistory();
console.log('sendMessage completed'); // Debug log
}
simulateAIResponse(conversation) {
const responses = [
"I'm a demo AI assistant created for this ChatGPT-like interface. In a real implementation, this would connect to an actual AI API like OpenAI's GPT-4.",
"This is a demonstration response. The interface mimics ChatGPT's design, but responses are simulated. You would need to integrate with a real AI service for actual functionality.",
"Hello! I'm simulating an AI response for this demo. The UI captures the look and feel of ChatGPT, including the typing animation and message formatting.",
"This interface demonstrates a ChatGPT-like experience. In production, you'd connect this to a real language model API to provide actual AI responses.",
"I understand you're testing this ChatGPT-style interface. The design includes features like conversation history, responsive layout, and smooth animations - all working in a static frontend!"
];
const response = responses[Math.floor(Math.random() * responses.length)];
const aiMessage = {
id: this.messageId++,
role: 'assistant',
content: response,
timestamp: new Date()
};
conversation.messages.push(aiMessage);
this.hideTypingIndicator();
this.renderMessages();
this.saveConversations();
}
async getAIResponse(conversation) {
// Collect all images from the conversation for Ollama
let ollamaImages = [];
const messages = conversation.messages.map(msg => {
const message = {
role: msg.role,
content: msg.content || ''
};
// Add images if present (for vision-capable models)
if (msg.images && msg.images.length > 0) {
if (this.settings.provider === 'ollama') {
// For Ollama, collect images to be sent at request level
// Extract base64 data without the data URL prefix
msg.images.forEach(img => {
let base64Data = img.base64;
// Remove data URL prefix if present (data:image/jpeg;base64,)
if (base64Data.startsWith('data:')) {
base64Data = base64Data.split(',')[1];
}
ollamaImages.push(base64Data);
});
console.log(`Ollama: Collected ${msg.images.length} image(s) from message`);
} else if (this.settings.provider === 'openrouter' || this.settings.provider === 'custom') {
// For OpenRouter and Custom APIs that support vision (OpenAI format)
message.content = [
{
type: 'text',
text: msg.content || ''
},
...msg.images.map(img => ({
type: 'image_url',
image_url: {
url: img.base64
}
}))
];
}
}
return message;
});
// Create AI message placeholder with metadata
const responseStartTime = Date.now();
const aiMessage = {
id: this.messageId++,
role: 'assistant',
content: '',
timestamp: new Date(),
metadata: {
provider: this.settings.provider,
model: this.settings.model,
startTime: responseStartTime,
endTime: null,
responseTime: null,
tokens: 0
}
};
conversation.messages.push(aiMessage);
this.hideTypingIndicator();
this.streamingMessageId = aiMessage.id; // Mark this message as streaming
this.renderMessages(); // Show empty AI message
let response;
if (this.settings.provider === 'ollama') {
response = await this.callOllama(messages, ollamaImages);
await this.handleStreamingResponse(response, aiMessage, conversation, 'ollama');
} else if (this.settings.provider === 'openrouter') {
response = await this.callOpenRouter(messages);
await this.handleStreamingResponse(response, aiMessage, conversation, 'openrouter');
} else if (this.settings.provider === 'custom') {
response = await this.callCustomAPI(messages);
if (typeof response === 'string') {
// Non-streaming custom API
aiMessage.content = response;
// Finalize metadata for non-streaming response
const endTime = Date.now();
if (aiMessage.metadata) {
aiMessage.metadata.endTime = endTime;
aiMessage.metadata.responseTime = endTime - aiMessage.metadata.startTime;
aiMessage.metadata.tokens = this.estimateTokens(aiMessage.content);
}
this.streamingMessageId = null; // Clear streaming state
this.renderMessages();
} else {
// Streaming custom API
await this.handleStreamingResponse(response, aiMessage, conversation, 'custom');
}
} else {
throw new Error('Unknown provider');
}
this.saveConversations();
}
async handleStreamingResponse(response, aiMessage, conversation, provider) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
let lastUpdateTime = 0;
const UPDATE_THROTTLE = 50; // Throttle for streaming updates (50ms for responsiveness)
let pendingUpdate = false;
try {
let totalChunks = 0;
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
totalChunks++;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
// Keep the last incomplete line in buffer
buffer = lines.pop() || '';
for (const line of lines) {
if (line.trim() === '') continue;
try {
let content = '';
if (provider === 'ollama') {
// Ollama format: {"message": {"content": "text"}}
if (line.startsWith('data: ')) {
const jsonStr = line.slice(6);
if (jsonStr.trim() === '[DONE]') break;
const data = JSON.parse(jsonStr);
content = data.message?.content || '';
} else {
const data = JSON.parse(line);
content = data.message?.content || '';
// Check if response is done
if (data.done) break;
}
} else if (provider === 'openrouter' || provider === 'custom') {
// OpenAI format: data: {"choices": [{"delta": {"content": "text"}}]}
if (line.startsWith('data: ')) {
const jsonStr = line.slice(6);
if (jsonStr.trim() === '[DONE]') break;
const data = JSON.parse(jsonStr);
content = data.choices?.[0]?.delta?.content || '';
}
}
if (content) {
aiMessage.content += content;
// Use renderMessages for streaming to ensure content appears
const now = Date.now();
if (now - lastUpdateTime > UPDATE_THROTTLE && !pendingUpdate) {
pendingUpdate = true;
requestAnimationFrame(() => {
this.renderMessages();
this.smoothScrollToBottom();
lastUpdateTime = Date.now();
pendingUpdate = false;
});
}
}
} catch (e) {
// Skip malformed JSON lines
console.warn('Failed to parse streaming response line:', line, e);
}
}
}
// Final update to ensure all content is rendered
this.updateStreamingMessage(aiMessage);
this.smoothScrollToBottom();
// Finalize response metadata
const endTime = Date.now();
if (aiMessage.metadata) {
aiMessage.metadata.endTime = endTime;
aiMessage.metadata.responseTime = endTime - aiMessage.metadata.startTime;
aiMessage.metadata.tokens = this.estimateTokens(aiMessage.content);
}
// Clear streaming state and re-render with full markdown formatting
this.streamingMessageId = null;
this.renderMessages();
console.log('Metadata finalized:', aiMessage.metadata);
} catch (error) {
console.error('Error reading stream:', error);
throw error;
} finally {
reader.releaseLock();
}
// Ensure the message has content
if (!aiMessage.content.trim()) {
aiMessage.content = 'Error: No response received from the AI service.';
if (aiMessage.metadata) {
aiMessage.metadata.endTime = Date.now();
aiMessage.metadata.responseTime = aiMessage.metadata.endTime - aiMessage.metadata.startTime;
}
this.streamingMessageId = null; // Clear streaming state
this.renderMessages();
}
}
// Simple token estimation (approximate)
estimateTokens(text) {
if (!text) return 0;
// Rough estimation: 1 token ≈ 4 characters for English text
// This is a simplification but gives a reasonable estimate
return Math.ceil(text.length / 4);
}
async callOllama(messages, images = []) {
const requestBody = {
model: this.settings.model,
messages: messages,
stream: true
};
// Add images array if there are any images (for vision models like Llava3)
if (images && images.length > 0) {
requestBody.images = images;
console.log(`Ollama: Sending ${images.length} image(s) to vision model ${this.settings.model}`);
}
try {
console.log('Ollama: Making request to URL:', `${this.settings.ollamaUrl}/api/chat`);
const response = await fetch(`${this.settings.ollamaUrl}/api/chat`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody)
});
if (!response.ok) {
throw new Error(`Ollama API error: ${response.status} ${response.statusText}`);
}
return response;
} catch (error) {
// Check for Mixed Content error (HTTPS page trying to access HTTP)
const isHttpsPage = window.location.protocol === 'https:';
const isHttpOllama = this.settings.ollamaUrl.startsWith('http://');
if (isHttpsPage && isHttpOllama) {
throw new Error(`Mixed Content Error: Cannot access HTTP Ollama server from HTTPS page.
🔒 Security Issue: Your page is served over HTTPS but Ollama is on HTTP.
Solutions:
1. 📥 Download and run this app locally (recommended)
2. 🔧 Set up HTTPS for Ollama:
- Use a reverse proxy (nginx, Traefik, etc.)
- Or use Cloudflare Tunnel
3. 🌐 Use OpenRouter or Custom API instead
4. 🔓 Access via HTTP (not recommended): http://astrixity.github.io/LLMe/
Current Ollama URL: ${this.settings.ollamaUrl}
Page protocol: ${window.location.protocol}`);
}
if (error.message.includes('CORS') || error.name === 'TypeError') {
throw new Error(`CORS error: Cannot access Ollama from web browser.
To fix this issue:
1. Download and run this app locally (recommended)
2. Configure Ollama to allow web access:
- Set environment variable: OLLAMA_ORIGINS=https://astrixity.github.io
- Or restart with: ollama serve --origins https://astrixity.github.io
3. For local development: OLLAMA_ORIGINS=*
The web browser blocks cross-origin requests for security reasons.`);
}
throw error;
}
}
async callOpenRouter(messages) {
if (!this.settings.openrouterKey) {
throw new Error('OpenRouter API key is required');
}
console.log('OpenRouter: Making request to URL:', `${this.settings.openrouterUrl}/chat/completions`);
const response = await fetch(`${this.settings.openrouterUrl}/chat/completions`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.settings.openrouterKey}`,
'Content-Type': 'application/json',
'HTTP-Referer': window.location.origin,
'X-Title': 'LLMe Chat Interface'
},
body: JSON.stringify({
model: this.settings.model,
messages: messages,
temperature: 0.7,
max_tokens: 2000,
stream: true
})
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(`OpenRouter API error: ${response.status} - ${errorData.error?.message || response.statusText}`);
}
return response;
}
async callCustomAPI(messages) {
if (!this.settings.customUrl) {
throw new Error('Custom API URL is required');
}
if (!this.settings.customModel) {
throw new Error('Custom model name is required');
}
const headers = {
'Content-Type': 'application/json'
};
// Add API key if provided
if (this.settings.customKey) {
headers['Authorization'] = `Bearer ${this.settings.customKey}`;
}
console.log('Custom API: Making request to URL:', `${this.settings.customUrl}/chat/completions`);
const response = await fetch(`${this.settings.customUrl}/chat/completions`, {
method: 'POST',
headers: headers,
body: JSON.stringify({
model: this.settings.customModel,
messages: messages,
temperature: 0.7,
max_tokens: 2000,
stream: true
})
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(`Custom API error: ${response.status} - ${errorData.error?.message || response.statusText}`);
}
// Check if the API supports streaming by looking at content-type
const contentType = response.headers.get('content-type');
if (contentType && contentType.includes('application/json') && !contentType.includes('stream')) {
// Non-streaming response - fallback to regular parsing
const data = await response.json();
return data.choices[0].message.content;
}
return response;
}
async testProviderConnection() {
const testBtn = this.testConnection;
const status = this.connectionStatus;
testBtn.disabled = true;
testBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Testing...';
status.className = 'connection-status testing';
status.textContent = 'Testing connection...';
try {