Upload rag_api.py with huggingface_hub
Browse files- rag_api.py +68 -27
rag_api.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
"""
|
| 2 |
-
Servidor RAG del
|
| 3 |
|
| 4 |
Cambios frente al `rag_api.py` original:
|
| 5 |
|
|
@@ -19,7 +19,10 @@ Para usarlo: reemplaza el `rag_api.py` del Space por este archivo y sube el
|
|
| 19 |
índice con `python scripts/rag/build_rag.py --push-to-hub jimytech/chatbot`.
|
| 20 |
"""
|
| 21 |
|
|
|
|
| 22 |
import os
|
|
|
|
|
|
|
| 23 |
from typing import Dict, List, Optional
|
| 24 |
|
| 25 |
from fastapi import FastAPI, HTTPException
|
|
@@ -72,6 +75,7 @@ GROQ_MODEL = os.environ.get("GROQ_MODEL", "openai/gpt-oss-120b")
|
|
| 72 |
DEEPSEEK_API_KEY = os.environ.get("DEEPSEEK_API_KEY", "")
|
| 73 |
DEEPSEEK_MODEL = os.environ.get("DEEPSEEK_MODEL", "deepseek-flash")
|
| 74 |
DEEPSEEK_BASE_URL = os.environ.get("DEEPSEEK_BASE_URL", "https://api.deepseek.com")
|
|
|
|
| 75 |
|
| 76 |
# --------------------------------------------------------
|
| 77 |
# 2. PROMPTS
|
|
@@ -223,25 +227,47 @@ class _RespuestaLLM:
|
|
| 223 |
|
| 224 |
|
| 225 |
class _LLMDeepSeek:
|
| 226 |
-
"""
|
| 227 |
|
| 228 |
-
|
| 229 |
-
|
|
|
|
|
|
|
| 230 |
"""
|
| 231 |
|
| 232 |
def __init__(self, model: str):
|
| 233 |
-
from openai import OpenAI
|
| 234 |
-
|
| 235 |
-
self._cliente = OpenAI(api_key=DEEPSEEK_API_KEY, base_url=DEEPSEEK_BASE_URL)
|
| 236 |
self._model = model
|
|
|
|
| 237 |
|
| 238 |
def invoke(self, prompt: str) -> _RespuestaLLM:
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 243 |
)
|
| 244 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
|
| 246 |
|
| 247 |
class _LLMConEmergencia:
|
|
@@ -269,26 +295,41 @@ class _LLMConEmergencia:
|
|
| 269 |
|
| 270 |
|
| 271 |
def construir_llm():
|
| 272 |
-
"""Devuelve `(llm, descripción)` según
|
| 273 |
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
|
|
|
|
|
|
| 277 |
"""
|
| 278 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
|
| 280 |
if DEEPSEEK_API_KEY:
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
)
|
| 288 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 289 |
|
| 290 |
-
if
|
| 291 |
-
return
|
| 292 |
|
| 293 |
return None, "ninguno (faltan DEEPSEEK_API_KEY y GROQ_API_KEY)"
|
| 294 |
|
|
@@ -330,7 +371,7 @@ LLM_ACTIVO = "no inicializado"
|
|
| 330 |
try:
|
| 331 |
llm, retriever, LLM_ACTIVO = load_rag()
|
| 332 |
except Exception as e: # noqa: BLE001
|
| 333 |
-
LLM_ACTIVO = f"error al inicializar: {type(e).__name__}"
|
| 334 |
print(f"❌ Error CRÍTICO al inicializar: {type(e).__name__}: {e}")
|
| 335 |
|
| 336 |
|
|
|
|
| 1 |
"""
|
| 2 |
+
Servidor RAG del chatbot UPT Aragua para el Space de HuggingFace.
|
| 3 |
|
| 4 |
Cambios frente al `rag_api.py` original:
|
| 5 |
|
|
|
|
| 19 |
índice con `python scripts/rag/build_rag.py --push-to-hub jimytech/chatbot`.
|
| 20 |
"""
|
| 21 |
|
| 22 |
+
import json
|
| 23 |
import os
|
| 24 |
+
import urllib.error
|
| 25 |
+
import urllib.request
|
| 26 |
from typing import Dict, List, Optional
|
| 27 |
|
| 28 |
from fastapi import FastAPI, HTTPException
|
|
|
|
| 75 |
DEEPSEEK_API_KEY = os.environ.get("DEEPSEEK_API_KEY", "")
|
| 76 |
DEEPSEEK_MODEL = os.environ.get("DEEPSEEK_MODEL", "deepseek-flash")
|
| 77 |
DEEPSEEK_BASE_URL = os.environ.get("DEEPSEEK_BASE_URL", "https://api.deepseek.com")
|
| 78 |
+
DEEPSEEK_TIMEOUT = int(os.environ.get("DEEPSEEK_TIMEOUT", "60"))
|
| 79 |
|
| 80 |
# --------------------------------------------------------
|
| 81 |
# 2. PROMPTS
|
|
|
|
| 227 |
|
| 228 |
|
| 229 |
class _LLMDeepSeek:
|
| 230 |
+
"""Cliente mínimo de la API de DeepSeek (compatible con OpenAI).
|
| 231 |
|
| 232 |
+
Usa `urllib` de la biblioteca estándar **a propósito**: el entorno del Space
|
| 233 |
+
no trae el paquete `openai` (su `requirements.txt` es propio y el CI no lo
|
| 234 |
+
sube), y añadirlo obligaría a tocar el Space. Así este módulo no depende de
|
| 235 |
+
nada que no esté ya instalado: ni `openai` ni `requests`.
|
| 236 |
"""
|
| 237 |
|
| 238 |
def __init__(self, model: str):
|
|
|
|
|
|
|
|
|
|
| 239 |
self._model = model
|
| 240 |
+
self._url = f"{DEEPSEEK_BASE_URL.rstrip('/')}/chat/completions"
|
| 241 |
|
| 242 |
def invoke(self, prompt: str) -> _RespuestaLLM:
|
| 243 |
+
cuerpo = json.dumps(
|
| 244 |
+
{
|
| 245 |
+
"model": self._model,
|
| 246 |
+
"messages": [{"role": "user", "content": prompt}],
|
| 247 |
+
"temperature": 0.15,
|
| 248 |
+
}
|
| 249 |
+
).encode("utf-8")
|
| 250 |
+
|
| 251 |
+
peticion = urllib.request.Request(
|
| 252 |
+
self._url,
|
| 253 |
+
data=cuerpo,
|
| 254 |
+
headers={
|
| 255 |
+
"Content-Type": "application/json",
|
| 256 |
+
"Authorization": f"Bearer {DEEPSEEK_API_KEY}",
|
| 257 |
+
},
|
| 258 |
+
method="POST",
|
| 259 |
)
|
| 260 |
+
|
| 261 |
+
try:
|
| 262 |
+
with urllib.request.urlopen(peticion, timeout=DEEPSEEK_TIMEOUT) as r:
|
| 263 |
+
datos = json.loads(r.read().decode("utf-8"))
|
| 264 |
+
except urllib.error.HTTPError as e:
|
| 265 |
+
# El cuerpo trae el motivo real (clave inválida, saldo, modelo…):
|
| 266 |
+
# sin él, diagnosticar esto es a ciegas.
|
| 267 |
+
detalle = e.read().decode("utf-8", "replace")[:300]
|
| 268 |
+
raise RuntimeError(f"DeepSeek HTTP {e.code}: {detalle}") from e
|
| 269 |
+
|
| 270 |
+
return _RespuestaLLM(datos["choices"][0]["message"]["content"] or "")
|
| 271 |
|
| 272 |
|
| 273 |
class _LLMConEmergencia:
|
|
|
|
| 295 |
|
| 296 |
|
| 297 |
def construir_llm():
|
| 298 |
+
"""Devuelve `(llm, descripción)` según lo que haya disponible.
|
| 299 |
|
| 300 |
+
**Ningún fallo aquí puede dejar el Space sin LLM.** Se comprobó de la peor
|
| 301 |
+
manera: la primera versión pedía el paquete `openai`, que no está instalado
|
| 302 |
+
en el Space, y el Space entero quedó en `status: error`. Ahora, si el
|
| 303 |
+
principal no se puede preparar, se cae a Groq; y si no hay ninguna clave, se
|
| 304 |
+
informa en `/health` en vez de morir en silencio.
|
| 305 |
"""
|
| 306 |
+
groq = None
|
| 307 |
+
if os.environ.get("GROQ_API_KEY"):
|
| 308 |
+
try:
|
| 309 |
+
groq = ChatGroq(temperature=0.15, model_name=GROQ_MODEL)
|
| 310 |
+
except Exception as e: # noqa: BLE001
|
| 311 |
+
print(f"⚠ No se pudo preparar Groq: {type(e).__name__}: {e}")
|
| 312 |
|
| 313 |
if DEEPSEEK_API_KEY:
|
| 314 |
+
try:
|
| 315 |
+
principal = _LLMDeepSeek(DEEPSEEK_MODEL)
|
| 316 |
+
except Exception as e: # noqa: BLE001
|
| 317 |
+
print(
|
| 318 |
+
f"⚠ No se pudo preparar DeepSeek ({type(e).__name__}: {e}); "
|
| 319 |
+
"se usa Groq"
|
| 320 |
)
|
| 321 |
+
principal = None
|
| 322 |
+
|
| 323 |
+
if principal is not None:
|
| 324 |
+
if groq is not None:
|
| 325 |
+
return (
|
| 326 |
+
_LLMConEmergencia(principal, groq, f"groq:{GROQ_MODEL}"),
|
| 327 |
+
f"deepseek:{DEEPSEEK_MODEL} (emergencia: groq:{GROQ_MODEL})",
|
| 328 |
+
)
|
| 329 |
+
return principal, f"deepseek:{DEEPSEEK_MODEL}"
|
| 330 |
|
| 331 |
+
if groq is not None:
|
| 332 |
+
return groq, f"groq:{GROQ_MODEL}"
|
| 333 |
|
| 334 |
return None, "ninguno (faltan DEEPSEEK_API_KEY y GROQ_API_KEY)"
|
| 335 |
|
|
|
|
| 371 |
try:
|
| 372 |
llm, retriever, LLM_ACTIVO = load_rag()
|
| 373 |
except Exception as e: # noqa: BLE001
|
| 374 |
+
LLM_ACTIVO = f"error al inicializar: {type(e).__name__}: {str(e)[:200]}"
|
| 375 |
print(f"❌ Error CRÍTICO al inicializar: {type(e).__name__}: {e}")
|
| 376 |
|
| 377 |
|