Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -27,10 +27,16 @@ BANXICO_SERIES = {
|
|
| 27 |
"SF43718": "Tipo de cambio USD/MXN (FIX)",
|
| 28 |
"SF46410": "TIIE 28 días (%)",
|
| 29 |
"SF61745": "Tasa objetivo Banxico (%)",
|
| 30 |
-
"SP74625": "Inflación general",
|
| 31 |
"SF290383": "Reservas internacionales (MDD)",
|
| 32 |
}
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
# ── Models ────────────────────────────────────────────────────────────────────
|
| 35 |
class ChatRequest(BaseModel):
|
| 36 |
query: str
|
|
@@ -59,8 +65,77 @@ def fetch_banxico_serie(serie_id: str) -> dict:
|
|
| 59 |
except Exception as e:
|
| 60 |
return {"serie": serie_id, "error": str(e)}
|
| 61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
def call_llm(prompt: str) -> dict:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
if GROQ_API_KEY:
|
| 65 |
try:
|
| 66 |
start = time.time()
|
|
@@ -71,14 +146,14 @@ def call_llm(prompt: str) -> dict:
|
|
| 71 |
payload = {
|
| 72 |
"model": "llama-3.3-70b-versatile",
|
| 73 |
"messages": [
|
| 74 |
-
{"role": "system", "content":
|
| 75 |
{"role": "user", "content": prompt}
|
| 76 |
],
|
| 77 |
"max_tokens": 1024,
|
| 78 |
-
"temperature": 0.
|
| 79 |
}
|
| 80 |
r = requests.post(f"{GROQ_BASE_URL}/chat/completions",
|
| 81 |
-
headers=headers, json=payload, timeout=
|
| 82 |
r.raise_for_status()
|
| 83 |
data = r.json()
|
| 84 |
latencia = int((time.time() - start) * 1000)
|
|
@@ -90,6 +165,7 @@ def call_llm(prompt: str) -> dict:
|
|
| 90 |
except Exception:
|
| 91 |
pass
|
| 92 |
|
|
|
|
| 93 |
try:
|
| 94 |
start = time.time()
|
| 95 |
headers = {
|
|
@@ -99,11 +175,11 @@ def call_llm(prompt: str) -> dict:
|
|
| 99 |
payload = {
|
| 100 |
"model": "meta/llama-3.1-70b-instruct",
|
| 101 |
"messages": [
|
| 102 |
-
{"role": "system", "content":
|
| 103 |
{"role": "user", "content": prompt}
|
| 104 |
],
|
| 105 |
"max_tokens": 1024,
|
| 106 |
-
"temperature": 0.
|
| 107 |
}
|
| 108 |
r = requests.post(f"{NVIDIA_BASE_URL}/chat/completions",
|
| 109 |
headers=headers, json=payload, timeout=45)
|
|
@@ -183,26 +259,9 @@ def telco():
|
|
| 183 |
|
| 184 |
@app.get("/worldbank")
|
| 185 |
def worldbank():
|
| 186 |
-
WB_INDICATORS = {
|
| 187 |
-
"NY.GDP.MKTP.CD": "PIB México (USD)",
|
| 188 |
-
"FP.CPI.TOTL.ZG": "Inflación anual (%)",
|
| 189 |
-
"SL.UEM.TOTL.ZS": "Desempleo (%)",
|
| 190 |
-
}
|
| 191 |
resultados = {}
|
| 192 |
for indicator, nombre in WB_INDICATORS.items():
|
| 193 |
-
|
| 194 |
-
url = f"https://api.worldbank.org/v2/country/MX/indicator/{indicator}?format=json&mrv=1"
|
| 195 |
-
r = requests.get(url, timeout=15)
|
| 196 |
-
data = r.json()
|
| 197 |
-
if len(data) > 1 and data[1]:
|
| 198 |
-
entry = data[1][0]
|
| 199 |
-
resultados[indicator] = {
|
| 200 |
-
"nombre": nombre,
|
| 201 |
-
"valor": entry.get("value"),
|
| 202 |
-
"año": entry.get("date"),
|
| 203 |
-
}
|
| 204 |
-
except Exception as e:
|
| 205 |
-
resultados[indicator] = {"nombre": nombre, "error": str(e)}
|
| 206 |
return {
|
| 207 |
"fuente": "World Bank API",
|
| 208 |
"timestamp": datetime.utcnow().isoformat() + "Z",
|
|
|
|
| 27 |
"SF43718": "Tipo de cambio USD/MXN (FIX)",
|
| 28 |
"SF46410": "TIIE 28 días (%)",
|
| 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": "PIB México (USD)",
|
| 36 |
+
"FP.CPI.TOTL.ZG": "Inflación anual (%)",
|
| 37 |
+
"SL.UEM.TOTL.ZS": "Desempleo (%)",
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
# ── Models ────────────────────────────────────────────────────────────────────
|
| 41 |
class ChatRequest(BaseModel):
|
| 42 |
query: str
|
|
|
|
| 65 |
except Exception as e:
|
| 66 |
return {"serie": serie_id, "error": str(e)}
|
| 67 |
|
| 68 |
+
def fetch_worldbank(indicator: str) -> dict:
|
| 69 |
+
try:
|
| 70 |
+
url = f"https://api.worldbank.org/v2/country/MX/indicator/{indicator}?format=json&mrv=1"
|
| 71 |
+
r = requests.get(url, timeout=15)
|
| 72 |
+
data = r.json()
|
| 73 |
+
if len(data) > 1 and data[1]:
|
| 74 |
+
entry = data[1][0]
|
| 75 |
+
return {
|
| 76 |
+
"nombre": WB_INDICATORS.get(indicator, indicator),
|
| 77 |
+
"valor": entry.get("value"),
|
| 78 |
+
"año": entry.get("date"),
|
| 79 |
+
}
|
| 80 |
+
except Exception as e:
|
| 81 |
+
return {"nombre": WB_INDICATORS.get(indicator), "error": str(e)}
|
| 82 |
+
return {}
|
| 83 |
+
|
| 84 |
+
def get_context_data() -> str:
|
| 85 |
+
"""Obtiene datos reales y construye contexto para el LLM."""
|
| 86 |
+
lines = ["=== DATOS REALES EN TIEMPO REAL — MÉXICO ===\n"]
|
| 87 |
+
|
| 88 |
+
# Banxico
|
| 89 |
+
lines.append("--- BANXICO (datos oficiales hoy) ---")
|
| 90 |
+
for serie_id in BANXICO_SERIES:
|
| 91 |
+
d = fetch_banxico_serie(serie_id)
|
| 92 |
+
if d.get("valor"):
|
| 93 |
+
lines.append(f"• {d['nombre']}: {d['valor']} (fecha: {d['fecha']})")
|
| 94 |
+
else:
|
| 95 |
+
lines.append(f"• {d['nombre']}: no disponible")
|
| 96 |
+
|
| 97 |
+
# World Bank
|
| 98 |
+
lines.append("\n--- WORLD BANK (datos más recientes) ---")
|
| 99 |
+
for indicator in WB_INDICATORS:
|
| 100 |
+
d = fetch_worldbank(indicator)
|
| 101 |
+
if d.get("valor"):
|
| 102 |
+
lines.append(f"• {d['nombre']}: {d['valor']} ({d.get('año','')})")
|
| 103 |
+
else:
|
| 104 |
+
lines.append(f"• {d['nombre']}: no disponible")
|
| 105 |
+
|
| 106 |
+
# IFT Telco (hardcoded verificado)
|
| 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% participación")
|
| 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 |
+
"""Obtiene datos reales, los inyecta en el prompt y llama al LLM."""
|
| 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 y ACTUALIZADOS obtenidos ahora mismo de fuentes oficiales:
|
| 127 |
+
|
| 128 |
+
{context}
|
| 129 |
+
|
| 130 |
+
REGLAS CRÍTICAS:
|
| 131 |
+
1. SIEMPRE usa los datos reales de arriba para responder — NUNCA digas "no tengo acceso a datos en tiempo real"
|
| 132 |
+
2. Si la pregunta es sobre TIIE, USD/MXN, inflación, reservas o tasa Banxico — usa los valores exactos de arriba
|
| 133 |
+
3. Si la pregunta es sobre telecomunicaciones — usa los datos IFT de arriba
|
| 134 |
+
4. Responde en español, de forma concisa y directa
|
| 135 |
+
5. Cita la fuente (Banxico, World Bank, IFT) al final de tu respuesta
|
| 136 |
+
6. Si el dato no está en los datos de arriba, dilo claramente sin inventar"""
|
| 137 |
+
|
| 138 |
+
# Groq LPU primero — rápido
|
| 139 |
if GROQ_API_KEY:
|
| 140 |
try:
|
| 141 |
start = time.time()
|
|
|
|
| 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": 1024,
|
| 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)
|
|
|
|
| 165 |
except Exception:
|
| 166 |
pass
|
| 167 |
|
| 168 |
+
# Fallback NVIDIA NIM
|
| 169 |
try:
|
| 170 |
start = time.time()
|
| 171 |
headers = {
|
|
|
|
| 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": 1024,
|
| 182 |
+
"temperature": 0.2,
|
| 183 |
}
|
| 184 |
r = requests.post(f"{NVIDIA_BASE_URL}/chat/completions",
|
| 185 |
headers=headers, json=payload, timeout=45)
|
|
|
|
| 259 |
|
| 260 |
@app.get("/worldbank")
|
| 261 |
def worldbank():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 262 |
resultados = {}
|
| 263 |
for indicator, nombre in WB_INDICATORS.items():
|
| 264 |
+
resultados[indicator] = fetch_worldbank(indicator)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 265 |
return {
|
| 266 |
"fuente": "World Bank API",
|
| 267 |
"timestamp": datetime.utcnow().isoformat() + "Z",
|