Spaces:
Running
Running
File size: 20,073 Bytes
e9a6464 |
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 |
// 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 = '';
}
});
});
|