-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
799 lines (675 loc) · 28.9 KB
/
app.js
File metadata and controls
799 lines (675 loc) · 28.9 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
class AIConsensus {
constructor() {
this.isDiscussionActive = false;
this.isPaused = false;
this.currentRound = 0;
this.maxRounds = 2;
this.messages = [];
this.settings = this.loadSettings();
this.providers = this.initializeProviders();
this.numModels = 3; // Support 3 models
this.initializeElements();
this.bindEvents();
this.loadProviderModels();
}
initializeElements() {
// Main elements
this.mainContent = document.querySelector('.main-content');
this.topicInput = document.getElementById('topicInput');
this.startBtn = document.getElementById('startBtn');
this.chatContainer = document.getElementById('chatContainer');
this.chatSection = document.getElementById('chatSection');
this.summarySection = document.getElementById('summarySection');
this.summaryContent = document.getElementById('summaryContent');
this.toastContainer = document.getElementById('toastContainer');
this.currentTopicBar = document.getElementById('currentTopicBar');
// Set initial state
this.mainContent.classList.add('initial-state');
// Control buttons
this.pauseBtn = document.getElementById('pauseBtn');
this.stopBtn = document.getElementById('stopBtn');
// Settings modal
this.settingsModal = document.getElementById('settingsModal');
this.settingsBtn = document.getElementById('settingsBtn');
this.closeSettingsBtn = document.getElementById('closeSettingsBtn');
this.saveSettingsBtn = document.getElementById('saveSettingsBtn');
this.cancelSettingsBtn = document.getElementById('cancelSettingsBtn');
// Settings inputs for all 3 models
this.modelSettings = [];
for (let i = 1; i <= this.numModels; i++) {
this.modelSettings.push({
providerSelect: document.getElementById(`providerAgent${i}`),
modelSelect: document.getElementById(`modelAgent${i}`),
apiKeyInput: document.getElementById(`apiKeyAgent${i}`),
baseUrlInput: document.getElementById(`baseUrlAgent${i}`),
baseUrlGroup: document.getElementById(`baseUrlAgent${i}Group`)
});
}
// General settings
this.maxRoundsInput = document.getElementById('maxRounds');
// Initialize start button state
if (this.startBtn && this.topicInput) {
this.startBtn.disabled = !this.topicInput.value.trim();
}
}
bindEvents() {
// Start discussion
this.startBtn.addEventListener('click', () => this.startDiscussion());
this.topicInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
this.startDiscussion();
}
});
this.topicInput.addEventListener('input', () => {
this.startBtn.disabled = !this.topicInput.value.trim();
});
// Suggestion chips
document.querySelectorAll('.suggestion-chip').forEach(chip => {
chip.addEventListener('click', () => {
this.topicInput.value = chip.textContent.trim();
this.topicInput.focus();
this.startBtn.disabled = false;
});
});
// Control buttons
this.pauseBtn.addEventListener('click', () => this.togglePause());
this.stopBtn.addEventListener('click', () => this.stopDiscussion());
// Settings modal
this.settingsBtn.addEventListener('click', () => this.openSettings());
this.closeSettingsBtn.addEventListener('click', () => this.closeSettings());
this.saveSettingsBtn.addEventListener('click', () => this.saveSettings());
this.cancelSettingsBtn.addEventListener('click', () => this.closeSettings());
// Provider changes
this.modelSettings.forEach((setting, index) => {
setting.providerSelect.addEventListener('change', () => this.onProviderChange(index + 1));
});
// Modal overlay click
this.settingsModal.addEventListener('click', (e) => {
if (e.target === this.settingsModal) {
this.closeSettings();
}
});
// Load saved settings
this.loadSettingsToUI();
}
initializeProviders() {
return {
openai: {
name: 'OpenAI',
baseUrl: 'https://api.openai.com/v1',
models: ['gpt-4', 'gpt-4-turbo', 'gpt-3.5-turbo', 'gpt-4o', 'gpt-4o-mini'],
requiresKey: true
},
anthropic: {
name: 'Anthropic',
baseUrl: 'https://api.anthropic.com/v1',
models: ['claude-3-5-sonnet-20241022', 'claude-3-opus-20240229', 'claude-3-sonnet-20240229', 'claude-3-haiku-20240307'],
requiresKey: true
},
openrouter: {
name: 'OpenRouter',
baseUrl: 'https://openrouter.ai/api/v1',
models: [],
requiresKey: true,
fetchModels: true
},
lmstudio: {
name: 'LM Studio',
baseUrl: 'http://localhost:1234/v1',
models: [],
requiresKey: false,
fetchModels: true,
showBaseUrl: true
},
ollama: {
name: 'Ollama',
baseUrl: 'http://localhost:11434/api',
models: [],
requiresKey: false,
fetchModels: true,
showBaseUrl: true
},
google: {
name: 'Google AI',
baseUrl: 'https://generativelanguage.googleapis.com/v1beta',
models: ['gemini-pro', 'gemini-1.5-pro', 'gemini-1.5-flash'],
requiresKey: true
}
};
}
async startDiscussion() {
const topic = this.topicInput.value.trim();
if (!topic) {
this.showError('Please enter a question for discussion');
return;
}
if (!this.validateSettings()) {
this.openSettings();
return;
}
this.isDiscussionActive = true;
this.isPaused = false;
this.currentRound = 0;
this.messages = [];
// Update UI
this.mainContent.classList.remove('initial-state');
this.mainContent.classList.add('discussion-active');
this.startBtn.style.display = 'none';
this.pauseBtn.style.display = 'inline-flex';
this.stopBtn.style.display = 'inline-flex';
this.summarySection.style.display = 'none';
this.chatContainer.innerHTML = '';
if (this.currentTopicBar) {
this.currentTopicBar.textContent = topic;
this.currentTopicBar.style.display = 'block';
}
try {
await this.runDiscussion(topic);
} catch (error) {
this.showError(`Discussion failed: ${error.message}`);
this.stopDiscussion();
}
}
async runDiscussion(topic) {
// Run discussion in rounds - each model contributes once per round
for (let round = 0; round < this.maxRounds && this.isDiscussionActive; round++) {
this.currentRound = round + 1;
// Each model takes a turn in this round
for (let modelIndex = 0; modelIndex < this.numModels && this.isDiscussionActive; modelIndex++) {
const modelConfig = this.settings[`agent${modelIndex + 1}`];
const modelName = this.getModelDisplayName(modelIndex + 1);
// Show typing indicator
this.showTypingIndicator(modelName);
// Build context for this model
const context = this.buildContext(topic, round, modelIndex);
const systemPrompt = this.getSystemPrompt(topic, round, modelIndex);
try {
// Respect pause state
while (this.isPaused && this.isDiscussionActive) {
await this.delay(150);
}
// Get AI response
const response = await this.getAIResponseWithRetry(context, systemPrompt, modelIndex);
// Remove typing indicator
this.removeTypingIndicator();
if (!this.isDiscussionActive) break;
const safeResponse = (response && response.trim()) ? response : 'I need more time to think about this.';
// Add message to UI
await this.addMessageWithAnimation(modelName, safeResponse, modelIndex + 1);
// Store message
this.messages.push({
model: modelName,
content: safeResponse,
round: round + 1,
modelIndex: modelIndex
});
} catch (error) {
this.removeTypingIndicator();
if (!this.isDiscussionActive) break;
const fallback = 'I encountered an issue. Let me listen to the others.';
await this.addMessageWithAnimation(modelName, fallback, modelIndex + 1);
this.messages.push({ model: modelName, content: fallback, round: round + 1, error: true });
}
}
}
if (this.isDiscussionActive) {
await this.generateSummary(topic);
this.stopDiscussion();
}
}
getSystemPrompt(topic, round, modelIndex) {
if (round === 0) {
// First round - share initial perspective
return `You are discussing: "${topic}"
You are one of ${this.numModels} AI models working together to find the best answer.
<thought>
Consider the question carefully. What's your initial perspective? (Keep to 1-2 sentences)
</thought>
<response>
Share your initial thoughts on this question in 2-3 clear sentences. Be specific and constructive.
</response>`;
} else {
// Later rounds - build on discussion and find common ground
return `You are discussing: "${topic}"
You are one of ${this.numModels} AI models working together to reach consensus.
<thought>
Review what others said. What do you agree with? What can you add? (1-2 sentences)
</thought>
<response>
In 2-3 sentences: acknowledge points you agree with, add any new insights, and help move toward a consensus answer. Be collaborative.
</response>`;
}
}
buildContext(topic, round, modelIndex) {
let context = `Topic: ${topic}\n\n`;
if (this.messages.length > 0) {
context += "Previous discussion:\n";
this.messages.forEach((msg) => {
context += `${msg.model}: ${msg.content}\n\n`;
});
}
context += `\nYou are in round ${round + 1} of ${this.maxRounds}. `;
if (round === this.maxRounds - 1) {
context += "This is the final round - help synthesize the discussion toward a clear consensus.";
}
return context;
}
async getAIResponseWithRetry(context, systemPrompt, modelIndex, { retries = 1, timeoutMs = 30000 } = {}) {
const attempt = async () => {
const timeoutPromise = new Promise((_, reject) =>
setTimeout(() => reject(new Error('Request timed out')), timeoutMs)
);
return await Promise.race([
this.getAIResponse(context, systemPrompt, modelIndex),
timeoutPromise
]);
};
let lastErr;
for (let i = 0; i <= retries; i++) {
try {
return await attempt();
} catch (err) {
lastErr = err;
await this.delay(300 + i * 300);
}
}
throw lastErr || new Error('Failed to get AI response');
}
async getAIResponse(context, systemPrompt, modelIndex) {
const agentConfig = this.settings[`agent${modelIndex + 1}`];
const provider = this.providers[agentConfig.provider];
const model = agentConfig.model;
const apiKey = agentConfig.apiKey;
if (agentConfig.provider === 'ollama') {
return await this.callOllamaAPI(context, systemPrompt, model, agentConfig.baseUrl);
} else if (agentConfig.provider === 'anthropic') {
return await this.callAnthropicAPI(context, systemPrompt, model, apiKey);
} else {
return await this.callOpenAICompatibleAPI(context, systemPrompt, model, provider.baseUrl, apiKey);
}
}
async callOpenAICompatibleAPI(context, systemPrompt, model, baseUrl, apiKey) {
const response = await fetch(`${baseUrl}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model: model,
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: context }
],
max_tokens: 800,
temperature: 0.7
})
});
if (!response.ok) {
throw new Error(`API request failed: ${response.status}`);
}
const data = await response.json();
return data.choices[0].message.content;
}
async callAnthropicAPI(context, systemPrompt, model, apiKey) {
const response = await fetch('https://api.anthropic.com/v1/messages', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': apiKey,
'anthropic-version': '2023-06-01'
},
body: JSON.stringify({
model: model,
max_tokens: 800,
system: systemPrompt,
messages: [
{ role: 'user', content: context }
],
temperature: 0.7
})
});
if (!response.ok) {
throw new Error(`Anthropic API request failed: ${response.status}`);
}
const data = await response.json();
return data.content[0].text;
}
async callOllamaAPI(context, systemPrompt, model, baseUrl) {
const response = await fetch(`${baseUrl || 'http://localhost:11434'}/api/generate`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: model,
prompt: `${systemPrompt}\n\n${context}`,
stream: false,
options: {
temperature: 0.7,
num_predict: 800
}
})
});
if (!response.ok) {
throw new Error(`Ollama API request failed: ${response.status}`);
}
const data = await response.json();
return data.response;
}
getModelDisplayName(modelNumber) {
const config = this.settings[`agent${modelNumber}`];
const modelName = config.model.split('/').pop().split('-').slice(0, 2).join('-');
return `Model ${modelNumber}`;
}
showTypingIndicator(modelName) {
const typingDiv = document.createElement('div');
const modelNum = parseInt(modelName.split(' ')[1]);
typingDiv.className = `chat-message typing-message agent-${modelNum}`;
typingDiv.innerHTML = `
<div class="message-header">
<div class="agent-info">
<div class="agent-avatar">${modelNum}</div>
</div>
<div class="agent-meta">
<div class="agent-name">${modelName}</div>
</div>
</div>
<div class="typing-indicator">
<span>is thinking</span>
<div class="typing-dots">
<div class="typing-dot"></div>
<div class="typing-dot"></div>
<div class="typing-dot"></div>
</div>
</div>
`;
this.chatContainer.appendChild(typingDiv);
this.chatContainer.scrollTop = this.chatContainer.scrollHeight;
}
removeTypingIndicator() {
const typingMessage = this.chatContainer.querySelector('.typing-message');
if (typingMessage) {
typingMessage.remove();
}
}
async addMessageWithAnimation(modelName, content, modelNumber) {
const messageDiv = document.createElement('div');
messageDiv.className = `chat-message agent-${modelNumber}`;
const modelConfig = this.settings[`agent${modelNumber}`];
const fullModelName = modelConfig.model || 'Unknown Model';
const currentTime = new Date().toLocaleTimeString('en-US', {
hour: '2-digit',
minute: '2-digit',
hour12: false
});
// Parse thought process and response
const thoughtMatch = content.match(/<thought>(.*?)<\/thought>/s);
const responseMatch = content.match(/<response>(.*?)<\/response>/s);
const thoughtContent = thoughtMatch ? thoughtMatch[1].trim() : '';
const responseContent = responseMatch ? responseMatch[1].trim() : content;
const thoughtSection = thoughtContent ? `
<div class="thought-section">
<div class="thought-content">${this.formatMarkdown(thoughtContent)}</div>
</div>
` : '';
const thoughtToggle = thoughtContent ? `
<button class="thought-toggle" onclick="this.parentElement.querySelector('.thought-section').style.display = this.parentElement.querySelector('.thought-section').style.display === 'block' ? 'none' : 'block'; this.textContent = this.textContent === 'Show thought' ? 'Hide thought' : 'Show thought';">Show thought</button>
` : '';
messageDiv.innerHTML = `
<div class="message-header">
<div class="agent-info">
<div class="agent-avatar">${modelNumber}</div>
</div>
<div class="agent-meta">
<div class="agent-name">${modelName}</div>
<div class="agent-model">${fullModelName}</div>
<div class="message-time">${currentTime}</div>
</div>
</div>
<div class="message-content">
<div class="message-text">${this.formatMarkdown(responseContent)}</div>
${thoughtSection}
${thoughtToggle}
</div>
`;
this.chatContainer.appendChild(messageDiv);
this.chatContainer.scrollTop = this.chatContainer.scrollHeight;
}
formatMarkdown(text) {
// Simple markdown formatting
text = text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
text = text.replace(/\*(.*?)\*/g, '<em>$1</em>');
text = text.replace(/`(.*?)`/g, '<code>$1</code>');
text = text.replace(/^- (.*$)/gm, '<li>$1</li>');
text = text.replace(/(<li>.*<\/li>)/gs, '<ul>$1</ul>');
text = text.replace(/\n\n/g, '</p><p>');
text = '<p>' + text + '</p>';
text = text.replace(/<p><\/p>/g, '');
text = text.replace(/<p>(<ul>.*?<\/ul>)<\/p>/gs, '$1');
return text;
}
async generateSummary(topic) {
if (this.messages.length === 0) return;
const summaryPrompt = `Based on this discussion about "${topic}", write a clear 3-4 sentence summary that:
1. States the main points of agreement between the models
2. Highlights the consensus answer or recommendation
3. Notes any important nuances or considerations mentioned
Keep it concise and focused on what the models agreed on.`;
const context = this.messages.map(msg => `${msg.model}: ${msg.content}`).join('\n\n');
try {
// Use the first model to generate summary
const summary = await this.getAIResponse(context, summaryPrompt, 0);
this.summaryContent.innerHTML = this.formatMarkdown(summary);
this.summarySection.style.display = 'block';
} catch (error) {
console.error('Failed to generate summary:', error);
// Fallback summary
this.summaryContent.innerHTML = '<p>The models discussed this topic and shared their perspectives. Review the conversation above to see their insights.</p>';
this.summarySection.style.display = 'block';
}
}
togglePause() {
if (!this.isDiscussionActive) return;
this.isPaused = !this.isPaused;
if (this.isPaused) {
this.pauseBtn.innerHTML = '<i class="fas fa-play"></i> Resume';
this.showToast('success', 'Paused');
} else {
this.pauseBtn.innerHTML = '<i class="fas fa-pause"></i> Pause';
this.showToast('success', 'Resumed');
}
}
stopDiscussion() {
this.isDiscussionActive = false;
this.isPaused = false;
this.mainContent.classList.remove('discussion-active');
this.mainContent.classList.add('initial-state');
this.pauseBtn.style.display = 'none';
this.stopBtn.style.display = 'none';
this.startBtn.style.display = 'inline-flex';
this.startBtn.innerHTML = '<i class="fas fa-paper-plane"></i>';
this.removeTypingIndicator();
if (this.currentTopicBar) {
this.currentTopicBar.style.display = 'none';
}
}
// Settings Management
openSettings() {
this.settingsModal.classList.add('active');
}
closeSettings() {
this.settingsModal.classList.remove('active');
}
async saveSettings() {
const newSettings = {};
for (let i = 1; i <= this.numModels; i++) {
const setting = this.modelSettings[i - 1];
newSettings[`agent${i}`] = {
provider: setting.providerSelect?.value || 'openai',
model: setting.modelSelect?.value || '',
apiKey: setting.apiKeyInput?.value || '',
baseUrl: setting.baseUrlInput?.value || ''
};
}
newSettings.maxRounds = parseInt(this.maxRoundsInput?.value) || 2;
// Validate
for (let i = 1; i <= this.numModels; i++) {
if (!newSettings[`agent${i}`].model) {
this.showError(`Please select a model for Model ${i}`);
return;
}
const provider = this.providers[newSettings[`agent${i}`].provider];
if (provider.requiresKey && !newSettings[`agent${i}`].apiKey) {
this.showError(`API key required for Model ${i}`);
return;
}
}
this.settings = newSettings;
this.maxRounds = newSettings.maxRounds;
this.saveSettingsToStorage();
this.closeSettings();
this.showSuccess('Settings saved successfully');
}
loadSettingsToUI() {
for (let i = 1; i <= this.numModels; i++) {
const setting = this.modelSettings[i - 1];
const agentSettings = this.settings[`agent${i}`];
if (setting.providerSelect) setting.providerSelect.value = agentSettings.provider;
if (setting.modelSelect) setting.modelSelect.value = agentSettings.model;
if (setting.apiKeyInput) setting.apiKeyInput.value = agentSettings.apiKey;
if (setting.baseUrlInput) setting.baseUrlInput.value = agentSettings.baseUrl;
}
if (this.maxRoundsInput) this.maxRoundsInput.value = this.settings.maxRounds;
// Load models for all agents
for (let i = 1; i <= this.numModels; i++) {
this.onProviderChange(i);
}
}
onProviderChange(modelNumber) {
const setting = this.modelSettings[modelNumber - 1];
const provider = this.providers[setting.providerSelect.value];
const agentConfig = this.settings[`agent${modelNumber}`];
// Show/hide base URL input
if (provider.showBaseUrl) {
setting.baseUrlGroup.style.display = 'block';
setting.baseUrlInput.value = agentConfig.baseUrl || provider.baseUrl;
} else {
setting.baseUrlGroup.style.display = 'none';
}
// Load models
this.loadProviderModels(modelNumber);
}
async loadProviderModels(modelNumber) {
const setting = this.modelSettings[modelNumber - 1];
const providerKey = setting.providerSelect.value;
const provider = this.providers[providerKey];
const agentConfig = this.settings[`agent${modelNumber}`];
setting.modelSelect.innerHTML = '<option value="">Loading models...</option>';
try {
let models = provider.models;
if (provider.fetchModels) {
models = await this.fetchModelsFromProvider(providerKey, agentConfig);
}
setting.modelSelect.innerHTML = '';
models.forEach(model => {
const option = document.createElement('option');
option.value = model;
option.textContent = model;
setting.modelSelect.appendChild(option);
});
if (agentConfig.model && models.includes(agentConfig.model)) {
setting.modelSelect.value = agentConfig.model;
}
} catch (error) {
setting.modelSelect.innerHTML = '<option value="">Failed to load models</option>';
console.error('Failed to load models:', error);
}
}
async fetchModelsFromProvider(providerKey, agentConfig) {
const provider = this.providers[providerKey];
try {
if (providerKey === 'openrouter') {
const response = await fetch('https://openrouter.ai/api/v1/models', {
headers: { 'Authorization': `Bearer ${agentConfig.apiKey}` }
});
const data = await response.json();
return data.data.map(model => model.id);
} else if (providerKey === 'lmstudio') {
const baseUrl = agentConfig.baseUrl || provider.baseUrl;
const response = await fetch(`${baseUrl}/models`);
const data = await response.json();
return data.data.map(model => model.id);
} else if (providerKey === 'ollama') {
const baseUrl = agentConfig.baseUrl || provider.baseUrl;
const response = await fetch(`${baseUrl}/tags`);
const data = await response.json();
return data.models.map(model => model.name);
}
} catch (error) {
console.error(`Failed to fetch models from ${providerKey}:`, error);
}
return provider.models;
}
validateSettings() {
if (!this.settings) return false;
for (let i = 1; i <= this.numModels; i++) {
const agentSettings = this.settings[`agent${i}`];
if (!agentSettings || !agentSettings.model) {
return false;
}
}
return true;
}
loadSettings() {
const defaultSettings = {
agent1: { provider: 'openai', model: 'gpt-3.5-turbo', apiKey: '', baseUrl: '' },
agent2: { provider: 'openai', model: 'gpt-3.5-turbo', apiKey: '', baseUrl: '' },
agent3: { provider: 'openai', model: 'gpt-3.5-turbo', apiKey: '', baseUrl: '' },
maxRounds: 2
};
try {
const saved = localStorage.getItem('ai-consensus-settings');
return saved ? { ...defaultSettings, ...JSON.parse(saved) } : defaultSettings;
} catch {
return defaultSettings;
}
}
saveSettingsToStorage() {
localStorage.setItem('ai-consensus-settings', JSON.stringify(this.settings));
}
showError(message) {
this.showToast('error', message);
}
showSuccess(message) {
this.showToast('success', message);
}
showToast(type, message) {
if (!this.toastContainer) {
console.log(message);
return;
}
const toast = document.createElement('div');
toast.className = `toast toast-${type}`;
const icon = type === 'error' ? 'fa-circle-exclamation' : 'fa-circle-check';
toast.innerHTML = `
<i class="fas ${icon} toast-icon"></i>
<span class="toast-message">${message}</span>
<button class="toast-close" aria-label="Close">×</button>
`;
this.toastContainer.appendChild(toast);
const remove = () => {
if (toast && toast.parentNode) toast.parentNode.removeChild(toast);
};
toast.querySelector('.toast-close').addEventListener('click', remove);
setTimeout(remove, 4000);
}
delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
// Initialize the application when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
new AIConsensus();
});