Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,6 +1,8 @@
|
|
| 1 |
"""
|
| 2 |
-
main.py — Fer Private AI · API REST
|
| 3 |
mx-data-api Space · Puerto 7860
|
|
|
|
|
|
|
| 4 |
"""
|
| 5 |
import os, requests, time
|
| 6 |
from datetime import datetime
|
|
@@ -8,7 +10,7 @@ from fastapi import FastAPI, HTTPException
|
|
| 8 |
from fastapi.middleware.cors import CORSMiddleware
|
| 9 |
from pydantic import BaseModel
|
| 10 |
|
| 11 |
-
app = FastAPI(title="Fer Private AI · API", version="
|
| 12 |
|
| 13 |
app.add_middleware(
|
| 14 |
CORSMiddleware,
|
|
@@ -17,52 +19,57 @@ app.add_middleware(
|
|
| 17 |
allow_headers=["*"],
|
| 18 |
)
|
| 19 |
|
| 20 |
-
NVIDIA_API_KEY
|
| 21 |
-
BANXICO_TOKEN
|
| 22 |
-
GROQ_API_KEY
|
| 23 |
-
TAVILY_API_KEY
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
BANXICO_SERIES = {
|
| 28 |
"SF43718": "Tipo de cambio USD/MXN (FIX)",
|
| 29 |
"SF46410": "TIIE 28 días (%)",
|
| 30 |
"SF61745": "Tasa objetivo Banxico (%)",
|
| 31 |
-
"SP74625": "Inflación general (índice)",
|
| 32 |
"SF290383": "Reservas internacionales (MDD)",
|
| 33 |
-
"SF43718": "Tipo de cambio USD/MXN (FIX)",
|
| 34 |
-
"SF60653": "INPC (Índice Nacional Precios Consumidor)",
|
| 35 |
"SF43784": "Tipo de cambio EUR/MXN",
|
| 36 |
}
|
| 37 |
|
| 38 |
WB_INDICATORS = {
|
| 39 |
-
"NY.GDP.MKTP.CD":
|
| 40 |
-
"NY.GDP.PCAP.CD":
|
| 41 |
-
"FP.CPI.TOTL.ZG":
|
| 42 |
-
"SL.UEM.TOTL.ZS":
|
| 43 |
-
"NE.EXP.GNFS.ZS":
|
| 44 |
-
"BX.KLT.DINV.WD.GD.ZS": "
|
| 45 |
}
|
| 46 |
|
|
|
|
|
|
|
|
|
|
| 47 |
class ChatRequest(BaseModel):
|
| 48 |
query: str
|
| 49 |
session_id: str = "mobile"
|
| 50 |
|
| 51 |
-
# ──
|
| 52 |
-
def
|
| 53 |
-
url = f"https://www.banxico.org.mx/SieAPIRest/service/v1/series/{serie_id}/datos/oportuno?token={BANXICO_TOKEN}"
|
| 54 |
try:
|
|
|
|
| 55 |
r = requests.get(url, timeout=15)
|
| 56 |
r.raise_for_status()
|
| 57 |
data = r.json()
|
| 58 |
series = data.get("bmx", {}).get("series", [])
|
| 59 |
-
if not series: return {
|
| 60 |
datos = series[0].get("datos", [])
|
| 61 |
-
if not datos: return {
|
| 62 |
ultimo = datos[-1]
|
| 63 |
return {"valor": ultimo.get("dato"), "fecha": ultimo.get("fecha")}
|
| 64 |
except:
|
| 65 |
-
return {
|
| 66 |
|
| 67 |
def fetch_worldbank(indicator: str) -> dict:
|
| 68 |
try:
|
|
@@ -74,246 +81,201 @@ def fetch_worldbank(indicator: str) -> dict:
|
|
| 74 |
return {"valor": entry.get("value"), "año": entry.get("date")}
|
| 75 |
except:
|
| 76 |
pass
|
| 77 |
-
return {
|
| 78 |
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
data = r.json()
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
timeout=10
|
| 117 |
-
)
|
| 118 |
-
if r.status_code == 200:
|
| 119 |
-
results = r.json().get("results", [])
|
| 120 |
-
snippets = []
|
| 121 |
-
for res in results[:3]:
|
| 122 |
-
title = res.get("title", "")
|
| 123 |
-
content = res.get("content", "")[:200]
|
| 124 |
-
snippets.append(f"• {title}: {content}")
|
| 125 |
-
return "\n".join(snippets)
|
| 126 |
-
except:
|
| 127 |
-
pass
|
| 128 |
-
return ""
|
| 129 |
-
|
| 130 |
-
def get_context_data(query: str) -> str:
|
| 131 |
-
"""Obtiene datos reales y construye contexto enriquecido para el LLM."""
|
| 132 |
-
lines = ["=== DATOS REALES EN TIEMPO REAL — MÉXICO ===\n"]
|
| 133 |
-
|
| 134 |
-
# Banxico
|
| 135 |
-
lines.append("--- BANXICO (datos oficiales hoy) ---")
|
| 136 |
-
banxico_data = {
|
| 137 |
-
"SF43718": "Tipo de cambio USD/MXN (FIX)",
|
| 138 |
-
"SF46410": "TIIE 28 días (%)",
|
| 139 |
-
"SF61745": "Tasa objetivo Banxico (%)",
|
| 140 |
-
"SP74625": "Inflación general (índice INPC)",
|
| 141 |
-
"SF290383": "Reservas internacionales (MDD)",
|
| 142 |
-
"SF43784": "Tipo de cambio EUR/MXN",
|
| 143 |
-
}
|
| 144 |
-
for serie_id, nombre in banxico_data.items():
|
| 145 |
-
d = fetch_banxico_serie(serie_id)
|
| 146 |
if d.get("valor"):
|
| 147 |
-
|
| 148 |
|
| 149 |
-
# World Bank
|
| 150 |
-
lines.append("\n--- WORLD BANK (datos macroeconómicos) ---")
|
| 151 |
wb_data = {
|
| 152 |
-
"NY.GDP.MKTP.CD":
|
| 153 |
-
"
|
| 154 |
-
"
|
| 155 |
-
"SL.UEM.TOTL.ZS": "Desempleo %",
|
| 156 |
-
"NE.EXP.GNFS.ZS": "Exportaciones % PIB",
|
| 157 |
-
"BX.KLT.DINV.WD.GD.ZS": "IED % PIB",
|
| 158 |
}
|
| 159 |
-
for
|
| 160 |
-
d = fetch_worldbank(
|
| 161 |
if d.get("valor"):
|
| 162 |
-
val = d[
|
| 163 |
-
if
|
| 164 |
val = f"${val/1e12:.2f} billones USD"
|
| 165 |
-
elif indicator == "NY.GDP.PCAP.CD":
|
| 166 |
-
val = f"${val:,.0f} USD"
|
| 167 |
else:
|
| 168 |
val = f"{val:.2f}%"
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
# IFT
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
q_lower = query.lower()
|
| 199 |
-
if any(w in q_lower for w in ["tiie", "tasa", "interés", "banxico"]):
|
| 200 |
-
wiki_queries.append("Banco de México política monetaria")
|
| 201 |
-
if any(w in q_lower for w in ["pib", "economía", "crecimiento"]):
|
| 202 |
-
wiki_queries.append("Economía de México")
|
| 203 |
-
if any(w in q_lower for w in ["telco", "telecomunicaciones", "telcel", "att", "movistar"]):
|
| 204 |
-
wiki_queries.append("Telecomunicaciones en México")
|
| 205 |
-
if any(w in q_lower for w in ["inflación", "inpc", "precios"]):
|
| 206 |
-
wiki_queries.append("Inflación en México")
|
| 207 |
-
|
| 208 |
-
for wq in wiki_queries[:1]: # máximo 1 búsqueda Wikipedia para no demorar
|
| 209 |
-
wiki_text = search_wikipedia(wq)
|
| 210 |
-
if wiki_text:
|
| 211 |
-
lines.append(f"\n--- WIKIPEDIA: {wq} ---")
|
| 212 |
-
lines.append(wiki_text[:500])
|
| 213 |
-
|
| 214 |
-
# Tavily para noticias recientes si la query lo requiere
|
| 215 |
-
if any(w in q_lower for w in ["hoy", "reciente", "última", "noticia", "2026", "actual"]):
|
| 216 |
-
tavily_text = search_tavily(query)
|
| 217 |
-
if tavily_text:
|
| 218 |
-
lines.append("\n--- NOTICIAS RECIENTES (Tavily) ---")
|
| 219 |
-
lines.append(tavily_text)
|
| 220 |
-
|
| 221 |
-
lines.append("\n=== FIN DE DATOS REALES ===")
|
| 222 |
-
return "\n".join(lines)
|
| 223 |
-
|
| 224 |
-
def call_llm(prompt: str) -> dict:
|
| 225 |
-
context = get_context_data(prompt)
|
| 226 |
-
|
| 227 |
-
system_prompt = f"""Eres un experto en economía mexicana y telecomunicaciones de México.
|
| 228 |
-
Tienes acceso a los siguientes datos REALES obtenidos ahora mismo de fuentes oficiales (Banxico, World Bank, IFT, Wikipedia):
|
| 229 |
-
|
| 230 |
-
{context}
|
| 231 |
-
|
| 232 |
-
REGLAS CRÍTICAS:
|
| 233 |
-
1. SIEMPRE usa los datos reales de arriba — NUNCA digas "no tengo acceso a datos en tiempo real"
|
| 234 |
-
2. Para TIIE, USD/MXN, tasas, reservas → usa exactamente los valores de Banxico de arriba
|
| 235 |
-
3. Para PIB, inflación, desempleo → usa los datos de World Bank de arriba
|
| 236 |
-
4. Para telecomunicaciones → usa los datos IFT de arriba
|
| 237 |
-
5. Responde en español, de forma clara y directa
|
| 238 |
-
6. Formatea números grandes de forma legible: $1.86 billones USD en vez de 1856365616165.94
|
| 239 |
-
7. Cita la fuente al final: (Fuente: Banxico / World Bank / IFT)
|
| 240 |
-
8. Si el dato no está disponible, dilo claramente — NUNCA inventes datos"""
|
| 241 |
-
|
| 242 |
-
# Groq LPU primero
|
| 243 |
if GROQ_API_KEY:
|
| 244 |
try:
|
| 245 |
start = time.time()
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
"
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
|
|
|
|
|
|
|
|
|
| 257 |
r.raise_for_status()
|
| 258 |
data = r.json()
|
| 259 |
-
latencia = int((time.time() - start) * 1000)
|
| 260 |
return {
|
| 261 |
-
"
|
| 262 |
-
"modelo":
|
| 263 |
-
"latencia_ms":
|
| 264 |
}
|
| 265 |
-
except
|
| 266 |
pass
|
| 267 |
|
| 268 |
# Fallback NVIDIA NIM
|
| 269 |
try:
|
| 270 |
start = time.time()
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
"
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
|
|
|
|
|
|
|
|
|
| 282 |
r.raise_for_status()
|
| 283 |
data = r.json()
|
| 284 |
-
latencia = int((time.time() - start) * 1000)
|
| 285 |
return {
|
| 286 |
-
"
|
| 287 |
-
"modelo":
|
| 288 |
-
"latencia_ms":
|
| 289 |
}
|
| 290 |
except Exception as e:
|
| 291 |
-
return {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
|
| 293 |
# ── Endpoints ─────────────────────────────────────────────────────────────────
|
|
|
|
| 294 |
@app.get("/")
|
| 295 |
def root():
|
| 296 |
return {
|
| 297 |
-
"name":
|
| 298 |
-
"version":
|
| 299 |
-
"status":
|
|
|
|
| 300 |
"endpoints": ["/health", "/indicadores", "/telco", "/worldbank", "/chat"],
|
| 301 |
-
"compute":
|
| 302 |
-
"tools": ["Banxico SIE", "World Bank", "IFT", "Wikipedia ES/EN", "Tavily"],
|
| 303 |
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 304 |
}
|
| 305 |
|
| 306 |
@app.get("/health")
|
| 307 |
def health():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 308 |
return {
|
| 309 |
-
"status":
|
| 310 |
-
"
|
|
|
|
|
|
|
| 311 |
"secrets": {
|
| 312 |
-
"NVIDIA_API_KEY":
|
| 313 |
-
"BANXICO_TOKEN":
|
| 314 |
-
"GROQ_API_KEY":
|
| 315 |
-
"
|
| 316 |
-
}
|
| 317 |
}
|
| 318 |
|
| 319 |
@app.get("/indicadores")
|
|
@@ -321,58 +283,44 @@ def indicadores():
|
|
| 321 |
if not BANXICO_TOKEN:
|
| 322 |
raise HTTPException(status_code=503, detail="BANXICO_TOKEN no configurado")
|
| 323 |
resultados = {}
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
"
|
| 327 |
-
"SF61745": "Tasa objetivo Banxico (%)",
|
| 328 |
-
"SP74625": "Inflación general (índice)",
|
| 329 |
-
"SF290383": "Reservas internacionales (MDD)",
|
| 330 |
-
}
|
| 331 |
-
for serie_id, nombre in series.items():
|
| 332 |
-
d = fetch_banxico_serie(serie_id)
|
| 333 |
-
resultados[serie_id] = {"nombre": nombre, "valor": d["valor"], "fecha": d["fecha"]}
|
| 334 |
return {
|
| 335 |
-
"fuente":
|
| 336 |
-
"timestamp":
|
| 337 |
"indicadores": resultados,
|
| 338 |
}
|
| 339 |
|
| 340 |
@app.get("/telco")
|
| 341 |
def telco():
|
| 342 |
return {
|
| 343 |
-
"fuente":
|
| 344 |
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 345 |
"mercado_movil": {
|
| 346 |
"total_lineas_millones": 127.4,
|
| 347 |
"periodo": "Q3 2024",
|
| 348 |
"operadores": [
|
| 349 |
-
{"operador": "Telcel",
|
| 350 |
{"operador": "AT&T México", "participacion_pct": 17.5},
|
| 351 |
-
{"operador": "Movistar",
|
| 352 |
{"operador": "Otros MVNOs", "participacion_pct": 2.1},
|
| 353 |
]
|
| 354 |
},
|
| 355 |
"ingresos_q1_2025_millones_mxn": 148541.1,
|
| 356 |
-
"cobertura_4g_pct_poblacion":
|
| 357 |
-
"penetracion_5g_pct":
|
| 358 |
}
|
| 359 |
|
| 360 |
@app.get("/worldbank")
|
| 361 |
def worldbank():
|
| 362 |
-
wb_data = {
|
| 363 |
-
"NY.GDP.MKTP.CD": "PIB México (USD)",
|
| 364 |
-
"NY.GDP.PCAP.CD": "PIB per cápita (USD)",
|
| 365 |
-
"FP.CPI.TOTL.ZG": "Inflación anual (%)",
|
| 366 |
-
"SL.UEM.TOTL.ZS": "Desempleo (%)",
|
| 367 |
-
"NE.EXP.GNFS.ZS": "Exportaciones (% PIB)",
|
| 368 |
-
}
|
| 369 |
resultados = {}
|
| 370 |
-
for indicator, nombre in
|
| 371 |
d = fetch_worldbank(indicator)
|
| 372 |
-
resultados[indicator] = {"nombre": nombre, "valor": d
|
| 373 |
return {
|
| 374 |
-
"fuente":
|
| 375 |
-
"timestamp":
|
| 376 |
"indicadores": resultados,
|
| 377 |
}
|
| 378 |
|
|
@@ -380,12 +328,14 @@ def worldbank():
|
|
| 380 |
def chat(req: ChatRequest):
|
| 381 |
if not req.query.strip():
|
| 382 |
raise HTTPException(status_code=400, detail="Query vacía")
|
| 383 |
-
|
|
|
|
|
|
|
| 384 |
return {
|
| 385 |
-
"query":
|
| 386 |
-
"response":
|
| 387 |
-
"modelo":
|
| 388 |
-
"latencia_ms":
|
| 389 |
-
"timestamp":
|
| 390 |
"infraestructura": "Fer Private AI · datos nunca salen de infraestructura privada",
|
| 391 |
}
|
|
|
|
| 1 |
"""
|
| 2 |
+
main.py — Fer Private AI · API REST v4.0
|
| 3 |
mx-data-api Space · Puerto 7860
|
| 4 |
+
v4: /chat llama al agente real en mx-data-intelligence via INTERNAL_API_KEY
|
| 5 |
+
Fallback a respuesta básica si el agente no está disponible
|
| 6 |
"""
|
| 7 |
import os, requests, time
|
| 8 |
from datetime import datetime
|
|
|
|
| 10 |
from fastapi.middleware.cors import CORSMiddleware
|
| 11 |
from pydantic import BaseModel
|
| 12 |
|
| 13 |
+
app = FastAPI(title="Fer Private AI · API", version="4.0.0")
|
| 14 |
|
| 15 |
app.add_middleware(
|
| 16 |
CORSMiddleware,
|
|
|
|
| 19 |
allow_headers=["*"],
|
| 20 |
)
|
| 21 |
|
| 22 |
+
NVIDIA_API_KEY = os.getenv("NVIDIA_API_KEY", "")
|
| 23 |
+
BANXICO_TOKEN = os.getenv("BANXICO_TOKEN", "")
|
| 24 |
+
GROQ_API_KEY = os.getenv("GROQ_API_KEY", "")
|
| 25 |
+
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY", "")
|
| 26 |
+
INTERNAL_API_KEY = os.getenv("INTERNAL_API_KEY", "")
|
| 27 |
+
|
| 28 |
+
# URL del agente real — Space mx-data-intelligence puerto interno 8099
|
| 29 |
+
# HF permite comunicación entre containers del mismo usuario via localhost
|
| 30 |
+
# cuando ambos Spaces corren en la misma región
|
| 31 |
+
AGENT_URL = "http://fercor95mx-mx-data-intelligence.hf.space:8099"
|
| 32 |
|
| 33 |
BANXICO_SERIES = {
|
| 34 |
"SF43718": "Tipo de cambio USD/MXN (FIX)",
|
| 35 |
"SF46410": "TIIE 28 días (%)",
|
| 36 |
"SF61745": "Tasa objetivo Banxico (%)",
|
| 37 |
+
"SP74625": "Inflación general (índice INPC)",
|
| 38 |
"SF290383": "Reservas internacionales (MDD)",
|
|
|
|
|
|
|
| 39 |
"SF43784": "Tipo de cambio EUR/MXN",
|
| 40 |
}
|
| 41 |
|
| 42 |
WB_INDICATORS = {
|
| 43 |
+
"NY.GDP.MKTP.CD": "PIB México (USD)",
|
| 44 |
+
"NY.GDP.PCAP.CD": "PIB per cápita (USD)",
|
| 45 |
+
"FP.CPI.TOTL.ZG": "Inflación anual (%)",
|
| 46 |
+
"SL.UEM.TOTL.ZS": "Desempleo (%)",
|
| 47 |
+
"NE.EXP.GNFS.ZS": "Exportaciones (% PIB)",
|
| 48 |
+
"BX.KLT.DINV.WD.GD.ZS": "IED (% PIB)",
|
| 49 |
}
|
| 50 |
|
| 51 |
+
GROQ_BASE_URL = "https://api.groq.com/openai/v1"
|
| 52 |
+
NVIDIA_BASE_URL = "https://integrate.api.nvidia.com/v1"
|
| 53 |
+
|
| 54 |
class ChatRequest(BaseModel):
|
| 55 |
query: str
|
| 56 |
session_id: str = "mobile"
|
| 57 |
|
| 58 |
+
# ── Fetchers de datos reales ──────────────────────────────────────────────────
|
| 59 |
+
def fetch_banxico(serie_id: str) -> dict:
|
|
|
|
| 60 |
try:
|
| 61 |
+
url = f"https://www.banxico.org.mx/SieAPIRest/service/v1/series/{serie_id}/datos/oportuno?token={BANXICO_TOKEN}"
|
| 62 |
r = requests.get(url, timeout=15)
|
| 63 |
r.raise_for_status()
|
| 64 |
data = r.json()
|
| 65 |
series = data.get("bmx", {}).get("series", [])
|
| 66 |
+
if not series: return {}
|
| 67 |
datos = series[0].get("datos", [])
|
| 68 |
+
if not datos: return {}
|
| 69 |
ultimo = datos[-1]
|
| 70 |
return {"valor": ultimo.get("dato"), "fecha": ultimo.get("fecha")}
|
| 71 |
except:
|
| 72 |
+
return {}
|
| 73 |
|
| 74 |
def fetch_worldbank(indicator: str) -> dict:
|
| 75 |
try:
|
|
|
|
| 81 |
return {"valor": entry.get("value"), "año": entry.get("date")}
|
| 82 |
except:
|
| 83 |
pass
|
| 84 |
+
return {}
|
| 85 |
|
| 86 |
+
# ── Llamada al agente real ────────────────────────────────────────────────────
|
| 87 |
+
def call_real_agent(query: str, session_id: str = "mobile") -> dict:
|
| 88 |
+
"""
|
| 89 |
+
Llama al agent_orchestrator.py real en mx-data-intelligence puerto 8099.
|
| 90 |
+
Usa INTERNAL_API_KEY para autenticación.
|
| 91 |
+
Si falla → fallback a respuesta básica con datos reales de Banxico.
|
| 92 |
+
"""
|
| 93 |
+
if INTERNAL_API_KEY:
|
| 94 |
+
try:
|
| 95 |
+
start = time.time()
|
| 96 |
+
headers = {
|
| 97 |
+
"Content-Type": "application/json",
|
| 98 |
+
"x-api-key": INTERNAL_API_KEY,
|
| 99 |
+
}
|
| 100 |
+
payload = {
|
| 101 |
+
"query": query,
|
| 102 |
+
"session_id": session_id,
|
| 103 |
+
"history": [],
|
| 104 |
+
}
|
| 105 |
+
r = requests.post(
|
| 106 |
+
f"{AGENT_URL}/agent/query",
|
| 107 |
+
headers=headers,
|
| 108 |
+
json=payload,
|
| 109 |
+
timeout=120,
|
| 110 |
+
)
|
| 111 |
+
r.raise_for_status()
|
| 112 |
data = r.json()
|
| 113 |
+
latencia = int((time.time() - start) * 1000)
|
| 114 |
+
return {
|
| 115 |
+
"response": data.get("response", "Sin respuesta"),
|
| 116 |
+
"modelo": "Agente Real · 7 tools · NVIDIA H100 + Groq LPU",
|
| 117 |
+
"latencia_ms": latencia,
|
| 118 |
+
}
|
| 119 |
+
except Exception as e:
|
| 120 |
+
# Agente no disponible — fallback a LLM básico con datos reales
|
| 121 |
+
pass
|
| 122 |
|
| 123 |
+
# ── Fallback: datos reales + LLM básico ──────────────────────────────────
|
| 124 |
+
return call_llm_fallback(query)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def call_llm_fallback(query: str) -> dict:
|
| 128 |
+
"""
|
| 129 |
+
Fallback cuando el agente real no está disponible.
|
| 130 |
+
Jala datos reales de Banxico/WB y los pasa al LLM.
|
| 131 |
+
"""
|
| 132 |
+
# Construir contexto con datos reales
|
| 133 |
+
facts = []
|
| 134 |
+
for serie_id, nombre in BANXICO_SERIES.items():
|
| 135 |
+
d = fetch_banxico(serie_id)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
if d.get("valor"):
|
| 137 |
+
facts.append(f"• {nombre}: {d['valor']} ({d['fecha']}) — Fuente: Banxico")
|
| 138 |
|
|
|
|
|
|
|
| 139 |
wb_data = {
|
| 140 |
+
"NY.GDP.MKTP.CD": "PIB México",
|
| 141 |
+
"FP.CPI.TOTL.ZG": "Inflación anual %",
|
| 142 |
+
"SL.UEM.TOTL.ZS": "Desempleo %",
|
|
|
|
|
|
|
|
|
|
| 143 |
}
|
| 144 |
+
for ind, nombre in wb_data.items():
|
| 145 |
+
d = fetch_worldbank(ind)
|
| 146 |
if d.get("valor"):
|
| 147 |
+
val = d["valor"]
|
| 148 |
+
if ind == "NY.GDP.MKTP.CD":
|
| 149 |
val = f"${val/1e12:.2f} billones USD"
|
|
|
|
|
|
|
| 150 |
else:
|
| 151 |
val = f"{val:.2f}%"
|
| 152 |
+
facts.append(f"• {nombre}: {val} ({d.get('año','')}) — Fuente: World Bank")
|
| 153 |
+
|
| 154 |
+
# IFT hardcodeado verificado
|
| 155 |
+
facts += [
|
| 156 |
+
"• Telcel: 63.4% participación mercado móvil — Fuente: IFT Q3 2024",
|
| 157 |
+
"• AT&T México: 17.5% — Fuente: IFT Q3 2024",
|
| 158 |
+
"• Movistar: 17.0% — Fuente: IFT Q3 2024",
|
| 159 |
+
"• Ingresos sector telco Q1 2025: 148,541 M MXN — Fuente: IFT",
|
| 160 |
+
"• Portabilidad H1 2025: Bait +244,024 / AT&T -752,664 — Fuente: IFT",
|
| 161 |
+
]
|
| 162 |
+
|
| 163 |
+
facts_str = "\n".join(facts)
|
| 164 |
+
|
| 165 |
+
system = """Eres un experto en economía mexicana.
|
| 166 |
+
REGLAS:
|
| 167 |
+
1. USA ÚNICAMENTE los DATOS VERIFICADOS que aparecen abajo
|
| 168 |
+
2. NUNCA digas 'no tengo acceso a datos en tiempo real' — los datos ya están aquí
|
| 169 |
+
3. NUNCA inventes cifras — si no está en los datos, di 'dato no disponible'
|
| 170 |
+
4. Responde en español, tono ejecutivo
|
| 171 |
+
5. Cita la fuente de cada dato"""
|
| 172 |
+
|
| 173 |
+
user = f"""DATOS VERIFICADOS EN TIEMPO REAL:
|
| 174 |
+
{facts_str}
|
| 175 |
+
|
| 176 |
+
PREGUNTA: {query}
|
| 177 |
+
|
| 178 |
+
Responde usando ÚNICAMENTE los datos de arriba."""
|
| 179 |
+
|
| 180 |
+
# Groq primero
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
if GROQ_API_KEY:
|
| 182 |
try:
|
| 183 |
start = time.time()
|
| 184 |
+
r = requests.post(
|
| 185 |
+
f"{GROQ_BASE_URL}/chat/completions",
|
| 186 |
+
headers={"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"},
|
| 187 |
+
json={
|
| 188 |
+
"model": "llama-3.3-70b-versatile",
|
| 189 |
+
"messages": [
|
| 190 |
+
{"role": "system", "content": system},
|
| 191 |
+
{"role": "user", "content": user}
|
| 192 |
+
],
|
| 193 |
+
"max_tokens": 1200,
|
| 194 |
+
"temperature": 0.1,
|
| 195 |
+
},
|
| 196 |
+
timeout=20
|
| 197 |
+
)
|
| 198 |
r.raise_for_status()
|
| 199 |
data = r.json()
|
|
|
|
| 200 |
return {
|
| 201 |
+
"response": data["choices"][0]["message"]["content"],
|
| 202 |
+
"modelo": "Llama 3.3 70B · Groq LPU (fallback)",
|
| 203 |
+
"latencia_ms": int((time.time() - start) * 1000),
|
| 204 |
}
|
| 205 |
+
except:
|
| 206 |
pass
|
| 207 |
|
| 208 |
# Fallback NVIDIA NIM
|
| 209 |
try:
|
| 210 |
start = time.time()
|
| 211 |
+
r = requests.post(
|
| 212 |
+
f"{NVIDIA_BASE_URL}/chat/completions",
|
| 213 |
+
headers={"Authorization": f"Bearer {NVIDIA_API_KEY}", "Content-Type": "application/json"},
|
| 214 |
+
json={
|
| 215 |
+
"model": "meta/llama-3.1-70b-instruct",
|
| 216 |
+
"messages": [
|
| 217 |
+
{"role": "system", "content": system},
|
| 218 |
+
{"role": "user", "content": user}
|
| 219 |
+
],
|
| 220 |
+
"max_tokens": 1200,
|
| 221 |
+
"temperature": 0.1,
|
| 222 |
+
},
|
| 223 |
+
timeout=45
|
| 224 |
+
)
|
| 225 |
r.raise_for_status()
|
| 226 |
data = r.json()
|
|
|
|
| 227 |
return {
|
| 228 |
+
"response": data["choices"][0]["message"]["content"],
|
| 229 |
+
"modelo": "LLaMA 3.1 70B · NVIDIA H100 (fallback)",
|
| 230 |
+
"latencia_ms": int((time.time() - start) * 1000),
|
| 231 |
}
|
| 232 |
except Exception as e:
|
| 233 |
+
return {
|
| 234 |
+
"response": f"Error de inferencia: {e}",
|
| 235 |
+
"modelo": "error",
|
| 236 |
+
"latencia_ms": 0,
|
| 237 |
+
}
|
| 238 |
|
| 239 |
# ── Endpoints ─────────────────────────────────────────────────────────────────
|
| 240 |
+
|
| 241 |
@app.get("/")
|
| 242 |
def root():
|
| 243 |
return {
|
| 244 |
+
"name": "Fer Private AI · API",
|
| 245 |
+
"version": "4.0.0",
|
| 246 |
+
"status": "ok",
|
| 247 |
+
"novedad": "v4 — /chat usa agente real con 7 tools y 15 reglas anti-alucinación",
|
| 248 |
"endpoints": ["/health", "/indicadores", "/telco", "/worldbank", "/chat"],
|
| 249 |
+
"compute": "NVIDIA H100 · NIM + Groq LPU",
|
|
|
|
| 250 |
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 251 |
}
|
| 252 |
|
| 253 |
@app.get("/health")
|
| 254 |
def health():
|
| 255 |
+
agent_status = "❌ no disponible"
|
| 256 |
+
if INTERNAL_API_KEY:
|
| 257 |
+
try:
|
| 258 |
+
r = requests.get(
|
| 259 |
+
f"{AGENT_URL}/agent/health",
|
| 260 |
+
headers={"x-api-key": INTERNAL_API_KEY},
|
| 261 |
+
timeout=10
|
| 262 |
+
)
|
| 263 |
+
if r.status_code == 200:
|
| 264 |
+
agent_status = "✅ conectado"
|
| 265 |
+
except:
|
| 266 |
+
agent_status = "⚠️ no alcanzable"
|
| 267 |
+
|
| 268 |
return {
|
| 269 |
+
"status": "ok",
|
| 270 |
+
"version": "4.0.0",
|
| 271 |
+
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 272 |
+
"agente_real": agent_status,
|
| 273 |
"secrets": {
|
| 274 |
+
"NVIDIA_API_KEY": "✅" if NVIDIA_API_KEY else "❌",
|
| 275 |
+
"BANXICO_TOKEN": "✅" if BANXICO_TOKEN else "❌",
|
| 276 |
+
"GROQ_API_KEY": "✅" if GROQ_API_KEY else "❌",
|
| 277 |
+
"INTERNAL_API_KEY": "✅" if INTERNAL_API_KEY else "❌",
|
| 278 |
+
},
|
| 279 |
}
|
| 280 |
|
| 281 |
@app.get("/indicadores")
|
|
|
|
| 283 |
if not BANXICO_TOKEN:
|
| 284 |
raise HTTPException(status_code=503, detail="BANXICO_TOKEN no configurado")
|
| 285 |
resultados = {}
|
| 286 |
+
for serie_id, nombre in BANXICO_SERIES.items():
|
| 287 |
+
d = fetch_banxico(serie_id)
|
| 288 |
+
resultados[serie_id] = {"nombre": nombre, "valor": d.get("valor"), "fecha": d.get("fecha")}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 289 |
return {
|
| 290 |
+
"fuente": "Banxico SIE API",
|
| 291 |
+
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 292 |
"indicadores": resultados,
|
| 293 |
}
|
| 294 |
|
| 295 |
@app.get("/telco")
|
| 296 |
def telco():
|
| 297 |
return {
|
| 298 |
+
"fuente": "IFT · ATDT",
|
| 299 |
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 300 |
"mercado_movil": {
|
| 301 |
"total_lineas_millones": 127.4,
|
| 302 |
"periodo": "Q3 2024",
|
| 303 |
"operadores": [
|
| 304 |
+
{"operador": "Telcel", "participacion_pct": 63.4},
|
| 305 |
{"operador": "AT&T México", "participacion_pct": 17.5},
|
| 306 |
+
{"operador": "Movistar", "participacion_pct": 17.0},
|
| 307 |
{"operador": "Otros MVNOs", "participacion_pct": 2.1},
|
| 308 |
]
|
| 309 |
},
|
| 310 |
"ingresos_q1_2025_millones_mxn": 148541.1,
|
| 311 |
+
"cobertura_4g_pct_poblacion": 92.0,
|
| 312 |
+
"penetracion_5g_pct": 3.5,
|
| 313 |
}
|
| 314 |
|
| 315 |
@app.get("/worldbank")
|
| 316 |
def worldbank():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 317 |
resultados = {}
|
| 318 |
+
for indicator, nombre in WB_INDICATORS.items():
|
| 319 |
d = fetch_worldbank(indicator)
|
| 320 |
+
resultados[indicator] = {"nombre": nombre, "valor": d.get("valor"), "año": d.get("año")}
|
| 321 |
return {
|
| 322 |
+
"fuente": "World Bank API",
|
| 323 |
+
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 324 |
"indicadores": resultados,
|
| 325 |
}
|
| 326 |
|
|
|
|
| 328 |
def chat(req: ChatRequest):
|
| 329 |
if not req.query.strip():
|
| 330 |
raise HTTPException(status_code=400, detail="Query vacía")
|
| 331 |
+
|
| 332 |
+
result = call_real_agent(req.query, req.session_id)
|
| 333 |
+
|
| 334 |
return {
|
| 335 |
+
"query": req.query,
|
| 336 |
+
"response": result.get("response", ""),
|
| 337 |
+
"modelo": result.get("modelo", ""),
|
| 338 |
+
"latencia_ms": result.get("latencia_ms", 0),
|
| 339 |
+
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 340 |
"infraestructura": "Fer Private AI · datos nunca salen de infraestructura privada",
|
| 341 |
}
|