Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,15 +1,21 @@
|
|
| 1 |
"""
|
| 2 |
-
main.py β Fer Private AI Β· API REST
|
| 3 |
mx-data-api Space Β· Puerto 7860
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
"""
|
| 6 |
-
import os
|
|
|
|
|
|
|
| 7 |
from datetime import datetime
|
| 8 |
from fastapi import FastAPI, HTTPException
|
| 9 |
from fastapi.middleware.cors import CORSMiddleware
|
| 10 |
from pydantic import BaseModel
|
| 11 |
|
| 12 |
-
app = FastAPI(title="Fer Private AI Β· API", version="
|
| 13 |
|
| 14 |
app.add_middleware(
|
| 15 |
CORSMiddleware,
|
|
@@ -18,35 +24,21 @@ app.add_middleware(
|
|
| 18 |
allow_headers=["*"],
|
| 19 |
)
|
| 20 |
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
GROQ_API_KEY = os.getenv("GROQ_API_KEY", "")
|
| 24 |
-
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY", "")
|
| 25 |
-
INTERNAL_API_KEY = os.getenv("INTERNAL_API_KEY", "")
|
| 26 |
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
"SF43783": "TIIE 28 dΓas (%)",
|
| 30 |
-
"SF61745": "Tasa objetivo Banxico (%)",
|
| 31 |
-
"SP74625": "InflaciΓ³n general (Γndice INPC)",
|
| 32 |
-
"SF290383": "Reservas internacionales (MDD)",
|
| 33 |
-
"SF43784": "Tipo de cambio EUR/MXN",
|
| 34 |
-
}
|
| 35 |
|
| 36 |
-
|
| 37 |
-
"
|
| 38 |
-
"
|
| 39 |
-
"
|
| 40 |
-
"
|
| 41 |
-
"
|
| 42 |
-
"BX.KLT.DINV.WD.GD.ZS": "IED (% PIB)",
|
| 43 |
}
|
| 44 |
|
| 45 |
-
#
|
| 46 |
-
# PREGUNTAS VERIFICADAS β fuente ΓΊnica para PWA y Streamlit
|
| 47 |
-
# Solo preguntas con datos reales en el bucket. Sin especulaciΓ³n ni histΓ³ricos
|
| 48 |
-
# que el sistema no tiene. Actualizar aquΓ = se actualiza en todo el sistema.
|
| 49 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 50 |
QUESTIONS = {
|
| 51 |
"banxico": [
|
| 52 |
"ΒΏCuΓ‘l es el tipo de cambio USD/MXN hoy?",
|
|
@@ -114,13 +106,13 @@ class ChatRequest(BaseModel):
|
|
| 114 |
query: str
|
| 115 |
session_id: str = "mobile"
|
| 116 |
|
| 117 |
-
# ββ Fetchers ββββββββββββββ
|
| 118 |
def fetch_banxico(serie_id: str) -> dict:
|
| 119 |
try:
|
| 120 |
url = f"https://www.banxico.org.mx/SieAPIRest/service/v1/series/{serie_id}/datos/oportuno?token={BANXICO_TOKEN}"
|
| 121 |
r = requests.get(url, timeout=15)
|
| 122 |
r.raise_for_status()
|
| 123 |
-
data
|
| 124 |
series = data.get("bmx", {}).get("series", [])
|
| 125 |
if not series: return {}
|
| 126 |
datos = series[0].get("datos", [])
|
|
@@ -130,161 +122,117 @@ def fetch_banxico(serie_id: str) -> dict:
|
|
| 130 |
except:
|
| 131 |
return {}
|
| 132 |
|
| 133 |
-
|
|
|
|
|
|
|
| 134 |
try:
|
| 135 |
-
|
| 136 |
-
r = requests.
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
pass
|
| 143 |
-
return {}
|
| 144 |
|
| 145 |
-
#
|
| 146 |
-
|
| 147 |
|
| 148 |
-
def
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
|
| 158 |
-
def call_real_agent(query: str, session_id: str = "mobile") -> dict:
|
| 159 |
try:
|
| 160 |
-
load_agent()
|
| 161 |
-
from modules.agent_orchestrator import run_agent
|
| 162 |
start = time.time()
|
| 163 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
return {
|
| 165 |
-
"response":
|
| 166 |
-
"modelo": "
|
| 167 |
"latencia_ms": int((time.time() - start) * 1000),
|
| 168 |
}
|
| 169 |
except Exception as e:
|
| 170 |
-
return
|
| 171 |
-
|
| 172 |
-
def call_llm_fallback(query: str, error: str = "") -> dict:
|
| 173 |
-
facts = []
|
| 174 |
-
for serie_id, nombre in BANXICO_SERIES.items():
|
| 175 |
-
d = fetch_banxico(serie_id)
|
| 176 |
-
if d.get("valor"):
|
| 177 |
-
facts.append(f"β’ {nombre}: {d['valor']} ({d['fecha']}) β Fuente: Banxico")
|
| 178 |
-
wb_map = {"NY.GDP.MKTP.CD": "PIB MΓ©xico", "FP.CPI.TOTL.ZG": "InflaciΓ³n anual %", "SL.UEM.TOTL.ZS": "Desempleo %"}
|
| 179 |
-
for ind, nombre in wb_map.items():
|
| 180 |
-
d = fetch_worldbank(ind)
|
| 181 |
-
if d.get("valor"):
|
| 182 |
-
if ind == "NY.GDP.MKTP.CD":
|
| 183 |
-
# World Bank devuelve en USD absolutos (~1.856e12)
|
| 184 |
-
# Convertir correctamente a billones (trillion)
|
| 185 |
-
val_num = float(d["valor"])
|
| 186 |
-
val = f"${val_num/1e12:.3f} billones USD ({val_num/1e12*1000:.1f} miles de millones)"
|
| 187 |
-
else:
|
| 188 |
-
val = f"{float(d['valor']):.2f}%"
|
| 189 |
-
facts.append(f"β’ {nombre}: {val} ({d.get('aΓ±o','')}) β Fuente: World Bank")
|
| 190 |
-
facts += [
|
| 191 |
-
"β’ Telcel: 63.4% participaciΓ³n mercado mΓ³vil β Fuente: IFT Q3 2024",
|
| 192 |
-
"β’ AT&T MΓ©xico: 17.5% β Fuente: IFT Q3 2024",
|
| 193 |
-
"β’ Portabilidad H1 2025: Bait +244,024 / AT&T -752,664 β Fuente: IFT",
|
| 194 |
-
]
|
| 195 |
-
facts_str = "\n".join(facts)
|
| 196 |
-
system = "Eres experto en economΓa y telecomunicaciones de MΓ©xico. USA SOLO los datos verificados. Cita la fuente."
|
| 197 |
-
user = f"DATOS VERIFICADOS:\n{facts_str}\n\nPREGUNTA: {query}"
|
| 198 |
-
if GROQ_API_KEY:
|
| 199 |
-
try:
|
| 200 |
-
start = time.time()
|
| 201 |
-
r = requests.post(
|
| 202 |
-
"https://api.groq.com/openai/v1/chat/completions",
|
| 203 |
-
headers={"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"},
|
| 204 |
-
json={"model": "llama-3.3-70b-versatile", "messages": [
|
| 205 |
-
{"role": "system", "content": system},
|
| 206 |
-
{"role": "user", "content": user}
|
| 207 |
-
], "max_tokens": 1200, "temperature": 0.1},
|
| 208 |
-
timeout=20
|
| 209 |
-
)
|
| 210 |
-
r.raise_for_status()
|
| 211 |
-
return {
|
| 212 |
-
"response": r.json()["choices"][0]["message"]["content"],
|
| 213 |
-
"modelo": "Llama 3.3 70B Β· Groq LPU (fallback)",
|
| 214 |
-
"latencia_ms": int((time.time() - start) * 1000),
|
| 215 |
-
}
|
| 216 |
-
except:
|
| 217 |
-
pass
|
| 218 |
-
return {"response": f"Error en agente: {error}", "modelo": "error", "latencia_ms": 0}
|
| 219 |
|
| 220 |
# ββ Endpoints βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 221 |
@app.get("/")
|
| 222 |
def root():
|
| 223 |
return {
|
| 224 |
-
"name": "Fer Private AI Β· API",
|
| 225 |
-
"version": "
|
| 226 |
-
"
|
| 227 |
"endpoints": ["/health", "/indicadores", "/telco", "/worldbank", "/chat", "/questions"],
|
| 228 |
-
"compute": "NVIDIA H100 Β· NIM + Groq LPU",
|
| 229 |
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 230 |
}
|
| 231 |
|
| 232 |
@app.get("/health")
|
| 233 |
def health():
|
| 234 |
-
|
| 235 |
try:
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
except
|
| 239 |
pass
|
| 240 |
return {
|
| 241 |
-
"status":
|
| 242 |
-
"version":
|
| 243 |
-
"
|
| 244 |
-
"
|
| 245 |
-
"bucket_data": "β
" if os.path.exists("/data/banxico.json") else "β /data no montado",
|
| 246 |
-
"secrets": {
|
| 247 |
-
"NVIDIA_API_KEY": "β
" if NVIDIA_API_KEY else "β",
|
| 248 |
-
"BANXICO_TOKEN": "β
" if BANXICO_TOKEN else "β",
|
| 249 |
-
"GROQ_API_KEY": "β
" if GROQ_API_KEY else "β",
|
| 250 |
-
"TAVILY_API_KEY": "β
" if TAVILY_API_KEY else "β",
|
| 251 |
-
"INTERNAL_API_KEY": "β
" if INTERNAL_API_KEY else "β",
|
| 252 |
-
},
|
| 253 |
}
|
| 254 |
|
| 255 |
@app.get("/questions")
|
| 256 |
def questions(categoria: str = None):
|
| 257 |
-
"""
|
| 258 |
-
Fuente ΓΊnica de preguntas verificadas para PWA y Streamlit.
|
| 259 |
-
?categoria=banxico|worldbank|inegi|telco|agente
|
| 260 |
-
Sin parΓ‘metro: devuelve todas las categorΓas.
|
| 261 |
-
"""
|
| 262 |
if categoria:
|
| 263 |
if categoria not in QUESTIONS:
|
| 264 |
-
raise HTTPException(status_code=404, detail=f"CategorΓa
|
| 265 |
-
return {
|
| 266 |
-
|
| 267 |
-
"preguntas": QUESTIONS[categoria],
|
| 268 |
-
"total": len(QUESTIONS[categoria]),
|
| 269 |
-
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 270 |
-
}
|
| 271 |
-
return {
|
| 272 |
-
"categorias": {cat: qs for cat, qs in QUESTIONS.items()},
|
| 273 |
-
"total": sum(len(qs) for qs in QUESTIONS.values()),
|
| 274 |
-
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 275 |
-
}
|
| 276 |
|
| 277 |
@app.get("/indicadores")
|
| 278 |
def indicadores():
|
| 279 |
-
if not BANXICO_TOKEN:
|
| 280 |
-
raise HTTPException(status_code=503, detail="BANXICO_TOKEN no configurado")
|
| 281 |
resultados = {}
|
| 282 |
-
for
|
| 283 |
-
d = fetch_banxico(
|
| 284 |
-
resultados[
|
| 285 |
|
| 286 |
-
|
| 287 |
-
tc = resultados.get("SF43718", {})
|
| 288 |
tiie = resultados.get("SF43783", {})
|
| 289 |
tasa = resultados.get("SF61745", {})
|
| 290 |
res = resultados.get("SF290383", {})
|
|
@@ -303,7 +251,6 @@ def indicadores():
|
|
| 303 |
"fecha_res": res.get("fecha"),
|
| 304 |
"inpc": inpc.get("valor"),
|
| 305 |
"fecha_inpc": inpc.get("fecha"),
|
| 306 |
-
"indicadores": resultados,
|
| 307 |
}
|
| 308 |
|
| 309 |
@app.get("/telco")
|
|
@@ -322,27 +269,36 @@ def telco():
|
|
| 322 |
]
|
| 323 |
},
|
| 324 |
"ingresos_q1_2025_millones_mxn": 148541.1,
|
| 325 |
-
"cobertura_4g_pct_poblacion": 92.0,
|
| 326 |
-
"penetracion_5g_pct": 3.5,
|
| 327 |
}
|
| 328 |
|
| 329 |
@app.get("/worldbank")
|
| 330 |
def worldbank():
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
"fuente": "World Bank API",
|
| 337 |
-
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 338 |
-
"indicadores": resultados,
|
| 339 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 340 |
|
| 341 |
@app.post("/chat")
|
| 342 |
def chat(req: ChatRequest):
|
| 343 |
if not req.query.strip():
|
| 344 |
raise HTTPException(status_code=400, detail="Query vacΓa")
|
| 345 |
-
result =
|
| 346 |
return {
|
| 347 |
"query": req.query,
|
| 348 |
"response": result.get("response", ""),
|
|
|
|
| 1 |
"""
|
| 2 |
+
main.py β Fer Private AI Β· API REST v6.0 Β· PROXY
|
| 3 |
mx-data-api Space Β· Puerto 7860
|
| 4 |
+
|
| 5 |
+
v6.0: Proxy puro β toda la lΓ³gica vive en mx-data-intelligence
|
| 6 |
+
Este Space solo hace forward al Space principal.
|
| 7 |
+
NO duplica agent_orchestrator, agent_tools ni ningΓΊn mΓ³dulo.
|
| 8 |
+
Un solo cerebro, una sola fuente de verdad.
|
| 9 |
"""
|
| 10 |
+
import os
|
| 11 |
+
import requests
|
| 12 |
+
import time
|
| 13 |
from datetime import datetime
|
| 14 |
from fastapi import FastAPI, HTTPException
|
| 15 |
from fastapi.middleware.cors import CORSMiddleware
|
| 16 |
from pydantic import BaseModel
|
| 17 |
|
| 18 |
+
app = FastAPI(title="Fer Private AI Β· API Proxy", version="6.0.0")
|
| 19 |
|
| 20 |
app.add_middleware(
|
| 21 |
CORSMiddleware,
|
|
|
|
| 24 |
allow_headers=["*"],
|
| 25 |
)
|
| 26 |
|
| 27 |
+
# Space principal β ΓΊnico cerebro del sistema
|
| 28 |
+
BRAIN_URL = "https://fercor95mx-mx-data-intelligence.hf.space"
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
+
BANXICO_TOKEN = os.getenv("BANXICO_TOKEN", "")
|
| 31 |
+
GROQ_API_KEY = os.getenv("GROQ_API_KEY", "")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
+
BANXICO_SERIES = {
|
| 34 |
+
"SF43718": "tipo_cambio_usd_mxn",
|
| 35 |
+
"SF43783": "tiie_28_dias",
|
| 36 |
+
"SF61745": "tasa_objetivo",
|
| 37 |
+
"SP74625": "inflacion_ipc",
|
| 38 |
+
"SF290383": "reservas_internacionales",
|
|
|
|
| 39 |
}
|
| 40 |
|
| 41 |
+
# ββ Preguntas verificadas β fuente ΓΊnica ββββββββββββββββββββββββββββββββββββββ
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
QUESTIONS = {
|
| 43 |
"banxico": [
|
| 44 |
"ΒΏCuΓ‘l es el tipo de cambio USD/MXN hoy?",
|
|
|
|
| 106 |
query: str
|
| 107 |
session_id: str = "mobile"
|
| 108 |
|
| 109 |
+
# ββ Fetchers directos (para /indicadores sin depender del Space) ββββββββββββββ
|
| 110 |
def fetch_banxico(serie_id: str) -> dict:
|
| 111 |
try:
|
| 112 |
url = f"https://www.banxico.org.mx/SieAPIRest/service/v1/series/{serie_id}/datos/oportuno?token={BANXICO_TOKEN}"
|
| 113 |
r = requests.get(url, timeout=15)
|
| 114 |
r.raise_for_status()
|
| 115 |
+
data = r.json()
|
| 116 |
series = data.get("bmx", {}).get("series", [])
|
| 117 |
if not series: return {}
|
| 118 |
datos = series[0].get("datos", [])
|
|
|
|
| 122 |
except:
|
| 123 |
return {}
|
| 124 |
|
| 125 |
+
# ββ Proxy al cerebro principal ββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 126 |
+
def call_brain(query: str, session_id: str = "mobile") -> dict:
|
| 127 |
+
"""Llama al agente en mx-data-intelligence via su API interna."""
|
| 128 |
try:
|
| 129 |
+
start = time.time()
|
| 130 |
+
r = requests.post(
|
| 131 |
+
f"{BRAIN_URL}/api/chat",
|
| 132 |
+
json={"query": query, "session_id": session_id},
|
| 133 |
+
timeout=120,
|
| 134 |
+
headers={"Content-Type": "application/json"},
|
| 135 |
+
)
|
| 136 |
+
if r.status_code == 200:
|
| 137 |
+
d = r.json()
|
| 138 |
+
return {
|
| 139 |
+
"response": d.get("response", d.get("answer", "")),
|
| 140 |
+
"modelo": d.get("modelo", "Agente mx-data-intelligence"),
|
| 141 |
+
"latencia_ms": int((time.time() - start) * 1000),
|
| 142 |
+
}
|
| 143 |
+
except Exception as e:
|
| 144 |
pass
|
|
|
|
| 145 |
|
| 146 |
+
# Fallback: Groq directo con datos Banxico
|
| 147 |
+
return call_groq_fallback(query)
|
| 148 |
|
| 149 |
+
def call_groq_fallback(query: str) -> dict:
|
| 150 |
+
"""Fallback con Groq cuando el Space principal no responde."""
|
| 151 |
+
facts = []
|
| 152 |
+
for sid, nombre in BANXICO_SERIES.items():
|
| 153 |
+
d = fetch_banxico(sid)
|
| 154 |
+
if d.get("valor"):
|
| 155 |
+
facts.append(f"β’ {nombre}: {d['valor']} ({d['fecha']}) β Banxico")
|
| 156 |
+
|
| 157 |
+
facts += [
|
| 158 |
+
"β’ PIB MΓ©xico 2024: 1.856 billones USD β World Bank",
|
| 159 |
+
"β’ InflaciΓ³n general mayo 2026: 3.94% β INEGI",
|
| 160 |
+
"β’ IGAE abril 2026: 106.39 β INEGI BIE-BISE",
|
| 161 |
+
"β’ Telcel: 63.4% participaciΓ³n mercado mΓ³vil β IFT Q3 2024",
|
| 162 |
+
"β’ AT&T MΓ©xico: 17.5% β IFT Q3 2024",
|
| 163 |
+
"β’ Portabilidad H1 2025: Bait +244,024 / AT&T -752,664 β IFT",
|
| 164 |
+
]
|
| 165 |
+
|
| 166 |
+
if not GROQ_API_KEY:
|
| 167 |
+
return {"response": "\n".join(facts), "modelo": "datos directos", "latencia_ms": 0}
|
| 168 |
|
|
|
|
| 169 |
try:
|
|
|
|
|
|
|
| 170 |
start = time.time()
|
| 171 |
+
r = requests.post(
|
| 172 |
+
"https://api.groq.com/openai/v1/chat/completions",
|
| 173 |
+
headers={"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"},
|
| 174 |
+
json={
|
| 175 |
+
"model": "llama-3.3-70b-versatile",
|
| 176 |
+
"messages": [
|
| 177 |
+
{"role": "system", "content": "Eres experto en economΓa de MΓ©xico. USA SOLO los datos proporcionados. Cita siempre la fuente."},
|
| 178 |
+
{"role": "user", "content": f"DATOS VERIFICADOS:\n{chr(10).join(facts)}\n\nPREGUNTA: {query}"}
|
| 179 |
+
],
|
| 180 |
+
"max_tokens": 1200,
|
| 181 |
+
"temperature": 0.1,
|
| 182 |
+
},
|
| 183 |
+
timeout=20,
|
| 184 |
+
)
|
| 185 |
+
r.raise_for_status()
|
| 186 |
return {
|
| 187 |
+
"response": r.json()["choices"][0]["message"]["content"],
|
| 188 |
+
"modelo": "Llama 3.3 70B Β· Groq (fallback)",
|
| 189 |
"latencia_ms": int((time.time() - start) * 1000),
|
| 190 |
}
|
| 191 |
except Exception as e:
|
| 192 |
+
return {"response": f"Error: {e}", "modelo": "error", "latencia_ms": 0}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
|
| 194 |
# ββ Endpoints βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 195 |
@app.get("/")
|
| 196 |
def root():
|
| 197 |
return {
|
| 198 |
+
"name": "Fer Private AI Β· API Proxy",
|
| 199 |
+
"version": "6.0.0",
|
| 200 |
+
"brain": BRAIN_URL,
|
| 201 |
"endpoints": ["/health", "/indicadores", "/telco", "/worldbank", "/chat", "/questions"],
|
|
|
|
| 202 |
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 203 |
}
|
| 204 |
|
| 205 |
@app.get("/health")
|
| 206 |
def health():
|
| 207 |
+
brain_ok = False
|
| 208 |
try:
|
| 209 |
+
r = requests.get(f"{BRAIN_URL}/health", timeout=10)
|
| 210 |
+
brain_ok = r.status_code == 200
|
| 211 |
+
except:
|
| 212 |
pass
|
| 213 |
return {
|
| 214 |
+
"status": "ok",
|
| 215 |
+
"version": "6.0.0",
|
| 216 |
+
"brain": "β
conectado" if brain_ok else "β οΈ sin respuesta (Space dormido)",
|
| 217 |
+
"timestamp": datetime.utcnow().isoformat() + "Z",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
}
|
| 219 |
|
| 220 |
@app.get("/questions")
|
| 221 |
def questions(categoria: str = None):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
if categoria:
|
| 223 |
if categoria not in QUESTIONS:
|
| 224 |
+
raise HTTPException(status_code=404, detail=f"CategorΓa no existe. Usa: {list(QUESTIONS.keys())}")
|
| 225 |
+
return {"categoria": categoria, "preguntas": QUESTIONS[categoria], "total": len(QUESTIONS[categoria])}
|
| 226 |
+
return {"categorias": QUESTIONS, "total": sum(len(v) for v in QUESTIONS.values())}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
|
| 228 |
@app.get("/indicadores")
|
| 229 |
def indicadores():
|
|
|
|
|
|
|
| 230 |
resultados = {}
|
| 231 |
+
for sid, nombre in BANXICO_SERIES.items():
|
| 232 |
+
d = fetch_banxico(sid)
|
| 233 |
+
resultados[sid] = {"nombre": nombre, "valor": d.get("valor"), "fecha": d.get("fecha")}
|
| 234 |
|
| 235 |
+
tc = resultados.get("SF43718", {})
|
|
|
|
| 236 |
tiie = resultados.get("SF43783", {})
|
| 237 |
tasa = resultados.get("SF61745", {})
|
| 238 |
res = resultados.get("SF290383", {})
|
|
|
|
| 251 |
"fecha_res": res.get("fecha"),
|
| 252 |
"inpc": inpc.get("valor"),
|
| 253 |
"fecha_inpc": inpc.get("fecha"),
|
|
|
|
| 254 |
}
|
| 255 |
|
| 256 |
@app.get("/telco")
|
|
|
|
| 269 |
]
|
| 270 |
},
|
| 271 |
"ingresos_q1_2025_millones_mxn": 148541.1,
|
|
|
|
|
|
|
| 272 |
}
|
| 273 |
|
| 274 |
@app.get("/worldbank")
|
| 275 |
def worldbank():
|
| 276 |
+
WB = {
|
| 277 |
+
"NY.GDP.MKTP.CD": "PIB MΓ©xico (USD)",
|
| 278 |
+
"FP.CPI.TOTL.ZG": "InflaciΓ³n anual (%)",
|
| 279 |
+
"SL.UEM.TOTL.ZS": "Desempleo (%)",
|
| 280 |
+
"NY.GDP.PCAP.CD": "PIB per cΓ‘pita (USD)",
|
|
|
|
|
|
|
|
|
|
| 281 |
}
|
| 282 |
+
resultados = {}
|
| 283 |
+
for ind, nombre in WB.items():
|
| 284 |
+
try:
|
| 285 |
+
r = requests.get(
|
| 286 |
+
f"https://api.worldbank.org/v2/country/MX/indicator/{ind}?format=json&mrv=1",
|
| 287 |
+
timeout=15
|
| 288 |
+
)
|
| 289 |
+
data = r.json()
|
| 290 |
+
if len(data) > 1 and data[1]:
|
| 291 |
+
e = data[1][0]
|
| 292 |
+
resultados[ind] = {"nombre": nombre, "valor": e.get("value"), "aΓ±o": e.get("date")}
|
| 293 |
+
except:
|
| 294 |
+
resultados[ind] = {"nombre": nombre, "valor": None, "aΓ±o": None}
|
| 295 |
+
return {"fuente": "World Bank API", "timestamp": datetime.utcnow().isoformat() + "Z", "indicadores": resultados}
|
| 296 |
|
| 297 |
@app.post("/chat")
|
| 298 |
def chat(req: ChatRequest):
|
| 299 |
if not req.query.strip():
|
| 300 |
raise HTTPException(status_code=400, detail="Query vacΓa")
|
| 301 |
+
result = call_brain(req.query, req.session_id)
|
| 302 |
return {
|
| 303 |
"query": req.query,
|
| 304 |
"response": result.get("response", ""),
|