feat: arquitectura RAG embebida y asistente UdeCi con botones interactivos (SDD-010, v3.8.25)
This commit is contained in:
@@ -1,13 +1,32 @@
|
||||
/**
|
||||
* 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.
|
||||
* ai-chat-widget.js - Lógica interactiva de UdeCi (SDD-010)
|
||||
* Asistente y Tutor Virtual de UniCABA con soporte RAG,
|
||||
* respuestas concisas y botones de opciones interactivas.
|
||||
*/
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
let isProcessing = false;
|
||||
const STORAGE_KEY = 'edu_space_ai_chat_messages_v1';
|
||||
const STORAGE_KEY = 'edu_space_udeci_chat_history_v2';
|
||||
|
||||
const ROLE_CHIPS = {
|
||||
docente: [
|
||||
{ label: "📍 Aulas y Meet", query: "¿Dónde consulto mis aulas asignadas y salas de Meet?" },
|
||||
{ label: "📝 Actas Gradebook", query: "¿Cómo cargo notas y cierro actas de regularidad?" },
|
||||
{ label: "👥 Ver Comisiones", query: "¿Dónde veo la lista de alumnos inscriptos?" }
|
||||
],
|
||||
bedelia: [
|
||||
{ label: "🔄 Flujo 9 Pasos", query: "¿Cuáles son los 9 pasos del flujo de Bedelía?" },
|
||||
{ label: "⚠️ Conflictos Áulicos", query: "¿Cómo funciona la matriz de conflictos y aforo?" },
|
||||
{ label: "🧬 Optimizador IA", query: "¿Cómo uso el optimizador de aulas?" },
|
||||
{ label: "📑 Importar Sheets", query: "¿Cómo uso el importador de Google Sheets?" }
|
||||
],
|
||||
alumno: [
|
||||
{ label: "📍 ¿Dónde curso hoy?", query: "¿En qué aula curso hoy mis materias?" },
|
||||
{ label: "📚 Mis Materias", query: "¿Dónde consulto mis asignaturas inscriptas?" },
|
||||
{ label: "📊 Calificaciones", query: "¿Cómo veo mis notas y regularidad?" }
|
||||
]
|
||||
};
|
||||
|
||||
function getContainer() {
|
||||
return document.getElementById('aiChatContainer');
|
||||
@@ -15,17 +34,20 @@
|
||||
|
||||
function getUserRole() {
|
||||
const container = getContainer();
|
||||
return (container ? container.getAttribute('data-user-role') : 'alumno') || 'alumno';
|
||||
const rawRole = (container ? container.getAttribute('data-user-role') : 'alumno') || 'alumno';
|
||||
const r = rawRole.toLowerCase();
|
||||
if (r.includes('docente') || r.includes('profesor') || r.includes('teacher')) return 'docente';
|
||||
if (r.includes('bedelia') || r.includes('admin')) return 'bedelia';
|
||||
return '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?";
|
||||
if (role === 'docente') {
|
||||
return "¡Hola! Soy **UdeCi**, tu tutor de Edu-Space para docentes. Puedo orientarte sobre asignaciones de aulas, el Gradebook y clases virtuales.";
|
||||
} else if (role === 'bedelia') {
|
||||
return "¡Hola! Soy **UdeCi**, tu asistente de soporte técnico para Bedelía. Puedo guiarte en el circuito de 9 pasos, resolución de conflictos y Moodle.";
|
||||
} 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?";
|
||||
return "¡Hola! Soy **UdeCi**, tu tutor virtual de cursada. Puedo ayudarte a consultar en qué aula cursas hoy, horarios y notas.";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,107 +85,73 @@
|
||||
return escaped;
|
||||
}
|
||||
|
||||
function appendMessage(role, content, save = true) {
|
||||
function appendMessage(role, content, options = [], 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);
|
||||
|
||||
let html = renderMarkdown(content);
|
||||
|
||||
// Si es mensaje del asistente y tiene opciones, renderizar botones interactivos
|
||||
if (!isUser && options && options.length > 0) {
|
||||
html += '<div class="ai-msg-options">';
|
||||
options.forEach(opt => {
|
||||
const cleanOpt = opt.replace(/^[📍📝👥🔄⚠️🧬📑📚📊❓]\s*/, '').trim();
|
||||
html += `<button type="button" class="ai-option-btn" data-query="${opt}">${opt}</button>`;
|
||||
});
|
||||
html += '</div>';
|
||||
}
|
||||
|
||||
msgDiv.innerHTML = html;
|
||||
messagesContainer.appendChild(msgDiv);
|
||||
messagesContainer.scrollTop = messagesContainer.scrollHeight;
|
||||
|
||||
// Asignar listeners a los botones de opciones dentro de la burbuja
|
||||
msgDiv.querySelectorAll('.ai-option-btn').forEach(btn => {
|
||||
btn.addEventListener('click', function(e) {
|
||||
e.preventDefault();
|
||||
const q = this.getAttribute('data-query');
|
||||
if (q) sendQuery(q);
|
||||
});
|
||||
});
|
||||
|
||||
if (save) {
|
||||
const history = loadHistory();
|
||||
history.push({ role, content });
|
||||
history.push({ role, content, options });
|
||||
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');
|
||||
function populateHeaderChips(role) {
|
||||
const headerChips = document.getElementById('aiQuickChipsHeader');
|
||||
if (!headerChips) return;
|
||||
headerChips.innerHTML = '';
|
||||
|
||||
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 = '';
|
||||
}
|
||||
const chips = ROLE_CHIPS[role] || ROLE_CHIPS.alumno;
|
||||
chips.forEach(chip => {
|
||||
const btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.className = 'ai-quick-chip';
|
||||
btn.textContent = chip.label;
|
||||
btn.title = chip.query;
|
||||
btn.addEventListener('click', () => sendQuery(chip.query));
|
||||
headerChips.appendChild(btn);
|
||||
});
|
||||
|
||||
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;
|
||||
async function sendQuery(queryText) {
|
||||
if (!queryText || 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;
|
||||
if (textarea) textarea.value = '';
|
||||
appendMessage('user', queryText, [], true);
|
||||
|
||||
// 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;
|
||||
@@ -187,19 +175,93 @@
|
||||
|
||||
const data = await res.json();
|
||||
if (res.ok && data.response) {
|
||||
appendMessage('assistant', data.response, true);
|
||||
appendMessage('assistant', data.response, data.quick_options || [], 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);
|
||||
const errorMsg = data.detail || data.message || 'UdeCi no pudo procesar la respuesta en este momento.';
|
||||
appendMessage('assistant', `⚠️ ${errorMsg}`, [], false);
|
||||
}
|
||||
} catch (err) {
|
||||
appendMessage('assistant', `⚠️ <em>No se pudo comunicar con el servidor local de IA: ${err.message}</em>`, false);
|
||||
appendMessage('assistant', `⚠️ Error de comunicación: ${err.message}`, [], false);
|
||||
} finally {
|
||||
isProcessing = false;
|
||||
if (typing) typing.classList.add('d-none');
|
||||
if (sendBtn) sendBtn.disabled = false;
|
||||
textarea.focus();
|
||||
if (textarea) textarea.focus();
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
const role = getUserRole();
|
||||
populateHeaderChips(role);
|
||||
|
||||
// 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 = '';
|
||||
});
|
||||
}
|
||||
|
||||
// Reiniciar conversación
|
||||
if (clearBtn) {
|
||||
clearBtn.addEventListener('click', () => {
|
||||
sessionStorage.removeItem(STORAGE_KEY);
|
||||
const messagesContainer = document.getElementById('aiChatMessages');
|
||||
if (messagesContainer) messagesContainer.innerHTML = '';
|
||||
const initialOptions = (ROLE_CHIPS[role] || []).map(c => c.label);
|
||||
appendMessage('assistant', getWelcomeMessage(role), initialOptions, false);
|
||||
});
|
||||
}
|
||||
|
||||
// Cargar historial previo o mensaje de bienvenida
|
||||
const history = loadHistory();
|
||||
if (history.length > 0) {
|
||||
history.forEach(msg => appendMessage(msg.role, msg.content, msg.options || [], false));
|
||||
} else {
|
||||
const initialOptions = (ROLE_CHIPS[role] || []).map(c => c.label);
|
||||
appendMessage('assistant', getWelcomeMessage(role), initialOptions, false);
|
||||
}
|
||||
|
||||
// Atajo Enter para enviar
|
||||
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 = function(e) {
|
||||
if (e) e.preventDefault();
|
||||
const textarea = document.getElementById('aiChatInput');
|
||||
if (!textarea) return;
|
||||
const text = textarea.value.trim();
|
||||
if (text) sendQuery(text);
|
||||
};
|
||||
|
||||
if (document.readyState === 'loading') {
|
||||
|
||||
Reference in New Issue
Block a user