Spaces:
Running
Running
// DOM Elements for Admin Panel | |
const loginScreen = document.getElementById('login-screen'); | |
const adminPanel = document.getElementById('admin-panel'); | |
const usernameInput = document.getElementById('username'); | |
const passwordInput = document.getElementById('password'); | |
const loginBtn = document.getElementById('login-btn'); | |
const loginError = document.getElementById('login-error'); | |
const logoutBtn = document.getElementById('logout-btn'); | |
const sectionTitle = document.getElementById('section-title'); | |
const saveBtn = document.getElementById('save-btn'); | |
const menuItems = document.querySelectorAll('.admin-menu li'); | |
const tabContents = document.querySelectorAll('.tab-content'); | |
// API Settings Form Elements | |
const apiKeyInput = document.getElementById('api-key'); | |
const toggleApiKeyBtn = document.getElementById('toggle-api-key'); | |
const apiEndpointInput = document.getElementById('api-endpoint'); | |
const testApiBtn = document.getElementById('test-api-btn'); | |
// Model Settings Form Elements | |
const modelSelect = document.getElementById('model-select'); | |
const modelDescription = document.getElementById('model-description'); | |
const temperatureSlider = document.getElementById('temperature'); | |
const tempValue = document.getElementById('temp-value'); | |
const maxTokensSlider = document.getElementById('max-tokens'); | |
const tokensValue = document.getElementById('tokens-value'); | |
// Instructions Form Elements | |
const chatbotInstructions = document.getElementById('chatbot-instructions'); | |
const includeKnowledgeBase = document.getElementById('include-knowledge-base'); | |
const templateSelect = document.getElementById('template-select'); | |
const applyTemplateBtn = document.getElementById('apply-template-btn'); | |
// Tone Settings Form Elements | |
const toneOptions = document.querySelectorAll('input[name="tone"]'); | |
const responseStyle = document.getElementById('response-style'); | |
const customToneInstructions = document.getElementById('custom-tone-instructions'); | |
const generatePreviewBtn = document.getElementById('generate-preview-btn'); | |
const previewResponse = document.querySelector('.preview-response'); | |
// Advanced Settings Form Elements | |
const enableMemory = document.getElementById('enable-memory'); | |
const memoryLimit = document.getElementById('memory-limit'); | |
const enableStreaming = document.getElementById('enable-streaming'); | |
const enableWebSearch = document.getElementById('enable-web-search'); | |
const widgetPosition = document.getElementById('widget-position'); | |
const primaryColor = document.getElementById('primary-color'); | |
const autoOpen = document.getElementById('auto-open'); | |
// Chat configuration object (will be loaded from localStorage) | |
let chatConfig = { | |
apiKey: '', | |
apiEndpoint: 'https://api.deepseek.com/v1/chat/completions', | |
model: 'deepseek-chat', | |
instructions: 'You are a helpful, friendly AI assistant called DeepSeek.', | |
toneStyle: 'friendly', | |
responseStyle: 'balanced', | |
customTone: '', | |
maxTokens: 1000, | |
temperature: 0.7, | |
memory: true, | |
memoryContext: 10, | |
streaming: true, | |
webSearch: false, | |
widgetPosition: 'bottom-right', | |
primaryColor: '#4285f4', | |
autoOpen: true | |
}; | |
// Admin Templates | |
const templates = { | |
'customer-support': { | |
instructions: 'You are DeepSeek, a helpful customer support assistant. Your role is to provide clear, accurate information about our products and services, help troubleshoot issues, and ensure customers feel valued and supported. Be friendly but professional, offer solutions rather than just explanations, and ask clarifying questions when needed.', | |
tone: 'professional' | |
}, | |
'technical-assistant': { | |
instructions: 'You are DeepSeek, a technical assistant specializing in programming, software development, and IT support. Provide detailed technical explanations, code samples when appropriate, and help users solve technical problems. Use precise terminology but remain accessible to users with varying levels of technical expertise.', | |
tone: 'professional' | |
}, | |
'creative-writer': { | |
instructions: 'You are DeepSeek, a creative writing assistant. Help users with storytelling, poetry, creative content ideas, and writing improvements. Be imaginative, inspirational, and provide examples that showcase various writing styles. When asked to generate creative content, aim for originality and emotional resonance.', | |
tone: 'casual' | |
}, | |
'research-assistant': { | |
instructions: 'You are DeepSeek, a research assistant with broad knowledge across academic fields. Help users find information, explore concepts, understand complex topics, and organize research findings. Provide comprehensive and nuanced responses while maintaining academic rigor. Cite limitations of your knowledge when appropriate.', | |
tone: 'formal' | |
} | |
}; | |
// Model descriptions | |
const modelDescriptions = { | |
'deepseek-chat': '<strong>DeepSeek Chat:</strong> General-purpose AI designed for conversation, providing helpful and accurate responses across a wide range of topics.', | |
'deepseek-chat-plus': '<strong>DeepSeek Chat Plus:</strong> Enhanced version of DeepSeek Chat with improved reasoning capabilities and more extensive knowledge base. Ideal for complex conversations.', | |
'deepseek-coder': '<strong>DeepSeek Coder:</strong> Specialized model for programming and software development tasks. Excels at code generation, debugging, and technical explanations.', | |
'deepseek-research': '<strong>DeepSeek Research:</strong> Advanced model optimized for research tasks, data analysis, and academic content. Features in-depth knowledge across scientific domains.' | |
}; | |
// Add error handling wrapper | |
function handleAsyncError(fn) { | |
return async function(...args) { | |
try { | |
await fn.apply(this, args); | |
} catch (error) { | |
console.error('Error:', error); | |
showNotification(error.message, 'error'); | |
} | |
}; | |
} | |
// Handle login with rate limiting | |
let loginAttempts = 0; | |
let lastLoginAttempt = 0; | |
async function handleLogin() { | |
const now = Date.now(); | |
const timeSinceLastAttempt = now - lastLoginAttempt; | |
// Rate limiting | |
if (loginAttempts >= 5 && timeSinceLastAttempt < 300000) { // 5 minutes lockout | |
const remainingTime = Math.ceil((300000 - timeSinceLastAttempt) / 60000); | |
loginError.textContent = `Too many attempts. Please try again in ${remainingTime} minutes.`; | |
return; | |
} | |
const username = usernameInput.value; | |
const password = passwordInput.value; | |
if (!username || !password) { | |
loginError.textContent = 'Please enter both username and password.'; | |
return; | |
} | |
const storedUsername = localStorage.getItem('adminUsername'); | |
const storedPassword = localStorage.getItem('adminPassword'); | |
lastLoginAttempt = now; | |
if (username === storedUsername && password === storedPassword) { | |
loginAttempts = 0; | |
loginScreen.classList.add('hidden'); | |
adminPanel.classList.remove('hidden'); | |
loadConfig(); | |
setFormValues(); | |
} else { | |
loginAttempts++; | |
loginError.textContent = 'Invalid username or password'; | |
setTimeout(() => { | |
loginError.textContent = ''; | |
}, 3000); | |
} | |
} | |
// Handle logout with confirmation | |
function handleLogout() { | |
if (hasUnsavedChanges()) { | |
if (!confirm('You have unsaved changes. Are you sure you want to logout?')) { | |
return; | |
} | |
} | |
adminPanel.classList.add('hidden'); | |
loginScreen.classList.remove('hidden'); | |
usernameInput.value = ''; | |
passwordInput.value = ''; | |
resetUnsavedChanges(); | |
} | |
// Track unsaved changes | |
let hasUnsavedChanges = () => false; | |
let resetUnsavedChanges = () => {}; | |
// Set up change tracking | |
function setupChangeTracking() { | |
const formElements = document.querySelectorAll('input, select, textarea'); | |
let initialValues = new Map(); | |
formElements.forEach(element => { | |
initialValues.set(element, element.value); | |
element.addEventListener('change', () => { | |
const hasChanges = Array.from(formElements).some(el => | |
initialValues.get(el) !== el.value | |
); | |
hasUnsavedChanges = () => hasChanges; | |
}); | |
}); | |
resetUnsavedChanges = () => { | |
formElements.forEach(element => { | |
initialValues.set(element, element.value); | |
}); | |
hasUnsavedChanges = () => false; | |
}; | |
} | |
// Save configuration with validation | |
async function saveConfig() { | |
// Validate API settings | |
if (!apiKeyInput.value) { | |
showNotification('API Key is required.', 'error'); | |
return; | |
} | |
if (!apiEndpointInput.value) { | |
showNotification('API Endpoint is required.', 'error'); | |
return; | |
} | |
// Validate model settings | |
if (parseFloat(temperatureSlider.value) < 0 || parseFloat(temperatureSlider.value) > 1) { | |
showNotification('Temperature must be between 0 and 1.', 'error'); | |
return; | |
} | |
// Save configuration | |
try { | |
// API Settings | |
chatConfig.apiKey = apiKeyInput.value; | |
chatConfig.apiEndpoint = apiEndpointInput.value; | |
// Model Settings | |
chatConfig.model = modelSelect.value; | |
chatConfig.temperature = parseFloat(temperatureSlider.value); | |
chatConfig.maxTokens = parseInt(maxTokensSlider.value); | |
// Instructions | |
chatConfig.instructions = chatbotInstructions.value; | |
// Tone Settings | |
toneOptions.forEach(option => { | |
if (option.checked) { | |
chatConfig.toneStyle = option.value; | |
} | |
}); | |
chatConfig.responseStyle = responseStyle.value; | |
chatConfig.customTone = customToneInstructions.value; | |
// Advanced Settings | |
chatConfig.memory = enableMemory.checked; | |
chatConfig.memoryContext = parseInt(memoryLimit.value); | |
chatConfig.streaming = enableStreaming.checked; | |
chatConfig.webSearch = enableWebSearch.checked; | |
chatConfig.widgetPosition = widgetPosition.value; | |
chatConfig.primaryColor = primaryColor.value; | |
chatConfig.autoOpen = autoOpen.checked; | |
// Save to localStorage | |
localStorage.setItem('chatConfig', JSON.stringify(chatConfig)); | |
// Reset unsaved changes tracker | |
resetUnsavedChanges(); | |
// Show success notification | |
showNotification('Changes saved successfully.', 'success'); | |
// Broadcast configuration change event | |
window.dispatchEvent(new CustomEvent('chatConfigUpdated', { detail: chatConfig })); | |
} catch (error) { | |
console.error('Save Error:', error); | |
showNotification('Failed to save changes: ' + error.message, 'error'); | |
} | |
} | |
// Test API connection with timeout | |
async function testApiConnection() { | |
const apiKey = apiKeyInput.value; | |
const apiEndpoint = apiEndpointInput.value; | |
if (!apiKey) { | |
showNotification('Please enter an API key.', 'error'); | |
return; | |
} | |
showNotification('Testing API connection...', 'info'); | |
try { | |
const controller = new AbortController(); | |
const timeoutId = setTimeout(() => controller.abort(), 10000); // 10 second timeout | |
const response = await fetch(apiEndpoint, { | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json', | |
'Authorization': `Bearer ${apiKey}` | |
}, | |
body: JSON.stringify({ | |
model: modelSelect.value, | |
messages: [ | |
{ | |
role: "system", | |
content: "You are a helpful assistant." | |
}, | |
{ | |
role: "user", | |
content: "Hello, this is a test message." | |
} | |
], | |
max_tokens: 10 | |
}), | |
signal: controller.signal | |
}); | |
clearTimeout(timeoutId); | |
if (response.ok) { | |
const data = await response.json(); | |
if (data.choices && data.choices[0]?.message?.content) { | |
showNotification('API connection successful!', 'success'); | |
} else { | |
throw new Error('Invalid API response format'); | |
} | |
} else { | |
const error = await response.json(); | |
throw new Error(error.error?.message || 'Unknown error'); | |
} | |
} catch (error) { | |
if (error.name === 'AbortError') { | |
showNotification('API request timed out. Please check your connection.', 'error'); | |
} else { | |
showNotification(`Connection error: ${error.message}`, 'error'); | |
} | |
} | |
} | |
// Apply template with validation | |
function applyTemplate() { | |
const template = templateSelect.value; | |
if (!template) { | |
showNotification('Please select a template.', 'warning'); | |
return; | |
} | |
if (hasUnsavedChanges()) { | |
if (!confirm('Applying a template will overwrite your current changes. Continue?')) { | |
return; | |
} | |
} | |
const selectedTemplate = templates[template]; | |
if (!selectedTemplate) { | |
showNotification('Template not found.', 'error'); | |
return; | |
} | |
try { | |
chatbotInstructions.value = selectedTemplate.instructions; | |
// Set tone | |
toneOptions.forEach(option => { | |
if (option.value === selectedTemplate.tone) { | |
option.checked = true; | |
} | |
}); | |
showNotification(`Applied ${templateSelect.options[templateSelect.selectedIndex].text} template.`, 'success'); | |
} catch (error) { | |
console.error('Template Error:', error); | |
showNotification('Failed to apply template: ' + error.message, 'error'); | |
} | |
} | |
// Generate preview with error handling | |
async function generatePreview() { | |
try { | |
// Collect current settings | |
let instructions = chatbotInstructions.value; | |
let tone = ''; | |
toneOptions.forEach(option => { | |
if (option.checked) { | |
tone = option.value; | |
} | |
}); | |
// Add tone customization to instructions | |
let toneInstruction = ''; | |
switch (tone) { | |
case 'friendly': | |
toneInstruction = 'Be warm, approachable, and conversational in your responses.'; | |
break; | |
case 'professional': | |
toneInstruction = 'Maintain a professional, business-like tone while being helpful.'; | |
break; | |
case 'casual': | |
toneInstruction = 'Keep your tone relaxed and casual, like chatting with a friend.'; | |
break; | |
case 'formal': | |
toneInstruction = 'Use a formal, academic tone with precise language.'; | |
break; | |
default: | |
throw new Error('Invalid tone selected'); | |
} | |
// Response style | |
let styleInstruction = ''; | |
switch (responseStyle.value) { | |
case 'concise': | |
styleInstruction = 'Keep your responses brief and to the point.'; | |
break; | |
case 'detailed': | |
styleInstruction = 'Provide detailed, comprehensive responses.'; | |
break; | |
case 'balanced': | |
styleInstruction = 'Balance brevity with thoroughness in your responses.'; | |
break; | |
default: | |
throw new Error('Invalid response style selected'); | |
} | |
// Custom tone instructions | |
let customInstructions = customToneInstructions.value; | |
// Combine all instructions | |
let fullInstructions = `${instructions}\n\n${toneInstruction}\n${styleInstruction}`; | |
if (customInstructions) { | |
fullInstructions += '\n\n' + customInstructions; | |
} | |
// Generate preview | |
let previewText = generatePreviewText(tone, responseStyle.value); | |
previewResponse.textContent = previewText; | |
showNotification('Preview generated.', 'info'); | |
} catch (error) { | |
console.error('Preview Error:', error); | |
showNotification('Failed to generate preview: ' + error.message, 'error'); | |
} | |
} | |
// Generate preview text | |
function generatePreviewText(tone, style) { | |
let baseText = ''; | |
switch (tone) { | |
case 'friendly': | |
baseText = 'Hi there! I\'m DeepSeek, your friendly AI assistant. I\'m here to help you with any questions or tasks you have today. Just let me know what you need assistance with, and I\'ll do my best to help you out!'; | |
break; | |
case 'professional': | |
baseText = 'Welcome. I\'m DeepSeek, your AI assistant. I\'m ready to provide you with accurate information and efficient assistance with your queries. Please let me know how I can be of service to you today.'; | |
break; | |
case 'casual': | |
baseText = 'Hey! DeepSeek here. What\'s up? Got anything you want to chat about or need help with? I\'m all ears and ready to jump in whenever you are!'; | |
break; | |
case 'formal': | |
baseText = 'Greetings. I am DeepSeek, an artificial intelligence assistant designed to provide you with information and assistance. I would be pleased to address any inquiries or requests you may have at this time.'; | |
break; | |
default: | |
baseText = 'Hello, I\'m DeepSeek. How can I help you today?'; | |
} | |
switch (style) { | |
case 'concise': | |
return baseText.split('.')[0] + '.'; | |
case 'detailed': | |
return baseText + ' I can help with information retrieval, creative content, problem-solving, and many other tasks. My knowledge base includes a wide range of topics, though I have some limitations on real-time data and specialized expertise. Feel free to be specific with your requests so I can provide the most helpful response.'; | |
case 'balanced': | |
default: | |
return baseText; | |
} | |
} | |
// Show notification with queue | |
const notificationQueue = []; | |
let isShowingNotification = false; | |
function showNotification(message, type = 'info') { | |
notificationQueue.push({ message, type }); | |
if (!isShowingNotification) { | |
showNextNotification(); | |
} | |
} | |
async function showNextNotification() { | |
if (notificationQueue.length === 0) { | |
isShowingNotification = false; | |
return; | |
} | |
isShowingNotification = true; | |
const { message, type } = notificationQueue.shift(); | |
const notification = document.createElement('div'); | |
notification.classList.add('notification', `notification-${type}`); | |
notification.textContent = message; | |
document.body.appendChild(notification); | |
await new Promise(resolve => setTimeout(resolve, 5000)); | |
notification.classList.add('notification-hide'); | |
await new Promise(resolve => setTimeout(resolve, 500)); | |
notification.remove(); | |
showNextNotification(); | |
} | |
// Initialize | |
document.addEventListener('DOMContentLoaded', () => { | |
setupChangeTracking(); | |
// Add event listeners | |
loginBtn.addEventListener('click', handleAsyncError(handleLogin)); | |
logoutBtn.addEventListener('click', handleLogout); | |
saveBtn.addEventListener('click', handleAsyncError(saveConfig)); | |
testApiBtn.addEventListener('click', handleAsyncError(testApiConnection)); | |
applyTemplateBtn.addEventListener('click', handleAsyncError(applyTemplate)); | |
generatePreviewBtn.addEventListener('click', handleAsyncError(generatePreview)); | |
// Window beforeunload handler | |
window.addEventListener('beforeunload', (e) => { | |
if (hasUnsavedChanges()) { | |
e.preventDefault(); | |
e.returnValue = ''; | |
} | |
}); | |
}); | |