Fercor95mx commited on
Commit
6ce8dc2
·
verified ·
1 Parent(s): 25815f0

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +133 -48
main.py CHANGED
@@ -1,8 +1,7 @@
1
  """
2
- main.py — Fer Private AI · API REST v5.0
3
  mx-data-api Space · Puerto 7860
4
- v5: Importa run_agent() directamente — mismo cerebro que el Streamlit
5
- Bucket mx-data-truth montado en /data — acceso directo a JSONs
6
  """
7
  import os, requests, time
8
  from datetime import datetime
@@ -10,7 +9,7 @@ from fastapi import FastAPI, HTTPException
10
  from fastapi.middleware.cors import CORSMiddleware
11
  from pydantic import BaseModel
12
 
13
- app = FastAPI(title="Fer Private AI · API", version="5.0.0")
14
 
15
  app.add_middleware(
16
  CORSMiddleware,
@@ -27,7 +26,7 @@ INTERNAL_API_KEY = os.getenv("INTERNAL_API_KEY", "")
27
 
28
  BANXICO_SERIES = {
29
  "SF43718": "Tipo de cambio USD/MXN (FIX)",
30
- "SF46410": "TIIE 28 días (%)",
31
  "SF61745": "Tasa objetivo Banxico (%)",
32
  "SP74625": "Inflación general (índice INPC)",
33
  "SF290383": "Reservas internacionales (MDD)",
@@ -43,6 +42,74 @@ WB_INDICATORS = {
43
  "BX.KLT.DINV.WD.GD.ZS": "IED (% PIB)",
44
  }
45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  class ChatRequest(BaseModel):
47
  query: str
48
  session_id: str = "mobile"
@@ -79,7 +146,6 @@ def fetch_worldbank(indicator: str) -> dict:
79
  _agent_loaded = False
80
 
81
  def load_agent():
82
- """Carga el agente real una sola vez al primer uso."""
83
  global _agent_loaded
84
  if not _agent_loaded:
85
  try:
@@ -90,63 +156,45 @@ def load_agent():
90
  _agent_loaded = True
91
 
92
  def call_real_agent(query: str, session_id: str = "mobile") -> dict:
93
- """Llama a run_agent() del agent_orchestrator directamente."""
94
  try:
95
  load_agent()
96
- # Invalidar cache para forzar datos frescos del bucket
97
- try:
98
- from modules.semantic_cache import invalidate_cache
99
- invalidate_cache()
100
- except Exception:
101
- pass
102
  from modules.agent_orchestrator import run_agent
103
  start = time.time()
104
- response = run_agent(
105
- user_question=query,
106
- history=[],
107
- stream_placeholder=None
108
- )
109
- latencia = int((time.time() - start) * 1000)
110
  return {
111
  "response": response,
112
  "modelo": "Agente Real · 7 tools · NVIDIA H100 + Groq LPU",
113
- "latencia_ms": latencia,
114
  }
115
  except Exception as e:
116
- # Fallback si el agente falla
117
  return call_llm_fallback(query, error=str(e))
118
 
119
  def call_llm_fallback(query: str, error: str = "") -> dict:
120
- """Fallback con datos reales + LLM cuando el agente no está disponible."""
121
  facts = []
122
  for serie_id, nombre in BANXICO_SERIES.items():
123
  d = fetch_banxico(serie_id)
124
  if d.get("valor"):
125
  facts.append(f"• {nombre}: {d['valor']} ({d['fecha']}) — Fuente: Banxico")
126
- wb_map = {
127
- "NY.GDP.MKTP.CD": "PIB México",
128
- "FP.CPI.TOTL.ZG": "Inflación anual %",
129
- "SL.UEM.TOTL.ZS": "Desempleo %",
130
- }
131
  for ind, nombre in wb_map.items():
132
  d = fetch_worldbank(ind)
133
  if d.get("valor"):
134
- val = d["valor"]
135
  if ind == "NY.GDP.MKTP.CD":
136
- val = f"${val/1e12:.2f} billones USD"
 
 
 
137
  else:
138
- val = f"{val:.2f}%"
139
  facts.append(f"• {nombre}: {val} ({d.get('año','')}) — Fuente: World Bank")
140
  facts += [
141
  "• Telcel: 63.4% participación mercado móvil — Fuente: IFT Q3 2024",
142
  "• AT&T México: 17.5% — Fuente: IFT Q3 2024",
143
- "• Movistar: 17.0% vía acuerdo AT&T — Fuente: IFT Q3 2024",
144
  "• Portabilidad H1 2025: Bait +244,024 / AT&T -752,664 — Fuente: IFT",
145
  ]
146
  facts_str = "\n".join(facts)
147
- system = """Eres experto en economía y telecomunicaciones de México.
148
- REGLAS: USA SOLO los datos verificados abajo. NUNCA digas 'no tengo acceso a datos'. Cita la fuente."""
149
- user = f"DATOS VERIFICADOS:\n{facts_str}\n\nPREGUNTA: {query}\n\nResponde usando SOLO los datos de arriba."
150
  if GROQ_API_KEY:
151
  try:
152
  start = time.time()
@@ -160,9 +208,8 @@ REGLAS: USA SOLO los datos verificados abajo. NUNCA digas 'no tengo acceso a dat
160
  timeout=20
161
  )
162
  r.raise_for_status()
163
- data = r.json()
164
  return {
165
- "response": data["choices"][0]["message"]["content"],
166
  "modelo": "Llama 3.3 70B · Groq LPU (fallback)",
167
  "latencia_ms": int((time.time() - start) * 1000),
168
  }
@@ -171,16 +218,14 @@ REGLAS: USA SOLO los datos verificados abajo. NUNCA digas 'no tengo acceso a dat
171
  return {"response": f"Error en agente: {error}", "modelo": "error", "latencia_ms": 0}
172
 
173
  # ── Endpoints ─────────────────────────────────────────────────────────────────
174
-
175
  @app.get("/")
176
  def root():
177
  return {
178
- "name": "Fer Private AI · API",
179
- "version": "5.0.0",
180
- "status": "ok",
181
- "novedad": "v5 — run_agent() importado directamente · mismo cerebro que Streamlit",
182
- "endpoints": ["/health", "/indicadores", "/telco", "/worldbank", "/chat"],
183
- "compute": "NVIDIA H100 · NIM + Groq LPU",
184
  "timestamp": datetime.utcnow().isoformat() + "Z",
185
  }
186
 
@@ -190,11 +235,11 @@ def health():
190
  try:
191
  from modules.agent_orchestrator import run_agent
192
  agent_ok = True
193
- except Exception as e:
194
  pass
195
  return {
196
  "status": "ok",
197
- "version": "5.0.0",
198
  "timestamp": datetime.utcnow().isoformat() + "Z",
199
  "agente_real": "✅ importado correctamente" if agent_ok else "❌ error al importar",
200
  "bucket_data": "✅" if os.path.exists("/data/banxico.json") else "❌ /data no montado",
@@ -207,6 +252,28 @@ def health():
207
  },
208
  }
209
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
210
  @app.get("/indicadores")
211
  def indicadores():
212
  if not BANXICO_TOKEN:
@@ -215,10 +282,28 @@ def indicadores():
215
  for serie_id, nombre in BANXICO_SERIES.items():
216
  d = fetch_banxico(serie_id)
217
  resultados[serie_id] = {"nombre": nombre, "valor": d.get("valor"), "fecha": d.get("fecha")}
 
 
 
 
 
 
 
 
218
  return {
219
- "fuente": "Banxico SIE API",
220
- "timestamp": datetime.utcnow().isoformat() + "Z",
221
- "indicadores": resultados,
 
 
 
 
 
 
 
 
 
 
222
  }
223
 
224
  @app.get("/telco")
 
1
  """
2
+ main.py — Fer Private AI · API REST v5.1
3
  mx-data-api Space · Puerto 7860
4
+ v5.1: Endpoint /questions — fuente única de preguntas para PWA y Streamlit
 
5
  """
6
  import os, requests, time
7
  from datetime import datetime
 
9
  from fastapi.middleware.cors import CORSMiddleware
10
  from pydantic import BaseModel
11
 
12
+ app = FastAPI(title="Fer Private AI · API", version="5.1.0")
13
 
14
  app.add_middleware(
15
  CORSMiddleware,
 
26
 
27
  BANXICO_SERIES = {
28
  "SF43718": "Tipo de cambio USD/MXN (FIX)",
29
+ "SF43783": "TIIE 28 días (%)",
30
  "SF61745": "Tasa objetivo Banxico (%)",
31
  "SP74625": "Inflación general (índice INPC)",
32
  "SF290383": "Reservas internacionales (MDD)",
 
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?",
53
+ "¿Cuál es la TIIE a 28 días actualmente?",
54
+ "¿Cuál es la tasa objetivo del Banco de México?",
55
+ "¿Cuáles son las reservas internacionales de México?",
56
+ "¿Cuál es el INPC según Banxico?",
57
+ "¿Cuál fue el tipo de cambio promedio en 2025?",
58
+ "¿Cuál fue el máximo del tipo de cambio en 2024?",
59
+ "¿Cuál fue el mínimo del tipo de cambio en 2025?",
60
+ "¿Cuántos recortes de tasa hizo Banxico en 2025?",
61
+ "Dame el histórico del tipo de cambio en 2026",
62
+ ],
63
+ "worldbank": [
64
+ "¿Cuál es el PIB de México según el World Bank?",
65
+ "¿Cuánto creció el PIB de México en 2024?",
66
+ "¿Cuáles son las exportaciones de México?",
67
+ "¿Cuánto recibió México en remesas en 2024?",
68
+ "¿Cuál es la deuda pública de México como % del PIB?",
69
+ "¿Cuál es la inflación de México según el World Bank?",
70
+ "¿Cuánto representa la deuda externa de México en USD?",
71
+ "¿Cuál es el PIB per cápita de México?",
72
+ "¿Cuál es el desempleo de México según el World Bank?",
73
+ "¿Cuánto importa México anualmente?",
74
+ ],
75
+ "inegi": [
76
+ "¿Cuál es el IGAE mensual de México?",
77
+ "¿Cuál es la inflación general de México?",
78
+ "¿Cuál es la tasa de desocupación de México?",
79
+ "¿Cuál es el PIB trimestral de México?",
80
+ "¿Cuántas personas trabajan en México?",
81
+ "¿Cuál es el INPC de México?",
82
+ "¿Cuál es la inflación subyacente de México?",
83
+ "¿Cuántas personas hay en México?",
84
+ "¿Qué es el IGAE y para qué sirve?",
85
+ "¿Cómo está la ocupación en México vs el desempleo?",
86
+ ],
87
+ "telco": [
88
+ "¿Cuál es la participación de mercado de Telcel?",
89
+ "¿Qué operadores tienen red 5G propia en México?",
90
+ "¿Cuánto ingresó el sector telecomunicaciones en México en 2025?",
91
+ "¿Cuál es la diferencia entre Telcel y Bait en términos de red 5G?",
92
+ "¿Cuál fue el saldo de portabilidad de Movistar en H1 2025?",
93
+ "¿Cuántas líneas móviles totales hay en México según el IFT?",
94
+ "¿Cuántos accesos de TV restringida hay en México?",
95
+ "¿Qué son los OMVs y cuáles ofrecen 5G en México?",
96
+ "¿Cuál es la diferencia de ingresos entre Telcel y AT&T México?",
97
+ "¿Cuántas líneas tiene AT&T en México?",
98
+ ],
99
+ "agente": [
100
+ "Dame un resumen económico completo de México",
101
+ "¿Cuál es el tipo de cambio USD/MXN hoy?",
102
+ "¿Cuál es la inflación general de México?",
103
+ "¿Cuál es el IGAE mensual de México?",
104
+ "¿Cuál es la tasa objetivo de Banxico?",
105
+ "¿Cuál es la participación de mercado de Telcel?",
106
+ "¿Cuál es la tasa de desocupación de México?",
107
+ "¿Cuántas personas trabajan en México?",
108
+ "¿Cuál es el PIB de México según el World Bank?",
109
+ "¿Cuál fue el saldo de portabilidad de AT&T en H1 2025?",
110
+ ],
111
+ }
112
+
113
  class ChatRequest(BaseModel):
114
  query: str
115
  session_id: str = "mobile"
 
146
  _agent_loaded = False
147
 
148
  def load_agent():
 
149
  global _agent_loaded
150
  if not _agent_loaded:
151
  try:
 
156
  _agent_loaded = True
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
+ response = run_agent(user_question=query, history=[], stream_placeholder=None)
 
 
 
 
 
164
  return {
165
  "response": response,
166
  "modelo": "Agente Real · 7 tools · NVIDIA H100 + Groq LPU",
167
+ "latencia_ms": int((time.time() - start) * 1000),
168
  }
169
  except Exception as e:
 
170
  return call_llm_fallback(query, error=str(e))
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()
 
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
  }
 
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": "5.1.0",
226
+ "status": "ok",
227
+ "endpoints": ["/health", "/indicadores", "/telco", "/worldbank", "/chat", "/questions"],
228
+ "compute": "NVIDIA H100 · NIM + Groq LPU",
 
229
  "timestamp": datetime.utcnow().isoformat() + "Z",
230
  }
231
 
 
235
  try:
236
  from modules.agent_orchestrator import run_agent
237
  agent_ok = True
238
+ except Exception:
239
  pass
240
  return {
241
  "status": "ok",
242
+ "version": "5.1.0",
243
  "timestamp": datetime.utcnow().isoformat() + "Z",
244
  "agente_real": "✅ importado correctamente" if agent_ok else "❌ error al importar",
245
  "bucket_data": "✅" if os.path.exists("/data/banxico.json") else "❌ /data no montado",
 
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 '{categoria}' no existe. Usa: {list(QUESTIONS.keys())}")
265
+ return {
266
+ "categoria": categoria,
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:
 
282
  for serie_id, nombre in BANXICO_SERIES.items():
283
  d = fetch_banxico(serie_id)
284
  resultados[serie_id] = {"nombre": nombre, "valor": d.get("valor"), "fecha": d.get("fecha")}
285
+
286
+ # Mapear campos para compatibilidad con la PWA
287
+ tc = resultados.get("SF43718", {})
288
+ tiie = resultados.get("SF43783", {})
289
+ tasa = resultados.get("SF61745", {})
290
+ res = resultados.get("SF290383", {})
291
+ inpc = resultados.get("SP74625", {})
292
+
293
  return {
294
+ "fuente": "Banxico SIE API",
295
+ "timestamp": datetime.utcnow().isoformat() + "Z",
296
+ "tipo_cambio_usd_mxn": tc.get("valor"),
297
+ "fecha_tc": tc.get("fecha"),
298
+ "tiie_28_dias": tiie.get("valor"),
299
+ "fecha_tiie": tiie.get("fecha"),
300
+ "tasa_objetivo": tasa.get("valor"),
301
+ "fecha_tasa": tasa.get("fecha"),
302
+ "reservas_internacionales": res.get("valor"),
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")