291 lines
12 KiB
Python
291 lines
12 KiB
Python
"""
|
|
Módulo de Integración de Asistente IA (UdeCi) con Arquitectura RAG Embebida
|
|
SDD-009 / SDD-010: Compatible con OpenAI API y Servidor Local Llama.cpp (Qwen3 Coder 30B)
|
|
"""
|
|
import re
|
|
import time
|
|
from typing import Optional, List
|
|
import httpx
|
|
from fastapi import APIRouter, HTTPException, Depends, Request, status
|
|
|
|
from dependencies import get_optional_current_user, require_roles
|
|
from app.models.setting import SystemSetting
|
|
from app.models.user import User
|
|
from app.services.rag_service import RAGService
|
|
from schemas.ai_chat import (
|
|
ChatRequest,
|
|
ChatResponse,
|
|
AITestConnectionResponse,
|
|
AISettingsSchema,
|
|
RAGReindexResponse
|
|
)
|
|
|
|
router = APIRouter(tags=["AI Chatbot"])
|
|
|
|
DEFAULT_ROLE_OPTIONS = {
|
|
"docente": ["📍 Aulas y Google Meet", "📝 Actas de Regularidad", "👥 Ver Comisiones", "❓ Ayuda"],
|
|
"bedelia": ["🔄 Flujo de 9 Pasos", "⚠️ Conflictos Áulicos", "🧬 Optimizador IA", "📑 Importar Sheets"],
|
|
"alumno": ["📍 ¿Dónde curso hoy?", "📚 Mis Materias", "📊 Mis Calificaciones", "❓ Ayuda"]
|
|
}
|
|
|
|
|
|
def generate_system_prompt_for_role(role: Optional[str], rag_context: Optional[str] = None) -> str:
|
|
"""
|
|
Genera el System Prompt de UdeCi enriquecido con fragmentos de conocimiento oficial (RAG),
|
|
imponiendo respuestas cortas, directas y opciones interactivas para el usuario.
|
|
"""
|
|
normalized_role = (role or "alumno").strip().lower()
|
|
if "docente" in normalized_role or "profesor" in normalized_role or "teacher" in normalized_role:
|
|
effective_role = "docente"
|
|
elif "bedelia" in normalized_role or "admin" in normalized_role:
|
|
effective_role = "bedelia"
|
|
else:
|
|
effective_role = "alumno"
|
|
|
|
context_section = rag_context if rag_context else "Consulta el sistema con tu usuario institucional."
|
|
|
|
return (
|
|
f"Eres UdeCi, el tutor virtual institucional de Admin Edu Space (UniCABA).\n"
|
|
f"El usuario tiene el rol de: {effective_role.upper()}.\n\n"
|
|
"REGLAS ESTRICTAS DE RESPUESTA:\n"
|
|
"1. Respuestas BREVES y PRECISAS: Responde en máximo 2 a 3 oraciones cortas o pasos directos. No des introducciones largas ni rodeos.\n"
|
|
"2. INFORMACIÓN OFICIAL: Responde basándote ÚNICAMENTE en la INFORMACIÓN DEL SISTEMA provista abajo. "
|
|
"Si la respuesta no está en esta información o el usuario solicita una acción que no corresponde a su rol, "
|
|
"indícale amablemente que no dispones de los permisos necesarios y que debe contactar a Bedelía.\n"
|
|
"3. Al final de tu mensaje, incluye EXACTAMENTE 2 o 3 opciones breves de seguimiento en este formato:\n"
|
|
"OPCIONES: [Opción 1 | Opción 2 | Opción 3]\n\n"
|
|
f"INFORMACIÓN OFICIAL DEL SISTEMA (RAG):\n{context_section}"
|
|
)
|
|
|
|
|
|
def _get_ai_config() -> dict:
|
|
"""Recupera la configuración activa del motor de IA desde SystemSetting."""
|
|
enabled_val = SystemSetting.get_value("ai_chat_enabled", "true")
|
|
enabled = enabled_val in ["true", "True", "1", True]
|
|
|
|
base_url = SystemSetting.get_value("ai_chat_base_url", "http://10.0.0.214:8080/v1") or "http://10.0.0.214:8080/v1"
|
|
api_key = SystemSetting.get_decrypted_value("ai_chat_api_key", "llama") or "llama"
|
|
model = SystemSetting.get_value("ai_chat_model", "qwen3-coder:30b") or "qwen3-coder:30b"
|
|
model_name = SystemSetting.get_value("ai_chat_model_name", "UdeCi (Tutor Virtual)") or "UdeCi (Tutor Virtual)"
|
|
|
|
try:
|
|
# En RAG se recomienda 0.1 para máxima fidelidad a los fragmentos
|
|
temperature = float(SystemSetting.get_value("ai_chat_temperature", 0.1))
|
|
except (ValueError, TypeError):
|
|
temperature = 0.1
|
|
|
|
try:
|
|
timeout = float(SystemSetting.get_value("ai_chat_timeout", 60.0))
|
|
except (ValueError, TypeError):
|
|
timeout = 60.0
|
|
|
|
return {
|
|
"enabled": enabled,
|
|
"base_url": base_url.strip().rstrip("/"),
|
|
"api_key": api_key.strip(),
|
|
"model": model.strip(),
|
|
"model_name": model_name.strip(),
|
|
"temperature": temperature,
|
|
"timeout": timeout
|
|
}
|
|
|
|
|
|
def _extract_options_from_reply(reply_text: str, role: str) -> tuple[str, List[str]]:
|
|
"""Extrae las opciones sugeridas al final del texto y limpia la respuesta para el usuario."""
|
|
options = []
|
|
clean_text = reply_text
|
|
|
|
match = re.search(r'OPCIONES:\s*\[(.*?)\]', reply_text, re.DOTALL | re.IGNORECASE)
|
|
if match:
|
|
raw_options = match.group(1).split('|')
|
|
options = [opt.strip() for opt in raw_options if opt.strip()]
|
|
clean_text = reply_text[:match.start()].strip()
|
|
|
|
if not options:
|
|
options = DEFAULT_ROLE_OPTIONS.get(role, DEFAULT_ROLE_OPTIONS["alumno"])
|
|
|
|
return clean_text, options
|
|
|
|
|
|
@router.post("/", response_model=ChatResponse)
|
|
@router.post("", response_model=ChatResponse)
|
|
async def get_agent_response(
|
|
request: ChatRequest,
|
|
req: Request,
|
|
current_user: Optional[User] = Depends(get_optional_current_user)
|
|
):
|
|
"""
|
|
Procesa la conversación con UdeCi aplicando la arquitectura RAG:
|
|
1. Resuelve el rol del usuario autenticado.
|
|
2. Ejecuta búsqueda semántica en KnowledgeChunk (RAG) filtrando por rol.
|
|
3. Inyecta el contexto oficial en el prompt para Llama.cpp con baja temperatura (0.1).
|
|
4. Genera respuesta breve y extrae opciones de botones interactivos.
|
|
"""
|
|
config = _get_ai_config()
|
|
|
|
if not config["enabled"]:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
|
detail="UdeCi está temporalmente deshabilitado por el administrador."
|
|
)
|
|
|
|
# 1. Determinar rol efectivo
|
|
effective_role = request.user_role or "alumno"
|
|
if current_user:
|
|
if getattr(current_user, "is_admin", False) or (getattr(current_user, "role", "") or "").upper() == "ADMIN":
|
|
effective_role = "bedelia"
|
|
elif hasattr(current_user, "role") and current_user.role:
|
|
role_str = str(current_user.role).lower()
|
|
if "docente" in role_str or "profesor" in role_str or "teacher" in role_str:
|
|
effective_role = "docente"
|
|
elif "bedelia" in role_str or "admin" in role_str:
|
|
effective_role = "bedelia"
|
|
else:
|
|
effective_role = "alumno"
|
|
|
|
# 2. Búsqueda semántica RAG sobre la última consulta del usuario
|
|
last_query = ""
|
|
for msg in reversed(request.messages):
|
|
if msg.role == "user":
|
|
last_query = msg.content
|
|
break
|
|
|
|
chunks = RAGService.search_relevant_chunks(last_query, effective_role, limit=3)
|
|
context_text = "\n\n".join([f"### {c['title']}\n{c['content']}" for c in chunks])
|
|
|
|
# 3. Inyección de Contexto en el System Prompt
|
|
system_prompt = generate_system_prompt_for_role(effective_role, context_text)
|
|
|
|
formatted_messages = [{"role": "system", "content": system_prompt}]
|
|
for msg in request.messages:
|
|
formatted_messages.append({"role": msg.role, "content": msg.content})
|
|
|
|
# Identificador individual único de usuario / sesión para aislar los slots de KV Cache en Llama.cpp
|
|
if current_user and getattr(current_user, "id", None):
|
|
user_identifier = f"usr_{current_user.id}"
|
|
elif request.conversation_id:
|
|
user_identifier = str(request.conversation_id).strip()
|
|
else:
|
|
client_ip = req.client.host if (req and req.client) else "local"
|
|
user_identifier = f"anon_{client_ip}"
|
|
|
|
payload = {
|
|
"model": config["model"],
|
|
"messages": formatted_messages,
|
|
"temperature": 0.1, # Temperatura estricta para evitar alucinaciones
|
|
"user": user_identifier # Aislamiento individual por usuario en Llama.cpp
|
|
}
|
|
|
|
target_url = f"{config['base_url']}/chat/completions"
|
|
headers = {
|
|
"Authorization": f"Bearer {config['api_key']}",
|
|
"Content-Type": "application/json"
|
|
}
|
|
|
|
# 4. Inferencia asíncrona no bloqueante
|
|
async with httpx.AsyncClient(timeout=config["timeout"]) as client:
|
|
try:
|
|
response = await client.post(target_url, headers=headers, json=payload)
|
|
response.raise_for_status()
|
|
ai_data = response.json()
|
|
raw_reply = ai_data["choices"][0]["message"]["content"]
|
|
clean_reply, options = _extract_options_from_reply(raw_reply, effective_role)
|
|
return ChatResponse(
|
|
response=clean_reply,
|
|
quick_options=options,
|
|
conversation_id=user_identifier
|
|
)
|
|
except httpx.TimeoutException:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_504_GATEWAY_TIMEOUT,
|
|
detail=f"UdeCi superó el tiempo límite de espera ({config['timeout']}s)."
|
|
)
|
|
except httpx.HTTPStatusError as e:
|
|
detail_msg = f"Error del motor de IA local ({e.response.status_code}): {e.response.text[:200]}"
|
|
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=detail_msg)
|
|
except httpx.RequestError as e:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
|
detail="Error conectando con UdeCi. Verifique que el servidor local de IA esté disponible."
|
|
)
|
|
|
|
|
|
@router.post("/rag/reindex", response_model=RAGReindexResponse)
|
|
def reindex_knowledge_base(
|
|
current_user: User = Depends(require_roles(["ADMIN"]))
|
|
):
|
|
"""Reindexa y particiona la documentación oficial en fragmentos RAG."""
|
|
count = RAGService.reindex_default_knowledge()
|
|
return RAGReindexResponse(
|
|
status="success",
|
|
indexed_chunks=count,
|
|
message=f"Se han reindexado exitosamente {count} fragmentos de conocimiento oficial para UdeCi."
|
|
)
|
|
|
|
|
|
@router.post("/test-connection", response_model=AITestConnectionResponse)
|
|
async def test_ai_connection(
|
|
current_user: User = Depends(require_roles(["ADMIN"]))
|
|
):
|
|
"""Verifica conectividad directa con el servidor local consultando /v1/models."""
|
|
config = _get_ai_config()
|
|
target_url = f"{config['base_url']}/models"
|
|
headers = {"Authorization": f"Bearer {config['api_key']}"}
|
|
|
|
start_time = time.time()
|
|
async with httpx.AsyncClient(timeout=10.0) as client:
|
|
try:
|
|
resp = await client.get(target_url, headers=headers)
|
|
latency_ms = round((time.time() - start_time) * 1000, 2)
|
|
if resp.status_code == 200:
|
|
data = resp.json()
|
|
model_ids = [m.get("id") for m in data.get("data", []) if isinstance(m, dict) and "id" in m]
|
|
return AITestConnectionResponse(
|
|
status="success",
|
|
message=f"Conexión exitosa con el servidor local ({config['base_url']}). Latencia: {latency_ms} ms.",
|
|
latency_ms=latency_ms,
|
|
models=model_ids
|
|
)
|
|
else:
|
|
return AITestConnectionResponse(
|
|
status="warning",
|
|
message=f"Respuesta inesperada ({resp.status_code}): {resp.text[:200]}",
|
|
latency_ms=latency_ms,
|
|
models=[]
|
|
)
|
|
except httpx.TimeoutException:
|
|
return AITestConnectionResponse(
|
|
status="error",
|
|
message=f"Tiempo de espera agotado al conectar a {config['base_url']} (Timeout: 10s).",
|
|
latency_ms=None,
|
|
models=[]
|
|
)
|
|
except httpx.RequestError as e:
|
|
return AITestConnectionResponse(
|
|
status="error",
|
|
message=f"No se pudo conectar a {config['base_url']}: {str(e)}",
|
|
latency_ms=None,
|
|
models=[]
|
|
)
|
|
|
|
|
|
@router.get("/config")
|
|
def get_ai_public_config(current_user: Optional[User] = Depends(get_optional_current_user)):
|
|
"""Retorna metadatos públicos de estado de UdeCi para el widget del frontend."""
|
|
config = _get_ai_config()
|
|
role_str = "alumno"
|
|
if current_user and hasattr(current_user, "role") and current_user.role:
|
|
r = str(current_user.role).lower()
|
|
if "docente" in r or "profesor" in r:
|
|
role_str = "docente"
|
|
elif "bedelia" in r or "admin" in r:
|
|
role_str = "bedelia"
|
|
|
|
return {
|
|
"status": "success",
|
|
"enabled": config["enabled"],
|
|
"name": "UdeCi",
|
|
"role": role_str,
|
|
"default_options": DEFAULT_ROLE_OPTIONS.get(role_str, DEFAULT_ROLE_OPTIONS["alumno"])
|
|
}
|