Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -20,6 +20,7 @@ app.add_middleware(
|
|
| 20 |
NVIDIA_API_KEY = os.getenv("NVIDIA_API_KEY", "")
|
| 21 |
BANXICO_TOKEN = os.getenv("BANXICO_TOKEN", "")
|
| 22 |
GROQ_API_KEY = os.getenv("GROQ_API_KEY", "")
|
|
|
|
| 23 |
NVIDIA_BASE_URL = "https://integrate.api.nvidia.com/v1"
|
| 24 |
GROQ_BASE_URL = "https://api.groq.com/openai/v1"
|
| 25 |
|
|
@@ -29,20 +30,25 @@ BANXICO_SERIES = {
|
|
| 29 |
"SF61745": "Tasa objetivo Banxico (%)",
|
| 30 |
"SP74625": "Inflación general (índice)",
|
| 31 |
"SF290383": "Reservas internacionales (MDD)",
|
|
|
|
|
|
|
|
|
|
| 32 |
}
|
| 33 |
|
| 34 |
WB_INDICATORS = {
|
| 35 |
-
"NY.GDP.MKTP.CD":
|
| 36 |
-
"
|
| 37 |
-
"
|
|
|
|
|
|
|
|
|
|
| 38 |
}
|
| 39 |
|
| 40 |
-
# ── Models ────────────────────────────────────────────────────────────────────
|
| 41 |
class ChatRequest(BaseModel):
|
| 42 |
query: str
|
| 43 |
session_id: str = "mobile"
|
| 44 |
|
| 45 |
-
# ──
|
| 46 |
def fetch_banxico_serie(serie_id: str) -> dict:
|
| 47 |
url = f"https://www.banxico.org.mx/SieAPIRest/service/v1/series/{serie_id}/datos/oportuno?token={BANXICO_TOKEN}"
|
| 48 |
try:
|
|
@@ -50,20 +56,13 @@ def fetch_banxico_serie(serie_id: str) -> dict:
|
|
| 50 |
r.raise_for_status()
|
| 51 |
data = r.json()
|
| 52 |
series = data.get("bmx", {}).get("series", [])
|
| 53 |
-
if not series:
|
| 54 |
-
return {"serie": serie_id, "nombre": BANXICO_SERIES.get(serie_id), "valor": None, "fecha": None}
|
| 55 |
datos = series[0].get("datos", [])
|
| 56 |
-
if not datos:
|
| 57 |
-
return {"serie": serie_id, "nombre": BANXICO_SERIES.get(serie_id), "valor": None, "fecha": None}
|
| 58 |
ultimo = datos[-1]
|
| 59 |
-
return {
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
"valor": ultimo.get("dato"),
|
| 63 |
-
"fecha": ultimo.get("fecha"),
|
| 64 |
-
}
|
| 65 |
-
except Exception as e:
|
| 66 |
-
return {"serie": serie_id, "error": str(e)}
|
| 67 |
|
| 68 |
def fetch_worldbank(indicator: str) -> dict:
|
| 69 |
try:
|
|
@@ -72,88 +71,189 @@ def fetch_worldbank(indicator: str) -> dict:
|
|
| 72 |
data = r.json()
|
| 73 |
if len(data) > 1 and data[1]:
|
| 74 |
entry = data[1][0]
|
| 75 |
-
return {
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
}
|
| 80 |
-
except Exception as e:
|
| 81 |
-
return {"nombre": WB_INDICATORS.get(indicator), "error": str(e)}
|
| 82 |
-
return {}
|
| 83 |
|
| 84 |
-
def
|
| 85 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
lines = ["=== DATOS REALES EN TIEMPO REAL — MÉXICO ===\n"]
|
| 87 |
|
| 88 |
# Banxico
|
| 89 |
lines.append("--- BANXICO (datos oficiales hoy) ---")
|
| 90 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
d = fetch_banxico_serie(serie_id)
|
| 92 |
if d.get("valor"):
|
| 93 |
-
lines.append(f"• {
|
| 94 |
-
else:
|
| 95 |
-
lines.append(f"• {d['nombre']}: no disponible")
|
| 96 |
|
| 97 |
# World Bank
|
| 98 |
-
lines.append("\n--- WORLD BANK (datos
|
| 99 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
d = fetch_worldbank(indicator)
|
| 101 |
if d.get("valor"):
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
|
| 106 |
-
# IFT Telco
|
| 107 |
lines.append("\n--- IFT TELECOMUNICACIONES (Q1 2025 verificado) ---")
|
| 108 |
lines.append("• Ingresos sector telco Q1 2025: 148,541 millones MXN")
|
| 109 |
lines.append("• Total líneas móviles: 127.4 millones (Q3 2024)")
|
| 110 |
lines.append("• Telcel (América Móvil): 63.4% participación")
|
| 111 |
lines.append("• AT&T México: 17.5% participación")
|
| 112 |
-
lines.append("• Movistar (Telefónica): 17.0%
|
| 113 |
-
lines.append("• Otros MVNOs: 2.1%")
|
| 114 |
lines.append("• Cobertura 4G LTE: 92% población")
|
| 115 |
-
lines.append("• Penetración 5G estimada: 3.5%")
|
| 116 |
lines.append("• Portabilidad H1 2025: Bait líder captación (+244,024), AT&T mayor pérdida (-752,664)")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
lines.append("\n=== FIN DE DATOS REALES ===")
|
| 119 |
return "\n".join(lines)
|
| 120 |
|
| 121 |
def call_llm(prompt: str) -> dict:
|
| 122 |
-
|
| 123 |
-
context = get_context_data()
|
| 124 |
|
| 125 |
system_prompt = f"""Eres un experto en economía mexicana y telecomunicaciones de México.
|
| 126 |
-
Tienes acceso a los siguientes datos REALES
|
| 127 |
|
| 128 |
{context}
|
| 129 |
|
| 130 |
REGLAS CRÍTICAS:
|
| 131 |
-
1. SIEMPRE usa los datos reales de arriba
|
| 132 |
-
2.
|
| 133 |
-
3.
|
| 134 |
-
4.
|
| 135 |
-
5.
|
| 136 |
-
6.
|
|
|
|
|
|
|
| 137 |
|
| 138 |
-
# Groq LPU primero
|
| 139 |
if GROQ_API_KEY:
|
| 140 |
try:
|
| 141 |
start = time.time()
|
| 142 |
-
headers = {
|
| 143 |
-
"Authorization": f"Bearer {GROQ_API_KEY}",
|
| 144 |
-
"Content-Type": "application/json"
|
| 145 |
-
}
|
| 146 |
payload = {
|
| 147 |
"model": "llama-3.3-70b-versatile",
|
| 148 |
"messages": [
|
| 149 |
{"role": "system", "content": system_prompt},
|
| 150 |
{"role": "user", "content": prompt}
|
| 151 |
],
|
| 152 |
-
"max_tokens":
|
| 153 |
"temperature": 0.2,
|
| 154 |
}
|
| 155 |
-
r = requests.post(f"{GROQ_BASE_URL}/chat/completions",
|
| 156 |
-
headers=headers, json=payload, timeout=20)
|
| 157 |
r.raise_for_status()
|
| 158 |
data = r.json()
|
| 159 |
latencia = int((time.time() - start) * 1000)
|
|
@@ -168,21 +268,17 @@ REGLAS CRÍTICAS:
|
|
| 168 |
# Fallback NVIDIA NIM
|
| 169 |
try:
|
| 170 |
start = time.time()
|
| 171 |
-
headers = {
|
| 172 |
-
"Authorization": f"Bearer {NVIDIA_API_KEY}",
|
| 173 |
-
"Content-Type": "application/json"
|
| 174 |
-
}
|
| 175 |
payload = {
|
| 176 |
"model": "meta/llama-3.1-70b-instruct",
|
| 177 |
"messages": [
|
| 178 |
{"role": "system", "content": system_prompt},
|
| 179 |
{"role": "user", "content": prompt}
|
| 180 |
],
|
| 181 |
-
"max_tokens":
|
| 182 |
"temperature": 0.2,
|
| 183 |
}
|
| 184 |
-
r = requests.post(f"{NVIDIA_BASE_URL}/chat/completions",
|
| 185 |
-
headers=headers, json=payload, timeout=45)
|
| 186 |
r.raise_for_status()
|
| 187 |
data = r.json()
|
| 188 |
latencia = int((time.time() - start) * 1000)
|
|
@@ -192,22 +288,18 @@ REGLAS CRÍTICAS:
|
|
| 192 |
"latencia_ms": latencia,
|
| 193 |
}
|
| 194 |
except Exception as e:
|
| 195 |
-
return {
|
| 196 |
-
"respuesta": f"Error de inferencia: {e}",
|
| 197 |
-
"modelo": "error",
|
| 198 |
-
"latencia_ms": 0,
|
| 199 |
-
}
|
| 200 |
|
| 201 |
# ── Endpoints ─────────────────────────────────────────────────────────────────
|
| 202 |
-
|
| 203 |
@app.get("/")
|
| 204 |
def root():
|
| 205 |
return {
|
| 206 |
"name": "Fer Private AI · API",
|
| 207 |
-
"version": "
|
| 208 |
"status": "ok",
|
| 209 |
"endpoints": ["/health", "/indicadores", "/telco", "/worldbank", "/chat"],
|
| 210 |
"compute": "NVIDIA H100 · NIM + Groq LPU",
|
|
|
|
| 211 |
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 212 |
}
|
| 213 |
|
|
@@ -216,11 +308,11 @@ def health():
|
|
| 216 |
return {
|
| 217 |
"status": "ok",
|
| 218 |
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 219 |
-
"compute": "NVIDIA H100 · NIM",
|
| 220 |
"secrets": {
|
| 221 |
"NVIDIA_API_KEY": "✅" if NVIDIA_API_KEY else "❌",
|
| 222 |
"BANXICO_TOKEN": "✅" if BANXICO_TOKEN else "❌",
|
| 223 |
"GROQ_API_KEY": "✅" if GROQ_API_KEY else "❌",
|
|
|
|
| 224 |
}
|
| 225 |
}
|
| 226 |
|
|
@@ -229,8 +321,16 @@ def indicadores():
|
|
| 229 |
if not BANXICO_TOKEN:
|
| 230 |
raise HTTPException(status_code=503, detail="BANXICO_TOKEN no configurado")
|
| 231 |
resultados = {}
|
| 232 |
-
|
| 233 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
return {
|
| 235 |
"fuente": "Banxico SIE API",
|
| 236 |
"timestamp": datetime.utcnow().isoformat() + "Z",
|
|
@@ -240,7 +340,7 @@ def indicadores():
|
|
| 240 |
@app.get("/telco")
|
| 241 |
def telco():
|
| 242 |
return {
|
| 243 |
-
"fuente": "IFT ·
|
| 244 |
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 245 |
"mercado_movil": {
|
| 246 |
"total_lineas_millones": 127.4,
|
|
@@ -259,9 +359,17 @@ def telco():
|
|
| 259 |
|
| 260 |
@app.get("/worldbank")
|
| 261 |
def worldbank():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 262 |
resultados = {}
|
| 263 |
-
for indicator, nombre in
|
| 264 |
-
|
|
|
|
| 265 |
return {
|
| 266 |
"fuente": "World Bank API",
|
| 267 |
"timestamp": datetime.utcnow().isoformat() + "Z",
|
|
|
|
| 20 |
NVIDIA_API_KEY = os.getenv("NVIDIA_API_KEY", "")
|
| 21 |
BANXICO_TOKEN = os.getenv("BANXICO_TOKEN", "")
|
| 22 |
GROQ_API_KEY = os.getenv("GROQ_API_KEY", "")
|
| 23 |
+
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY", "")
|
| 24 |
NVIDIA_BASE_URL = "https://integrate.api.nvidia.com/v1"
|
| 25 |
GROQ_BASE_URL = "https://api.groq.com/openai/v1"
|
| 26 |
|
|
|
|
| 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": "PIB México (USD)",
|
| 40 |
+
"NY.GDP.PCAP.CD": "PIB per cápita (USD)",
|
| 41 |
+
"FP.CPI.TOTL.ZG": "Inflación anual (%)",
|
| 42 |
+
"SL.UEM.TOTL.ZS": "Desempleo (%)",
|
| 43 |
+
"NE.EXP.GNFS.ZS": "Exportaciones (% PIB)",
|
| 44 |
+
"BX.KLT.DINV.WD.GD.ZS": "Inversión extranjera directa (% PIB)",
|
| 45 |
}
|
| 46 |
|
|
|
|
| 47 |
class ChatRequest(BaseModel):
|
| 48 |
query: str
|
| 49 |
session_id: str = "mobile"
|
| 50 |
|
| 51 |
+
# ── Data fetchers ─────────────────────────────────────────────────────────────
|
| 52 |
def fetch_banxico_serie(serie_id: str) -> dict:
|
| 53 |
url = f"https://www.banxico.org.mx/SieAPIRest/service/v1/series/{serie_id}/datos/oportuno?token={BANXICO_TOKEN}"
|
| 54 |
try:
|
|
|
|
| 56 |
r.raise_for_status()
|
| 57 |
data = r.json()
|
| 58 |
series = data.get("bmx", {}).get("series", [])
|
| 59 |
+
if not series: return {"valor": None, "fecha": None}
|
|
|
|
| 60 |
datos = series[0].get("datos", [])
|
| 61 |
+
if not datos: return {"valor": None, "fecha": None}
|
|
|
|
| 62 |
ultimo = datos[-1]
|
| 63 |
+
return {"valor": ultimo.get("dato"), "fecha": ultimo.get("fecha")}
|
| 64 |
+
except:
|
| 65 |
+
return {"valor": None, "fecha": None}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
def fetch_worldbank(indicator: str) -> dict:
|
| 68 |
try:
|
|
|
|
| 71 |
data = r.json()
|
| 72 |
if len(data) > 1 and data[1]:
|
| 73 |
entry = data[1][0]
|
| 74 |
+
return {"valor": entry.get("value"), "año": entry.get("date")}
|
| 75 |
+
except:
|
| 76 |
+
pass
|
| 77 |
+
return {"valor": None, "año": None}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
+
def search_wikipedia(query: str) -> str:
|
| 80 |
+
"""Busca en Wikipedia en español, fallback a inglés."""
|
| 81 |
+
try:
|
| 82 |
+
# Búsqueda en español
|
| 83 |
+
url = "https://es.wikipedia.org/api/rest_v1/page/summary/" + query.replace(" ", "_")
|
| 84 |
+
r = requests.get(url, timeout=10)
|
| 85 |
+
if r.status_code == 200:
|
| 86 |
+
data = r.json()
|
| 87 |
+
extract = data.get("extract", "")
|
| 88 |
+
if extract and len(extract) > 50:
|
| 89 |
+
return extract[:800]
|
| 90 |
+
except:
|
| 91 |
+
pass
|
| 92 |
+
try:
|
| 93 |
+
# Fallback a inglés
|
| 94 |
+
url = "https://en.wikipedia.org/api/rest_v1/page/summary/" + query.replace(" ", "_")
|
| 95 |
+
r = requests.get(url, timeout=10)
|
| 96 |
+
if r.status_code == 200:
|
| 97 |
+
data = r.json()
|
| 98 |
+
return data.get("extract", "")[:800]
|
| 99 |
+
except:
|
| 100 |
+
pass
|
| 101 |
+
return ""
|
| 102 |
+
|
| 103 |
+
def search_tavily(query: str) -> str:
|
| 104 |
+
"""Búsqueda web en tiempo real vía Tavily."""
|
| 105 |
+
if not TAVILY_API_KEY:
|
| 106 |
+
return ""
|
| 107 |
+
try:
|
| 108 |
+
r = requests.post(
|
| 109 |
+
"https://api.tavily.com/search",
|
| 110 |
+
json={
|
| 111 |
+
"api_key": TAVILY_API_KEY,
|
| 112 |
+
"query": query + " México 2025",
|
| 113 |
+
"max_results": 3,
|
| 114 |
+
"search_depth": "basic",
|
| 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 |
+
lines.append(f"• {nombre}: {d['valor']} (fecha: {d['fecha']})")
|
|
|
|
|
|
|
| 148 |
|
| 149 |
# World Bank
|
| 150 |
+
lines.append("\n--- WORLD BANK (datos macroeconómicos) ---")
|
| 151 |
+
wb_data = {
|
| 152 |
+
"NY.GDP.MKTP.CD": "PIB México",
|
| 153 |
+
"NY.GDP.PCAP.CD": "PIB per cápita USD",
|
| 154 |
+
"FP.CPI.TOTL.ZG": "Inflación anual %",
|
| 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 indicator, nombre in wb_data.items():
|
| 160 |
d = fetch_worldbank(indicator)
|
| 161 |
if d.get("valor"):
|
| 162 |
+
val = d['valor']
|
| 163 |
+
if indicator == "NY.GDP.MKTP.CD":
|
| 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 |
+
lines.append(f"• {nombre}: {val} ({d.get('año','')})")
|
| 170 |
|
| 171 |
+
# IFT Telco
|
| 172 |
lines.append("\n--- IFT TELECOMUNICACIONES (Q1 2025 verificado) ---")
|
| 173 |
lines.append("• Ingresos sector telco Q1 2025: 148,541 millones MXN")
|
| 174 |
lines.append("• Total líneas móviles: 127.4 millones (Q3 2024)")
|
| 175 |
lines.append("• Telcel (América Móvil): 63.4% participación")
|
| 176 |
lines.append("• AT&T México: 17.5% participación")
|
| 177 |
+
lines.append("• Movistar (Telefónica): 17.0% vía acuerdo infraestructura AT&T")
|
| 178 |
+
lines.append("• Otros MVNOs (Bait, Virgin, Diri): 2.1%")
|
| 179 |
lines.append("• Cobertura 4G LTE: 92% población")
|
| 180 |
+
lines.append("• Penetración 5G estimada: 3.5% (CDMX, GDL, MTY, QRO)")
|
| 181 |
lines.append("• Portabilidad H1 2025: Bait líder captación (+244,024), AT&T mayor pérdida (-752,664)")
|
| 182 |
+
lines.append("• Altán Redes: 4.5G LTE (NO 5G comercial)")
|
| 183 |
+
lines.append("• Regulador: ATDT (antes IFT, reorganizado 2025)")
|
| 184 |
+
|
| 185 |
+
# Contexto económico general
|
| 186 |
+
lines.append("\n--- CONTEXTO ECONÓMICO MÉXICO 2025 ---")
|
| 187 |
+
lines.append("• Política monetaria: Banxico en ciclo de baja de tasas desde 2024")
|
| 188 |
+
lines.append("• Nearshoring: México beneficiado por relocalización de cadenas de suministro")
|
| 189 |
+
lines.append("• T-MEC vigente, revisión 2026 en proceso")
|
| 190 |
+
lines.append("• Remesas: récord histórico ~$64,000 MDD en 2024")
|
| 191 |
+
lines.append("• Turismo: ~$35,000 MDD en divisas 2024")
|
| 192 |
+
lines.append("• Reforma judicial 2024: impacto en certeza jurídica e inversión extranjera")
|
| 193 |
+
lines.append("• PEMEX: restructuración financiera en curso, deuda ~$100,000 MDD")
|
| 194 |
+
lines.append("• CFE: expansión renovables, meta 35% energía limpia 2024")
|
| 195 |
+
|
| 196 |
+
# Wikipedia para contexto adicional
|
| 197 |
+
wiki_queries = []
|
| 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 |
+
headers = {"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"}
|
|
|
|
|
|
|
|
|
|
| 247 |
payload = {
|
| 248 |
"model": "llama-3.3-70b-versatile",
|
| 249 |
"messages": [
|
| 250 |
{"role": "system", "content": system_prompt},
|
| 251 |
{"role": "user", "content": prompt}
|
| 252 |
],
|
| 253 |
+
"max_tokens": 1500,
|
| 254 |
"temperature": 0.2,
|
| 255 |
}
|
| 256 |
+
r = requests.post(f"{GROQ_BASE_URL}/chat/completions", headers=headers, json=payload, timeout=20)
|
|
|
|
| 257 |
r.raise_for_status()
|
| 258 |
data = r.json()
|
| 259 |
latencia = int((time.time() - start) * 1000)
|
|
|
|
| 268 |
# Fallback NVIDIA NIM
|
| 269 |
try:
|
| 270 |
start = time.time()
|
| 271 |
+
headers = {"Authorization": f"Bearer {NVIDIA_API_KEY}", "Content-Type": "application/json"}
|
|
|
|
|
|
|
|
|
|
| 272 |
payload = {
|
| 273 |
"model": "meta/llama-3.1-70b-instruct",
|
| 274 |
"messages": [
|
| 275 |
{"role": "system", "content": system_prompt},
|
| 276 |
{"role": "user", "content": prompt}
|
| 277 |
],
|
| 278 |
+
"max_tokens": 1500,
|
| 279 |
"temperature": 0.2,
|
| 280 |
}
|
| 281 |
+
r = requests.post(f"{NVIDIA_BASE_URL}/chat/completions", headers=headers, json=payload, timeout=45)
|
|
|
|
| 282 |
r.raise_for_status()
|
| 283 |
data = r.json()
|
| 284 |
latencia = int((time.time() - start) * 1000)
|
|
|
|
| 288 |
"latencia_ms": latencia,
|
| 289 |
}
|
| 290 |
except Exception as e:
|
| 291 |
+
return {"respuesta": f"Error: {e}", "modelo": "error", "latencia_ms": 0}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
|
| 293 |
# ── Endpoints ─────────────────────────────────────────────────────────────────
|
|
|
|
| 294 |
@app.get("/")
|
| 295 |
def root():
|
| 296 |
return {
|
| 297 |
"name": "Fer Private AI · API",
|
| 298 |
+
"version": "2.0.0",
|
| 299 |
"status": "ok",
|
| 300 |
"endpoints": ["/health", "/indicadores", "/telco", "/worldbank", "/chat"],
|
| 301 |
"compute": "NVIDIA H100 · NIM + Groq LPU",
|
| 302 |
+
"tools": ["Banxico SIE", "World Bank", "IFT", "Wikipedia ES/EN", "Tavily"],
|
| 303 |
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 304 |
}
|
| 305 |
|
|
|
|
| 308 |
return {
|
| 309 |
"status": "ok",
|
| 310 |
"timestamp": datetime.utcnow().isoformat() + "Z",
|
|
|
|
| 311 |
"secrets": {
|
| 312 |
"NVIDIA_API_KEY": "✅" if NVIDIA_API_KEY else "❌",
|
| 313 |
"BANXICO_TOKEN": "✅" if BANXICO_TOKEN else "❌",
|
| 314 |
"GROQ_API_KEY": "✅" if GROQ_API_KEY else "❌",
|
| 315 |
+
"TAVILY_API_KEY": "✅" if TAVILY_API_KEY else "❌",
|
| 316 |
}
|
| 317 |
}
|
| 318 |
|
|
|
|
| 321 |
if not BANXICO_TOKEN:
|
| 322 |
raise HTTPException(status_code=503, detail="BANXICO_TOKEN no configurado")
|
| 323 |
resultados = {}
|
| 324 |
+
series = {
|
| 325 |
+
"SF43718": "Tipo de cambio USD/MXN (FIX)",
|
| 326 |
+
"SF46410": "TIIE 28 días (%)",
|
| 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": "Banxico SIE API",
|
| 336 |
"timestamp": datetime.utcnow().isoformat() + "Z",
|
|
|
|
| 340 |
@app.get("/telco")
|
| 341 |
def telco():
|
| 342 |
return {
|
| 343 |
+
"fuente": "IFT · ATDT",
|
| 344 |
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 345 |
"mercado_movil": {
|
| 346 |
"total_lineas_millones": 127.4,
|
|
|
|
| 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 wb_data.items():
|
| 371 |
+
d = fetch_worldbank(indicator)
|
| 372 |
+
resultados[indicator] = {"nombre": nombre, "valor": d["valor"], "año": d["año"]}
|
| 373 |
return {
|
| 374 |
"fuente": "World Bank API",
|
| 375 |
"timestamp": datetime.utcnow().isoformat() + "Z",
|