🤖 모델 관리 고도화: - 모델 다운로드: 인기 모델들 원클릭 설치 (llama, qwen, gemma, codellama, mistral) - 모델 삭제: 확인 모달과 함께 안전한 삭제 기능 - 사용 가능한 모델 목록: 태그별 분류 (chat, code, lightweight 등) - 모델 상세 정보: 설명, 크기, 용도별 태그 표시 �� 실시간 시스템 모니터링: - CPU/메모리/디스크/GPU 사용률 원형 프로그레스바 - 색상 코딩: 사용률에 따른 시각적 구분 (녹색/주황/빨강) - 실시간 업데이트: 30초마다 자동 새로고침 - 시스템 리소스 상세 정보 (코어 수, 용량, 온도 등) 🎨 고급 UI/UX: - 모달 창: 부드러운 애니메이션과 블러 효과 - 원형 프로그레스바: CSS 기반 실시간 업데이트 - 반응형 디자인: 모바일 최적화 - 태그 시스템: 모델 분류 및 시각화 🔧 새 API 엔드포인트: - POST /admin/models/download - 모델 다운로드 - DELETE /admin/models/{model_name} - 모델 삭제 - GET /admin/models/available - 다운로드 가능한 모델 목록 - GET /admin/system/stats - 시스템 리소스 사용률 수정된 파일: - server/main.py: Phase 2 API 엔드포인트 추가 - test_admin.py: 테스트 모드 Phase 2 기능 추가 - templates/admin.html: 시스템 모니터링 섹션, 모달 창 추가 - static/admin.css: 모니터링 차트, 모달 스타일 추가 - static/admin.js: Phase 2 기능 JavaScript 구현
442 lines
16 KiB
JavaScript
442 lines
16 KiB
JavaScript
// AI Server Admin Dashboard JavaScript
|
|
|
|
class AdminDashboard {
|
|
constructor() {
|
|
this.apiKey = this.getApiKey();
|
|
this.baseUrl = window.location.origin;
|
|
this.init();
|
|
}
|
|
|
|
getApiKey() {
|
|
// 테스트 모드에서는 기본 API 키 사용
|
|
let apiKey = localStorage.getItem('ai_admin_api_key');
|
|
if (!apiKey) {
|
|
// 테스트 모드 기본 키
|
|
apiKey = 'test-admin-key-123';
|
|
localStorage.setItem('ai_admin_api_key', apiKey);
|
|
|
|
// 사용자에게 알림
|
|
setTimeout(() => {
|
|
alert('테스트 모드입니다.\nAPI Key: test-admin-key-123');
|
|
}, 1000);
|
|
}
|
|
return apiKey;
|
|
}
|
|
|
|
async init() {
|
|
this.updateCurrentTime();
|
|
setInterval(() => this.updateCurrentTime(), 1000);
|
|
|
|
await this.loadSystemStatus();
|
|
await this.loadModels();
|
|
await this.loadApiKeys();
|
|
await this.loadSystemStats(); // Phase 2
|
|
|
|
// Auto-refresh every 30 seconds
|
|
setInterval(() => {
|
|
this.loadSystemStatus();
|
|
this.loadModels();
|
|
this.loadSystemStats(); // Phase 2
|
|
}, 30000);
|
|
}
|
|
|
|
updateCurrentTime() {
|
|
const now = new Date();
|
|
document.getElementById('current-time').textContent =
|
|
now.toLocaleString('ko-KR', {
|
|
year: 'numeric',
|
|
month: '2-digit',
|
|
day: '2-digit',
|
|
hour: '2-digit',
|
|
minute: '2-digit',
|
|
second: '2-digit'
|
|
});
|
|
}
|
|
|
|
async apiRequest(endpoint, options = {}) {
|
|
const url = `${this.baseUrl}${endpoint}`;
|
|
const defaultOptions = {
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'X-API-Key': this.apiKey
|
|
}
|
|
};
|
|
|
|
try {
|
|
const response = await fetch(url, { ...defaultOptions, ...options });
|
|
if (!response.ok) {
|
|
if (response.status === 401) {
|
|
localStorage.removeItem('ai_admin_api_key');
|
|
location.reload();
|
|
return;
|
|
}
|
|
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
}
|
|
return await response.json();
|
|
} catch (error) {
|
|
console.error('API Request failed:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async loadSystemStatus() {
|
|
try {
|
|
// Check AI Server status
|
|
const healthResponse = await this.apiRequest('/health');
|
|
document.getElementById('server-status').textContent = 'Online';
|
|
document.getElementById('server-status').className = 'status-value';
|
|
|
|
// Check Ollama status
|
|
try {
|
|
const ollamaResponse = await this.apiRequest('/admin/ollama/status');
|
|
document.getElementById('ollama-status').textContent =
|
|
ollamaResponse.status === 'online' ? 'Online' : 'Offline';
|
|
document.getElementById('ollama-status').className =
|
|
`status-value ${ollamaResponse.status === 'online' ? '' : 'error'}`;
|
|
} catch (error) {
|
|
document.getElementById('ollama-status').textContent = 'Offline';
|
|
document.getElementById('ollama-status').className = 'status-value error';
|
|
}
|
|
|
|
// Load active model
|
|
try {
|
|
const modelResponse = await this.apiRequest('/admin/models/active');
|
|
document.getElementById('active-model').textContent =
|
|
modelResponse.model || 'None';
|
|
} catch (error) {
|
|
document.getElementById('active-model').textContent = 'Unknown';
|
|
}
|
|
|
|
// Load API call stats (placeholder)
|
|
document.getElementById('api-calls').textContent = '0';
|
|
|
|
} catch (error) {
|
|
console.error('Failed to load system status:', error);
|
|
document.getElementById('server-status').textContent = 'Error';
|
|
document.getElementById('server-status').className = 'status-value error';
|
|
}
|
|
}
|
|
|
|
async loadModels() {
|
|
try {
|
|
const response = await this.apiRequest('/admin/models');
|
|
const models = response.models || [];
|
|
|
|
const tbody = document.getElementById('models-tbody');
|
|
|
|
if (models.length === 0) {
|
|
tbody.innerHTML = '<tr><td colspan="5" class="loading">No models found</td></tr>';
|
|
return;
|
|
}
|
|
|
|
tbody.innerHTML = models.map(model => `
|
|
<tr>
|
|
<td>
|
|
<strong>${model.name}</strong>
|
|
${model.is_active ? '<span class="status-badge active">Active</span>' : ''}
|
|
</td>
|
|
<td>${this.formatSize(model.size)}</td>
|
|
<td>
|
|
<span class="status-badge ${model.status === 'ready' ? 'active' : 'inactive'}">
|
|
${model.status || 'Unknown'}
|
|
</span>
|
|
</td>
|
|
<td>${model.last_used ? new Date(model.last_used).toLocaleString('ko-KR') : 'Never'}</td>
|
|
<td>
|
|
<button class="btn btn-small btn-primary" onclick="admin.testModel('${model.name}')">
|
|
<i class="fas fa-play"></i> Test
|
|
</button>
|
|
<button class="btn btn-small btn-danger" onclick="admin.confirmDeleteModel('${model.name}')">
|
|
<i class="fas fa-trash"></i> Delete
|
|
</button>
|
|
</td>
|
|
</tr>
|
|
`).join('');
|
|
|
|
} catch (error) {
|
|
console.error('Failed to load models:', error);
|
|
document.getElementById('models-tbody').innerHTML =
|
|
'<tr><td colspan="5" class="loading">Error loading models</td></tr>';
|
|
}
|
|
}
|
|
|
|
async loadApiKeys() {
|
|
try {
|
|
const response = await this.apiRequest('/admin/api-keys');
|
|
const apiKeys = response.api_keys || [];
|
|
|
|
const container = document.getElementById('api-keys-list');
|
|
|
|
if (apiKeys.length === 0) {
|
|
container.innerHTML = '<div class="loading">No API keys found</div>';
|
|
return;
|
|
}
|
|
|
|
container.innerHTML = apiKeys.map(key => `
|
|
<div class="api-key-item">
|
|
<div class="api-key-info">
|
|
<div class="api-key-name">${key.name || 'Unnamed Key'}</div>
|
|
<div class="api-key-value">${this.maskApiKey(key.key)}</div>
|
|
<div class="api-key-meta">
|
|
Created: ${new Date(key.created_at).toLocaleString('ko-KR')} |
|
|
Uses: ${key.usage_count || 0}
|
|
</div>
|
|
</div>
|
|
<div class="api-key-actions">
|
|
<button class="btn btn-small btn-danger" onclick="admin.deleteApiKey('${key.id}')">
|
|
<i class="fas fa-trash"></i> Delete
|
|
</button>
|
|
</div>
|
|
</div>
|
|
`).join('');
|
|
|
|
} catch (error) {
|
|
console.error('Failed to load API keys:', error);
|
|
document.getElementById('api-keys-list').innerHTML =
|
|
'<div class="loading">Error loading API keys</div>';
|
|
}
|
|
}
|
|
|
|
formatSize(bytes) {
|
|
if (!bytes) return 'Unknown';
|
|
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
|
|
const i = Math.floor(Math.log(bytes) / Math.log(1024));
|
|
return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i];
|
|
}
|
|
|
|
maskApiKey(key) {
|
|
if (!key) return 'Unknown';
|
|
if (key.length <= 8) return key;
|
|
return key.substring(0, 4) + '...' + key.substring(key.length - 4);
|
|
}
|
|
|
|
async refreshModels() {
|
|
document.getElementById('models-tbody').innerHTML =
|
|
'<tr><td colspan="5" class="loading">Refreshing models...</td></tr>';
|
|
await this.loadModels();
|
|
}
|
|
|
|
async testModel(modelName) {
|
|
try {
|
|
const response = await this.apiRequest('/admin/models/test', {
|
|
method: 'POST',
|
|
body: JSON.stringify({ model: modelName })
|
|
});
|
|
|
|
alert(`Model test result:\n${response.result || 'Test completed successfully'}`);
|
|
} catch (error) {
|
|
alert(`Model test failed: ${error.message}`);
|
|
}
|
|
}
|
|
|
|
async generateApiKey() {
|
|
const name = prompt('Enter a name for the new API key:');
|
|
if (!name) return;
|
|
|
|
try {
|
|
const response = await this.apiRequest('/admin/api-keys', {
|
|
method: 'POST',
|
|
body: JSON.stringify({ name })
|
|
});
|
|
|
|
alert(`New API key created:\n${response.api_key}\n\nPlease save this key securely. It will not be shown again.`);
|
|
await this.loadApiKeys();
|
|
} catch (error) {
|
|
alert(`Failed to generate API key: ${error.message}`);
|
|
}
|
|
}
|
|
|
|
async deleteApiKey(keyId) {
|
|
if (!confirm('Are you sure you want to delete this API key?')) return;
|
|
|
|
try {
|
|
await this.apiRequest(`/admin/api-keys/${keyId}`, {
|
|
method: 'DELETE'
|
|
});
|
|
|
|
await this.loadApiKeys();
|
|
} catch (error) {
|
|
alert(`Failed to delete API key: ${error.message}`);
|
|
}
|
|
}
|
|
|
|
// Phase 2: System Monitoring
|
|
async loadSystemStats() {
|
|
try {
|
|
const response = await this.apiRequest('/admin/system/stats');
|
|
|
|
// Update CPU
|
|
this.updateProgressCircle('cpu-progress', response.cpu.usage_percent);
|
|
document.getElementById('cpu-text').textContent = `${response.cpu.usage_percent}%`;
|
|
document.getElementById('cpu-cores').textContent = `${response.cpu.core_count} cores`;
|
|
|
|
// Update Memory
|
|
this.updateProgressCircle('memory-progress', response.memory.usage_percent);
|
|
document.getElementById('memory-text').textContent = `${response.memory.usage_percent}%`;
|
|
document.getElementById('memory-details').textContent =
|
|
`${response.memory.used_gb} / ${response.memory.total_gb} GB`;
|
|
|
|
// Update Disk
|
|
this.updateProgressCircle('disk-progress', response.disk.usage_percent);
|
|
document.getElementById('disk-text').textContent = `${response.disk.usage_percent}%`;
|
|
document.getElementById('disk-details').textContent =
|
|
`${response.disk.used_gb} / ${response.disk.total_gb} GB`;
|
|
|
|
// Update GPU
|
|
if (response.gpu && response.gpu.length > 0) {
|
|
const gpu = response.gpu[0];
|
|
this.updateProgressCircle('gpu-progress', gpu.load);
|
|
document.getElementById('gpu-text').textContent = `${gpu.load}%`;
|
|
document.getElementById('gpu-details').textContent =
|
|
`${gpu.name} - ${gpu.temperature}°C`;
|
|
} else {
|
|
document.getElementById('gpu-text').textContent = '--';
|
|
document.getElementById('gpu-details').textContent = 'No GPU detected';
|
|
}
|
|
|
|
} catch (error) {
|
|
console.error('Failed to load system stats:', error);
|
|
}
|
|
}
|
|
|
|
updateProgressCircle(elementId, percentage) {
|
|
const element = document.getElementById(elementId);
|
|
const degrees = (percentage / 100) * 360;
|
|
|
|
// Remove existing color classes
|
|
element.classList.remove('low', 'medium', 'high');
|
|
|
|
// Add appropriate color class
|
|
if (percentage < 50) {
|
|
element.classList.add('low');
|
|
} else if (percentage < 80) {
|
|
element.classList.add('medium');
|
|
} else {
|
|
element.classList.add('high');
|
|
}
|
|
|
|
// Update CSS custom property for progress
|
|
element.style.setProperty('--progress', `${degrees}deg`);
|
|
}
|
|
|
|
// Phase 2: Model Download
|
|
async openModelDownload() {
|
|
try {
|
|
const response = await this.apiRequest('/admin/models/available');
|
|
const models = response.available_models || [];
|
|
|
|
const container = document.getElementById('available-models-list');
|
|
|
|
if (models.length === 0) {
|
|
container.innerHTML = '<div class="loading">No models available</div>';
|
|
} else {
|
|
container.innerHTML = models.map(model => `
|
|
<div class="available-model-item">
|
|
<div class="model-info">
|
|
<div class="model-name">${model.name}</div>
|
|
<div class="model-description">${model.description}</div>
|
|
<div class="model-tags">
|
|
${model.tags.map(tag => `<span class="model-tag ${tag}">${tag}</span>`).join('')}
|
|
</div>
|
|
<div class="model-size">Size: ${model.size}</div>
|
|
</div>
|
|
<button class="btn btn-success" onclick="admin.downloadModel('${model.name}')">
|
|
<i class="fas fa-download"></i> Download
|
|
</button>
|
|
</div>
|
|
`).join('');
|
|
}
|
|
|
|
this.openModal('model-download-modal');
|
|
|
|
} catch (error) {
|
|
console.error('Failed to load available models:', error);
|
|
alert('Failed to load available models');
|
|
}
|
|
}
|
|
|
|
async downloadModel(modelName) {
|
|
try {
|
|
const response = await this.apiRequest('/admin/models/download', {
|
|
method: 'POST',
|
|
body: JSON.stringify({ model: modelName })
|
|
});
|
|
|
|
if (response.success) {
|
|
alert(`Download started: ${response.message}`);
|
|
this.closeModal('model-download-modal');
|
|
// Refresh models list after a short delay
|
|
setTimeout(() => this.loadModels(), 2000);
|
|
} else {
|
|
alert(`Download failed: ${response.error}`);
|
|
}
|
|
|
|
} catch (error) {
|
|
alert(`Download failed: ${error.message}`);
|
|
}
|
|
}
|
|
|
|
// Phase 2: Model Delete
|
|
confirmDeleteModel(modelName) {
|
|
document.getElementById('delete-model-name').textContent = modelName;
|
|
|
|
// Set up delete confirmation
|
|
const confirmBtn = document.getElementById('confirm-delete-btn');
|
|
confirmBtn.onclick = () => this.deleteModel(modelName);
|
|
|
|
this.openModal('model-delete-modal');
|
|
}
|
|
|
|
async deleteModel(modelName) {
|
|
try {
|
|
const response = await this.apiRequest(`/admin/models/${modelName}`, {
|
|
method: 'DELETE'
|
|
});
|
|
|
|
if (response.success) {
|
|
alert(`Model deleted: ${response.message}`);
|
|
this.closeModal('model-delete-modal');
|
|
await this.loadModels();
|
|
} else {
|
|
alert(`Delete failed: ${response.error}`);
|
|
}
|
|
|
|
} catch (error) {
|
|
alert(`Delete failed: ${error.message}`);
|
|
}
|
|
}
|
|
|
|
// Modal management
|
|
openModal(modalId) {
|
|
document.getElementById(modalId).style.display = 'block';
|
|
}
|
|
|
|
closeModal(modalId) {
|
|
document.getElementById(modalId).style.display = 'none';
|
|
}
|
|
}
|
|
|
|
// Global functions for HTML onclick handlers
|
|
let admin;
|
|
|
|
function refreshModels() {
|
|
admin.refreshModels();
|
|
}
|
|
|
|
function generateApiKey() {
|
|
admin.generateApiKey();
|
|
}
|
|
|
|
function openModelDownload() {
|
|
admin.openModelDownload();
|
|
}
|
|
|
|
function closeModal(modalId) {
|
|
admin.closeModal(modalId);
|
|
}
|
|
|
|
// Initialize dashboard when page loads
|
|
document.addEventListener('DOMContentLoaded', () => {
|
|
admin = new AdminDashboard();
|
|
});
|