feat: integración de Asistente IA contextual con Llama.cpp Qwen3 Coder 30B (SDD-009, v3.8.24)
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"version": "3.8.23",
|
||||
"version": "3.8.24",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
/**
|
||||
* ai-chat-widget.js - Lógica interactiva del Asistente IA (SDD-009)
|
||||
* Maneja el estado conversacional, llamadas AJAX al backend FastAPI,
|
||||
* persistencia de sesión y renderizado accesible de mensajes.
|
||||
*/
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
let isProcessing = false;
|
||||
const STORAGE_KEY = 'edu_space_ai_chat_messages_v1';
|
||||
|
||||
function getContainer() {
|
||||
return document.getElementById('aiChatContainer');
|
||||
}
|
||||
|
||||
function getUserRole() {
|
||||
const container = getContainer();
|
||||
return (container ? container.getAttribute('data-user-role') : 'alumno') || 'alumno';
|
||||
}
|
||||
|
||||
function getWelcomeMessage(role) {
|
||||
const r = (role || 'alumno').toLowerCase();
|
||||
if (r.includes('docente') || r.includes('profesor') || r.includes('teacher')) {
|
||||
return "¡Hola! 👋 Soy tu <strong>Tutor de Edu-Space</strong> para Docentes. Puedo orientarte sobre cómo consultar tus aulas asignadas, cargar calificaciones en el <strong>Gradebook</strong>, cerrar actas de regularidad y gestionar enlaces de Google Meet. ¿En qué puedo asistirte?";
|
||||
} else if (r.includes('bedelia') || r.includes('admin')) {
|
||||
return "¡Hola! 👋 Soy el <strong>Asistente Técnico de Bedelía</strong>. Puedo ayudarte con el <strong>flujo secuencial de 9 pasos</strong>, matriz de conflictos áulicos, el Optimizador Genético, importación masiva de Google Sheets y la cola de Moodle 4.1. ¿Qué tarea deseas revisar?";
|
||||
} else {
|
||||
return "¡Hola! 👋 Soy tu <strong>Tutor de Cursada</strong>. Puedo ayudarte a consultar en qué aula o sala virtual cursas hoy, ver tus horarios semanales, verificar materias inscriptas y notas académicas. ¿Cuál es tu consulta?";
|
||||
}
|
||||
}
|
||||
|
||||
function loadHistory() {
|
||||
try {
|
||||
const raw = sessionStorage.getItem(STORAGE_KEY);
|
||||
return raw ? JSON.parse(raw) : [];
|
||||
} catch (e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function saveHistory(messages) {
|
||||
try {
|
||||
sessionStorage.setItem(STORAGE_KEY, JSON.stringify(messages));
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
function renderMarkdown(text) {
|
||||
if (!text) return '';
|
||||
let escaped = text
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>');
|
||||
|
||||
// Negrita **texto**
|
||||
escaped = escaped.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
|
||||
// Cursiva *texto*
|
||||
escaped = escaped.replace(/\*(.*?)\*/g, '<em>$1</em>');
|
||||
// Código inline `codigo`
|
||||
escaped = escaped.replace(/`([^`]+)`/g, '<code>$1</code>');
|
||||
// Saltos de línea
|
||||
escaped = escaped.replace(/\n/g, '<br>');
|
||||
|
||||
return escaped;
|
||||
}
|
||||
|
||||
function appendMessage(role, content, save = true) {
|
||||
const messagesContainer = document.getElementById('aiChatMessages');
|
||||
if (!messagesContainer) return;
|
||||
|
||||
const isUser = role === 'user';
|
||||
const msgDiv = document.createElement('div');
|
||||
msgDiv.className = `ai-msg ${isUser ? 'ai-msg-user' : 'ai-msg-assistant'}`;
|
||||
msgDiv.innerHTML = isUser ? renderMarkdown(content) : renderMarkdown(content);
|
||||
|
||||
messagesContainer.appendChild(msgDiv);
|
||||
messagesContainer.scrollTop = messagesContainer.scrollHeight;
|
||||
|
||||
if (save) {
|
||||
const history = loadHistory();
|
||||
history.push({ role, content });
|
||||
saveHistory(history);
|
||||
}
|
||||
}
|
||||
|
||||
function initChat() {
|
||||
const launcher = document.getElementById('aiChatLauncher');
|
||||
const panel = document.getElementById('aiChatPanel');
|
||||
const closeBtn = document.getElementById('aiChatCloseBtn');
|
||||
const clearBtn = document.getElementById('aiChatClearBtn');
|
||||
const textarea = document.getElementById('aiChatInput');
|
||||
const form = document.getElementById('aiChatForm');
|
||||
|
||||
if (!launcher || !panel) return;
|
||||
|
||||
// Toggle panel
|
||||
launcher.addEventListener('click', () => {
|
||||
const isHidden = panel.classList.contains('d-none');
|
||||
if (isHidden) {
|
||||
panel.classList.remove('d-none');
|
||||
launcher.style.transform = 'scale(0.9)';
|
||||
setTimeout(() => {
|
||||
if (textarea) textarea.focus();
|
||||
}, 100);
|
||||
} else {
|
||||
panel.classList.add('d-none');
|
||||
launcher.style.transform = '';
|
||||
}
|
||||
});
|
||||
|
||||
if (closeBtn) {
|
||||
closeBtn.addEventListener('click', () => {
|
||||
panel.classList.add('d-none');
|
||||
launcher.style.transform = '';
|
||||
});
|
||||
}
|
||||
|
||||
// Limpiar conversación
|
||||
if (clearBtn) {
|
||||
clearBtn.addEventListener('click', () => {
|
||||
if (confirm('¿Deseas reiniciar la conversación con el tutor?')) {
|
||||
sessionStorage.removeItem(STORAGE_KEY);
|
||||
const messagesContainer = document.getElementById('aiChatMessages');
|
||||
if (messagesContainer) messagesContainer.innerHTML = '';
|
||||
const role = getUserRole();
|
||||
appendMessage('assistant', getWelcomeMessage(role), false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Cargar historial previo o mensaje de bienvenida
|
||||
const history = loadHistory();
|
||||
const role = getUserRole();
|
||||
if (history.length > 0) {
|
||||
history.forEach(msg => appendMessage(msg.role, msg.content, false));
|
||||
} else {
|
||||
appendMessage('assistant', getWelcomeMessage(role), false);
|
||||
}
|
||||
|
||||
// Auto-resize de textarea y atajo Enter
|
||||
if (textarea) {
|
||||
textarea.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
if (form) form.dispatchEvent(new Event('submit', { cancelable: true }));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
window.handleAiChatSubmit = async function(e) {
|
||||
if (e) e.preventDefault();
|
||||
if (isProcessing) return;
|
||||
|
||||
const textarea = document.getElementById('aiChatInput');
|
||||
const typing = document.getElementById('aiChatTyping');
|
||||
const sendBtn = document.getElementById('aiChatSendBtn');
|
||||
if (!textarea) return;
|
||||
|
||||
const query = textarea.value.trim();
|
||||
if (!query) return;
|
||||
|
||||
// Limpiar campo de texto y mostrar mensaje del usuario
|
||||
textarea.value = '';
|
||||
appendMessage('user', query, true);
|
||||
|
||||
// Bloquear UI e indicar escritura
|
||||
isProcessing = true;
|
||||
if (typing) typing.classList.remove('d-none');
|
||||
if (sendBtn) sendBtn.disabled = true;
|
||||
|
||||
const userRole = getUserRole();
|
||||
const rawHistory = loadHistory();
|
||||
const payloadMessages = rawHistory.map(m => ({
|
||||
role: m.role,
|
||||
content: m.content
|
||||
}));
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/chat', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
messages: payloadMessages,
|
||||
user_role: userRole
|
||||
})
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
if (res.ok && data.response) {
|
||||
appendMessage('assistant', data.response, true);
|
||||
} else {
|
||||
const errorMsg = data.detail || data.message || 'El motor de IA local no está respondiendo en este momento.';
|
||||
appendMessage('assistant', `⚠️ <em>${errorMsg}</em>`, false);
|
||||
}
|
||||
} catch (err) {
|
||||
appendMessage('assistant', `⚠️ <em>No se pudo comunicar con el servidor local de IA: ${err.message}</em>`, false);
|
||||
} finally {
|
||||
isProcessing = false;
|
||||
if (typing) typing.classList.add('d-none');
|
||||
if (sendBtn) sendBtn.disabled = false;
|
||||
textarea.focus();
|
||||
}
|
||||
};
|
||||
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', initChat);
|
||||
} else {
|
||||
initChat();
|
||||
}
|
||||
})();
|
||||
+30
-3
@@ -86,9 +86,9 @@ const env = nunjucks.configure(path.join(__dirname, '../views'), {
|
||||
});
|
||||
|
||||
// Versiones institucionales del sistema
|
||||
const APP_VERSION = '3.8.23';
|
||||
const FRONTEND_VERSION = '3.8.23';
|
||||
const BACKEND_VERSION = '3.8.23';
|
||||
const APP_VERSION = '3.8.24';
|
||||
const FRONTEND_VERSION = '3.8.24';
|
||||
const BACKEND_VERSION = '3.8.24';
|
||||
|
||||
env.addGlobal('app_version', APP_VERSION);
|
||||
env.addGlobal('frontend_version', FRONTEND_VERSION);
|
||||
@@ -365,6 +365,33 @@ app.use('/api/genetic', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Proxy transparente hacia la API del Asistente IA (/api/chat)
|
||||
app.use('/api/chat', async (req, res) => {
|
||||
try {
|
||||
const token = req.cookies.auth_token;
|
||||
const backendBase = (process.env.FLASK_API_URL || 'http://localhost:5000/api/v1').replace(/\/api\/v1\/?$/, '');
|
||||
const targetUrl = `${backendBase}/api/chat${req.url}`;
|
||||
const headers = { ...req.headers };
|
||||
delete headers.host;
|
||||
delete headers['content-length'];
|
||||
if (token && !headers.authorization) {
|
||||
headers.authorization = `Bearer ${token}`;
|
||||
}
|
||||
const resp = await axios({
|
||||
method: req.method,
|
||||
url: targetUrl,
|
||||
data: req.body,
|
||||
params: req.query,
|
||||
headers,
|
||||
validateStatus: () => true
|
||||
});
|
||||
return res.status(resp.status).json(resp.data);
|
||||
} catch (err) {
|
||||
console.error('API chat proxy error:', err.message);
|
||||
return res.status(500).json({ error: 'ProxyError', message: 'Error de comunicación con el Asistente IA: ' + err.message });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
app.use('/', indexRoutes);
|
||||
app.use('/auth', authRoutes);
|
||||
|
||||
@@ -1869,6 +1869,8 @@ router.post('/settings/moodle/test', forwardSettingsAction);
|
||||
router.post('/settings/moodle/sync', forwardSettingsAction);
|
||||
router.get('/settings/moodle/stats', forwardSettingsAction);
|
||||
router.post('/settings/ui', forwardSettingsAction);
|
||||
router.post('/settings/ai', forwardSettingsAction);
|
||||
router.post('/settings/ai/test', forwardSettingsAction);
|
||||
router.post('/settings/reset_system', forwardSettingsAction);
|
||||
router.post('/system/reset', forwardSettingsAction);
|
||||
|
||||
|
||||
@@ -88,6 +88,11 @@
|
||||
<i class="bi bi-window-desktop me-2 text-primary"></i>Interfaz & Dashboard
|
||||
</button>
|
||||
</li>
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link" id="tab-ai-btn" data-bs-toggle="tab" data-bs-target="#tab-ai" type="button" role="tab">
|
||||
<i class="bi bi-cpu me-2 text-success"></i>Asistente IA & LLM Local
|
||||
</button>
|
||||
</li>
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link text-danger" id="tab-maintenance-btn" data-bs-toggle="tab" data-bs-target="#tab-maintenance" type="button" role="tab">
|
||||
<i class="bi bi-radioactive me-2 text-danger"></i>Mantenimiento & Reinicio
|
||||
@@ -555,7 +560,165 @@
|
||||
</div>
|
||||
|
||||
<!-- ========================================== -->
|
||||
<!-- PESTAÑA 5: MANTENIMIENTO & REINICIO -->
|
||||
<!-- PESTAÑA 5: ASISTENTE IA & LLM LOCAL (SDD-009) -->
|
||||
<!-- ========================================== -->
|
||||
<div class="tab-pane fade" id="tab-ai" role="tabpanel">
|
||||
<div class="row g-4">
|
||||
<div class="col-lg-8">
|
||||
<form id="aiConfigForm" onsubmit="saveAiConfig(event)">
|
||||
<!-- Estado General del Asistente -->
|
||||
<div class="card border shadow-none bg-body-tertiary p-3 mb-4 rounded-3">
|
||||
<h6 class="fw-bold mb-3 d-flex align-items-center">
|
||||
<i class="bi bi-robot text-success me-2"></i>Estado del Tutor Inteligente
|
||||
</h6>
|
||||
|
||||
<div class="form-check form-switch p-0 d-flex align-items-center justify-content-between mb-3 border rounded p-3 bg-body">
|
||||
<div class="pe-3">
|
||||
<label class="form-check-label fw-bold mb-1 d-block text-body" for="ai_enabled_switch">
|
||||
Habilitar Asistente IA Conversacional en la Plataforma
|
||||
</label>
|
||||
<div class="text-muted small">
|
||||
Despliega el widget de chat contextual flotante en la interfaz para todos los perfiles de usuario autenticados (Docentes, Alumnos y Bedelía).
|
||||
</div>
|
||||
</div>
|
||||
<input class="form-check-input ms-2 fs-4" type="checkbox" role="switch" id="ai_enabled_switch"
|
||||
{% if not settings or not settings.ai or settings.ai.enabled %}checked{% endif %}>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Parámetros de Conexión Llama.cpp / OpenAI Compatible -->
|
||||
<div class="card border shadow-none bg-body-tertiary p-3 mb-4 rounded-3">
|
||||
<h6 class="fw-bold mb-3 d-flex align-items-center">
|
||||
<i class="bi bi-hdd-network text-primary me-2"></i>Conexión al Servidor de Inferencia Local
|
||||
</h6>
|
||||
|
||||
<div class="row g-3">
|
||||
<div class="col-md-8">
|
||||
<label class="form-label small fw-semibold" for="ai_base_url">URL Base de la API (Endpoint v1)</label>
|
||||
<div class="input-group input-group-sm">
|
||||
<span class="input-group-text"><i class="bi bi-link-45deg"></i></span>
|
||||
<input type="url" class="form-control" id="ai_base_url" name="base_url"
|
||||
placeholder="http://10.0.0.214:8080/v1"
|
||||
value="{{ settings.ai.base_url if settings and settings.ai else 'http://10.0.0.214:8080/v1' }}" required>
|
||||
</div>
|
||||
<div class="form-text small">Endpoint compatible con OpenAI expuesto por Llama.cpp en la red local institucional.</div>
|
||||
</div>
|
||||
|
||||
<div class="col-md-4">
|
||||
<label class="form-label small fw-semibold" for="ai_api_key">Clave API (API Key)</label>
|
||||
<div class="input-group input-group-sm">
|
||||
<span class="input-group-text"><i class="bi bi-key"></i></span>
|
||||
<input type="password" class="form-control" id="ai_api_key" name="api_key"
|
||||
placeholder="••••••••••••"
|
||||
value="{{ settings.ai.api_key if settings and settings.ai else 'llama' }}">
|
||||
</div>
|
||||
<div class="form-text small">Token Bearer para autorización con el motor de IA.</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Configuración del Modelo y Límites de Contexto -->
|
||||
<div class="card border shadow-none bg-body-tertiary p-3 mb-4 rounded-3">
|
||||
<h6 class="fw-bold mb-3 d-flex align-items-center">
|
||||
<i class="bi bi-cpu-fill text-info me-2"></i>Modelo de Lenguaje & Parámetros de Generación
|
||||
</h6>
|
||||
|
||||
<div class="row g-3 mb-3">
|
||||
<div class="col-md-6">
|
||||
<label class="form-label small fw-semibold" for="ai_model">ID del Modelo (Llama.cpp / Ollama)</label>
|
||||
<input type="text" class="form-control form-control-sm" id="ai_model" name="model"
|
||||
placeholder="qwen3-coder:30b"
|
||||
value="{{ settings.ai.model if settings and settings.ai else 'qwen3-coder:30b' }}" required>
|
||||
<div class="form-text small">Identificador exacto configurado en el servidor de inferencia.</div>
|
||||
</div>
|
||||
|
||||
<div class="col-md-6">
|
||||
<label class="form-label small fw-semibold" for="ai_model_name">Nombre Descriptivo</label>
|
||||
<input type="text" class="form-control form-control-sm" id="ai_model_name" name="model_name"
|
||||
placeholder="Qwen3 Coder 30B-A3B (Llama.cpp)"
|
||||
value="{{ settings.ai.model_name if settings and settings.ai else 'Qwen3 Coder 30B-A3B (Llama.cpp)' }}">
|
||||
<div class="form-text small">Etiqueta mostrada en el encabezado del widget de chat.</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row g-3">
|
||||
<div class="col-md-3">
|
||||
<label class="form-label small fw-semibold" for="ai_temperature">Temperatura</label>
|
||||
<input type="number" step="0.05" min="0.0" max="2.0" class="form-control form-control-sm" id="ai_temperature" name="temperature"
|
||||
value="{{ settings.ai.temperature if settings and settings.ai else '0.3' }}" required>
|
||||
<div class="form-text small">0.3 recomendado para respuestas técnicas exactas.</div>
|
||||
</div>
|
||||
|
||||
<div class="col-md-3">
|
||||
<label class="form-label small fw-semibold" for="ai_timeout">Timeout (Segundos)</label>
|
||||
<input type="number" min="5" max="600" class="form-control form-control-sm" id="ai_timeout" name="timeout"
|
||||
value="{{ settings.ai.timeout if settings and settings.ai else '60' }}" required>
|
||||
<div class="form-text small">Tiempo límite para inferencias asíncronas no bloqueantes.</div>
|
||||
</div>
|
||||
|
||||
<div class="col-md-3">
|
||||
<label class="form-label small fw-semibold" for="ai_context_limit">Tokens Contexto</label>
|
||||
<input type="number" class="form-control form-control-sm" id="ai_context_limit" name="context_limit"
|
||||
value="{{ settings.ai.context_limit if settings and settings.ai else '65536' }}">
|
||||
<div class="form-text small">Ventana máxima de contexto del modelo (KV Cache).</div>
|
||||
</div>
|
||||
|
||||
<div class="col-md-3">
|
||||
<label class="form-label small fw-semibold" for="ai_output_limit">Tokens Salida</label>
|
||||
<input type="number" class="form-control form-control-sm" id="ai_output_limit" name="output_limit"
|
||||
value="{{ settings.ai.output_limit if settings and settings.ai else '65536' }}">
|
||||
<div class="form-text small">Límite de tokens de la respuesta generada.</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Contenedor de Resultado de Prueba -->
|
||||
<div id="aiTestResult" class="mb-3"></div>
|
||||
|
||||
<!-- Acciones del Formulario -->
|
||||
<div class="d-flex justify-content-between flex-wrap gap-2">
|
||||
<button type="button" class="btn btn-outline-info btn-sm px-3" id="btnTestAi" onclick="testAiConnection()">
|
||||
<i class="bi bi-activity me-1"></i>Probar Conexión con Llama.cpp
|
||||
</button>
|
||||
<button type="submit" class="btn btn-success btn-sm px-4" id="btnSaveAi">
|
||||
<i class="bi bi-check2-circle me-1"></i>Guardar Configuración de IA
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<!-- Panel Lateral: Arquitectura y Roles del Agente -->
|
||||
<div class="col-lg-4">
|
||||
<div class="card border-0 bg-success-subtle text-success-emphasis p-3 rounded-3 mb-3 shadow-sm">
|
||||
<h6 class="fw-bold mb-2"><i class="bi bi-shield-check me-2"></i>Arquitectura de Seguridad & Roles</h6>
|
||||
<p class="small mb-2">
|
||||
El backend inyecta automáticamente un <strong>System Prompt contextual</strong> según el rol del usuario autenticado:
|
||||
</p>
|
||||
<ul class="small mb-2 ps-3">
|
||||
<li><strong>Docente:</strong> Guía de reserva de aulas, actas en Gradebook y enlaces de Google Meet.</li>
|
||||
<li><strong>Alumno:</strong> Guía de cursada, aulas del día y horarios. <em>Prohibición total de funciones de gestión.</em></li>
|
||||
<li><strong>Bedelía / Admin:</strong> Soporte Nivel 1 en el flujo de 9 pasos, resolución de colisiones y Moodle 4.1.</li>
|
||||
</ul>
|
||||
<div class="text-success small fw-semibold">
|
||||
<i class="bi bi-lightning-charge me-1"></i>Inferencia 100% asíncrona no bloqueante con <code>httpx</code>.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card border-0 bg-body-tertiary p-3 rounded-3">
|
||||
<h6 class="fw-bold mb-2"><i class="bi bi-server me-1"></i>Topología del Servidor Local</h6>
|
||||
<div class="small text-muted mb-2">
|
||||
<strong>Host:</strong> <code>10.0.0.214:8080</code><br>
|
||||
<strong>Motor:</strong> Llama.cpp Server (OpenAI Compatible)<br>
|
||||
<strong>Modelo Oficial:</strong> Qwen3 Coder 30B-A3B<br>
|
||||
<strong>Hardware:</strong> Servidor Dedicado GPU UniCABA
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ========================================== -->
|
||||
<!-- PESTAÑA 6: MANTENIMIENTO & REINICIO -->
|
||||
<!-- ========================================== -->
|
||||
<div class="tab-pane fade" id="tab-maintenance" role="tabpanel">
|
||||
<div class="row g-4">
|
||||
@@ -1251,6 +1414,92 @@ async function saveUiConfig(e) {
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// Guardar Configuración del Asistente IA (Llama.cpp)
|
||||
// -------------------------------------------------------------
|
||||
async function saveAiConfig(e) {
|
||||
e.preventDefault();
|
||||
const btn = document.getElementById('btnSaveAi');
|
||||
btn.disabled = true;
|
||||
btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Guardando...';
|
||||
|
||||
const payload = {
|
||||
enabled: document.getElementById('ai_enabled_switch').checked,
|
||||
base_url: document.getElementById('ai_base_url').value.trim(),
|
||||
api_key: document.getElementById('ai_api_key').value.trim(),
|
||||
model: document.getElementById('ai_model').value.trim(),
|
||||
model_name: document.getElementById('ai_model_name').value.trim(),
|
||||
temperature: parseFloat(document.getElementById('ai_temperature').value) || 0.3,
|
||||
timeout: parseInt(document.getElementById('ai_timeout').value, 10) || 60,
|
||||
context_limit: parseInt(document.getElementById('ai_context_limit').value, 10) || 65536,
|
||||
output_limit: parseInt(document.getElementById('ai_output_limit').value, 10) || 65536
|
||||
};
|
||||
|
||||
try {
|
||||
const res = await fetch('/admin/settings/ai', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
const data = await res.json();
|
||||
if (res.ok && data.status === 'success') {
|
||||
showAlert(data.message || 'Configuración de Asistente IA guardada correctamente.', 'success');
|
||||
} else {
|
||||
showAlert(data.message || 'Error al guardar la configuración de IA.', 'danger');
|
||||
}
|
||||
} catch (err) {
|
||||
showAlert('Error de comunicación con el servidor: ' + err.message, 'danger');
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.innerHTML = '<i class="bi bi-check2-circle me-1"></i>Guardar Configuración de IA';
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// Probar Conexión con Servidor Llama.cpp Local
|
||||
// -------------------------------------------------------------
|
||||
async function testAiConnection() {
|
||||
const btn = document.getElementById('btnTestAi');
|
||||
const resultBox = document.getElementById('aiTestResult');
|
||||
btn.disabled = true;
|
||||
btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Conectando...';
|
||||
resultBox.innerHTML = '<div class="alert alert-info py-2 px-3 small mb-0"><span class="spinner-border spinner-border-sm me-2"></span>Verificando disponibilidad de Llama.cpp y consultando endpoint de modelos...</div>';
|
||||
|
||||
const payload = {
|
||||
base_url: document.getElementById('ai_base_url').value.trim(),
|
||||
api_key: document.getElementById('ai_api_key').value.trim()
|
||||
};
|
||||
|
||||
try {
|
||||
const res = await fetch('/admin/settings/ai/test', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
const data = await res.json();
|
||||
|
||||
if (res.ok && data.status === 'success') {
|
||||
const modelsList = (data.models && data.models.length > 0) ? ` Modelos detectados: <code>${data.models.join(', ')}</code>` : '';
|
||||
resultBox.innerHTML = `
|
||||
<div class="alert alert-success py-2 px-3 small mb-0 d-flex align-items-center justify-content-between">
|
||||
<div>
|
||||
<i class="bi bi-check-circle-fill me-2"></i><strong>${data.message}</strong>${modelsList}
|
||||
</div>
|
||||
<span class="badge bg-success-subtle text-success-emphasis border border-success-subtle font-monospace">${data.latency_ms || 0} ms</span>
|
||||
</div>`;
|
||||
} else if (data.status === 'warning') {
|
||||
resultBox.innerHTML = `<div class="alert alert-warning py-2 px-3 small mb-0"><i class="bi bi-exclamation-triangle-fill me-2"></i><strong>Aviso:</strong> ${data.message}</div>`;
|
||||
} else {
|
||||
resultBox.innerHTML = `<div class="alert alert-danger py-2 px-3 small mb-0"><i class="bi bi-x-circle-fill me-2"></i><strong>Fallo de conexión:</strong> ${data.message || 'No se pudo contactar al servidor Llama.cpp.'}</div>`;
|
||||
}
|
||||
} catch (err) {
|
||||
resultBox.innerHTML = `<div class="alert alert-danger py-2 px-3 small mb-0"><i class="bi bi-x-circle-fill me-2"></i><strong>Error de red:</strong> ${err.message}</div>`;
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.innerHTML = '<i class="bi bi-activity me-1"></i>Probar Conexión con Llama.cpp';
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// Reinicialización Total del Sistema (Requiere Contraseña Admin)
|
||||
// -------------------------------------------------------------
|
||||
|
||||
@@ -1780,5 +1780,8 @@
|
||||
});
|
||||
</script>
|
||||
|
||||
{% if auth_user and auth_user.is_authenticated %}
|
||||
{% include "partials/ai_chat_widget.html" %}
|
||||
{% endif %}
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,265 @@
|
||||
{% set current_role_name = (current_user.role if current_user and current_user.role else (user.role if user and user.role else 'alumno')) | lower %}
|
||||
<!-- ===================================================== -->
|
||||
<!-- WIDGET FLOTANTE: ASISTENTE IA Y CHATBOT CONTEXTUAL -->
|
||||
<!-- SDD-009: UniCABA Edu-Space AI Assistant (Llama.cpp) -->
|
||||
<!-- ===================================================== -->
|
||||
|
||||
<div id="aiChatContainer" class="ai-chat-container" data-user-role="{{ current_role_name }}">
|
||||
<!-- Botón Lanzador Flotante -->
|
||||
<button id="aiChatLauncher" class="ai-chat-launcher btn shadow-lg" type="button" aria-label="Abrir Asistente IA" title="Asistente IA - Tutor Contextual UniCABA">
|
||||
<span class="ai-launcher-icon"><i class="bi bi-robot"></i></span>
|
||||
<span class="ai-launcher-badge pulse-dot"></span>
|
||||
</button>
|
||||
|
||||
<!-- Panel de Conversación (Expandible) -->
|
||||
<div id="aiChatPanel" class="ai-chat-panel card shadow-lg border-0 d-none" role="dialog" aria-modal="true" aria-labelledby="aiChatTitle">
|
||||
<!-- Cabecera del Chat -->
|
||||
<div class="card-header ai-chat-header d-flex align-items-center justify-content-between p-3 border-bottom">
|
||||
<div class="d-flex align-items-center gap-2 overflow-hidden">
|
||||
<div class="ai-avatar-circle">
|
||||
<i class="bi bi-cpu-fill text-white"></i>
|
||||
</div>
|
||||
<div class="lh-sm text-truncate">
|
||||
<h6 class="mb-0 fw-bold text-truncate text-white" id="aiChatTitle">
|
||||
Tutor Edu-Space
|
||||
<span class="badge bg-success-subtle text-success-emphasis border border-success-subtle ms-1 font-monospace" style="font-size: 0.65rem;">Llama.cpp</span>
|
||||
</h6>
|
||||
<small class="text-white-50" style="font-size: 0.72rem;">
|
||||
<span class="status-indicator-dot me-1"></span>Qwen3 Coder 30B •
|
||||
<span class="text-uppercase fw-semibold text-warning-emphasis" id="aiRoleBadge">{{ current_role_name }}</span>
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
<div class="d-flex align-items-center gap-1">
|
||||
<button type="button" class="btn btn-sm btn-outline-light border-0 py-1 px-2" id="aiChatClearBtn" title="Limpiar conversación">
|
||||
<i class="bi bi-trash3"></i>
|
||||
</button>
|
||||
<button type="button" class="btn btn-sm btn-outline-light border-0 py-1 px-2" id="aiChatCloseBtn" title="Minimizar chat">
|
||||
<i class="bi bi-x-lg"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Cuerpo de Mensajes -->
|
||||
<div class="card-body ai-chat-messages p-3" id="aiChatMessages" tabindex="0">
|
||||
<!-- Mensaje de Bienvenida Inicial generado dinámicamente por JS según el rol -->
|
||||
</div>
|
||||
|
||||
<!-- Indicador de Escritura -->
|
||||
<div id="aiChatTyping" class="ai-typing-indicator px-3 py-1 d-none">
|
||||
<small class="text-muted d-flex align-items-center gap-2">
|
||||
<span class="typing-dot"></span>
|
||||
<span class="typing-dot"></span>
|
||||
<span class="typing-dot"></span>
|
||||
<span>El tutor está formulando la respuesta...</span>
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<!-- Área de Entrada / Envío -->
|
||||
<div class="card-footer ai-chat-footer p-2 bg-body-tertiary border-top">
|
||||
<form id="aiChatForm" class="d-flex align-items-center gap-2 m-0" onsubmit="handleAiChatSubmit(event)">
|
||||
<textarea id="aiChatInput" class="form-control form-control-sm ai-chat-textarea"
|
||||
rows="1"
|
||||
placeholder="Pregúntale al tutor sobre el sistema..."
|
||||
aria-label="Mensaje para el Asistente"></textarea>
|
||||
<button type="submit" class="btn btn-primary btn-sm rounded-circle ai-send-btn" id="aiChatSendBtn" title="Enviar mensaje">
|
||||
<i class="bi bi-send-fill"></i>
|
||||
</button>
|
||||
</form>
|
||||
<div class="text-center mt-1">
|
||||
<small class="text-muted font-monospace" style="font-size: 0.65rem;">
|
||||
Inferencia local segura UniCABA • Presiona Enter para enviar
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
/* Estilos del Contenedor Flotante */
|
||||
.ai-chat-container {
|
||||
position: fixed;
|
||||
bottom: 24px;
|
||||
right: 24px;
|
||||
z-index: 1060;
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
/* Botón Lanzador */
|
||||
.ai-chat-launcher {
|
||||
width: 58px;
|
||||
height: 58px;
|
||||
border-radius: 50% !important;
|
||||
background: linear-gradient(135deg, #B43E8E 0%, #0d6efd 100%) !important;
|
||||
color: #ffffff !important;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border: 2px solid rgba(255, 255, 255, 0.4) !important;
|
||||
position: relative;
|
||||
cursor: pointer;
|
||||
transition: transform 0.25s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.25s ease;
|
||||
}
|
||||
.ai-chat-launcher:hover {
|
||||
transform: scale(1.08);
|
||||
box-shadow: 0 10px 25px rgba(180, 62, 142, 0.45) !important;
|
||||
}
|
||||
.ai-launcher-icon {
|
||||
font-size: 1.65rem;
|
||||
line-height: 1;
|
||||
}
|
||||
.pulse-dot {
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
right: 4px;
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
background-color: #22c55e;
|
||||
border-radius: 50%;
|
||||
border: 2px solid #ffffff;
|
||||
box-shadow: 0 0 8px #22c55e;
|
||||
animation: aiPulse 2s infinite;
|
||||
}
|
||||
@keyframes aiPulse {
|
||||
0% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(34, 197, 94, 0.7); }
|
||||
70% { transform: scale(1.1); box-shadow: 0 0 0 8px rgba(34, 197, 94, 0); }
|
||||
100% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(34, 197, 94, 0); }
|
||||
}
|
||||
|
||||
/* Panel de Chat */
|
||||
.ai-chat-panel {
|
||||
width: 380px;
|
||||
max-width: calc(100vw - 32px);
|
||||
height: 540px;
|
||||
max-height: calc(100vh - 100px);
|
||||
border-radius: 16px !important;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
animation: aiSlideUp 0.3s cubic-bezier(0.16, 1, 0.3, 1) forwards;
|
||||
box-shadow: 0 20px 45px rgba(0, 0, 0, 0.28) !important;
|
||||
}
|
||||
@keyframes aiSlideUp {
|
||||
from { opacity: 0; transform: translateY(20px) scale(0.96); }
|
||||
to { opacity: 1; transform: translateY(0) scale(1); }
|
||||
}
|
||||
|
||||
/* Cabecera del Chat */
|
||||
.ai-chat-header {
|
||||
background: linear-gradient(135deg, #992875 0%, #0d6efd 100%) !important;
|
||||
}
|
||||
.ai-avatar-circle {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 50%;
|
||||
background: rgba(255, 255, 255, 0.22);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 1.15rem;
|
||||
}
|
||||
.status-indicator-dot {
|
||||
display: inline-block;
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
background-color: #22c55e;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
/* Área de Mensajes */
|
||||
.ai-chat-messages {
|
||||
flex: 1 1 auto;
|
||||
overflow-y: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
scroll-behavior: smooth;
|
||||
}
|
||||
|
||||
/* Burbujas de Mensaje */
|
||||
.ai-msg {
|
||||
max-width: 85%;
|
||||
padding: 10px 14px;
|
||||
border-radius: 14px;
|
||||
font-size: 0.88rem;
|
||||
line-height: 1.45;
|
||||
word-break: break-word;
|
||||
}
|
||||
.ai-msg-user {
|
||||
align-self: flex-end;
|
||||
background-color: #0d6efd;
|
||||
color: #ffffff;
|
||||
border-bottom-right-radius: 4px;
|
||||
}
|
||||
.ai-msg-assistant {
|
||||
align-self: flex-start;
|
||||
border-bottom-left-radius: 4px;
|
||||
}
|
||||
[data-bs-theme="dark"] .ai-msg-assistant {
|
||||
background-color: #1e293b;
|
||||
color: #f1f5f9;
|
||||
border: 1px solid #334155;
|
||||
}
|
||||
[data-bs-theme="light"] .ai-msg-assistant {
|
||||
background-color: #f8fafc;
|
||||
color: #0f172a;
|
||||
border: 1px solid #e2e8f0;
|
||||
}
|
||||
|
||||
.ai-msg code {
|
||||
font-size: 0.82rem;
|
||||
padding: 2px 5px;
|
||||
border-radius: 4px;
|
||||
background: rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
[data-bs-theme="dark"] .ai-msg code {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
/* Indicador de Escritura */
|
||||
.ai-typing-indicator .typing-dot {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
background-color: #94a3b8;
|
||||
border-radius: 50%;
|
||||
animation: typingBounce 1.4s infinite ease-in-out;
|
||||
}
|
||||
.ai-typing-indicator .typing-dot:nth-child(1) { animation-delay: 0s; }
|
||||
.ai-typing-indicator .typing-dot:nth-child(2) { animation-delay: 0.2s; }
|
||||
.ai-typing-indicator .typing-dot:nth-child(3) { animation-delay: 0.4s; }
|
||||
@keyframes typingBounce {
|
||||
0%, 80%, 100% { transform: scale(0.6); opacity: 0.4; }
|
||||
40% { transform: scale(1.1); opacity: 1; }
|
||||
}
|
||||
|
||||
/* Formulario del Chat */
|
||||
.ai-chat-textarea {
|
||||
resize: none;
|
||||
border-radius: 20px;
|
||||
padding-left: 14px;
|
||||
padding-right: 14px;
|
||||
max-height: 80px;
|
||||
}
|
||||
.ai-send-btn {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
@media (max-width: 576px) {
|
||||
.ai-chat-container {
|
||||
bottom: 16px;
|
||||
right: 16px;
|
||||
}
|
||||
.ai-chat-panel {
|
||||
width: calc(100vw - 32px);
|
||||
height: calc(100vh - 120px);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<!-- Script Lógico del Widget -->
|
||||
<script src="/js/ai-chat-widget.js"></script>
|
||||
Reference in New Issue
Block a user