Fercor95mx commited on
Commit
6018772
Β·
verified Β·
1 Parent(s): dc8dd93

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +118 -162
main.py CHANGED
@@ -1,15 +1,21 @@
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
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="5.1.0")
13
 
14
  app.add_middleware(
15
  CORSMiddleware,
@@ -18,35 +24,21 @@ app.add_middleware(
18
  allow_headers=["*"],
19
  )
20
 
21
- NVIDIA_API_KEY = os.getenv("NVIDIA_API_KEY", "")
22
- BANXICO_TOKEN = os.getenv("BANXICO_TOKEN", "")
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
- 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)",
33
- "SF43784": "Tipo de cambio EUR/MXN",
34
- }
35
 
36
- WB_INDICATORS = {
37
- "NY.GDP.MKTP.CD": "PIB MΓ©xico (USD)",
38
- "NY.GDP.PCAP.CD": "PIB per cΓ‘pita (USD)",
39
- "FP.CPI.TOTL.ZG": "InflaciΓ³n anual (%)",
40
- "SL.UEM.TOTL.ZS": "Desempleo (%)",
41
- "NE.EXP.GNFS.ZS": "Exportaciones (% PIB)",
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 = r.json()
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
- def fetch_worldbank(indicator: str) -> dict:
 
 
134
  try:
135
- url = f"https://api.worldbank.org/v2/country/MX/indicator/{indicator}?format=json&mrv=1"
136
- r = requests.get(url, timeout=15)
137
- data = r.json()
138
- if len(data) > 1 and data[1]:
139
- entry = data[1][0]
140
- return {"valor": entry.get("value"), "aΓ±o": entry.get("date")}
141
- except:
 
 
 
 
 
 
 
 
142
  pass
143
- return {}
144
 
145
- # ── Agente real ───────────────────────────────────────────────────────────────
146
- _agent_loaded = False
147
 
148
- def load_agent():
149
- global _agent_loaded
150
- if not _agent_loaded:
151
- try:
152
- from modules.rag_chroma import init_chroma
153
- init_chroma(force=False)
154
- except Exception:
155
- pass
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()
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": "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
 
232
  @app.get("/health")
233
  def health():
234
- agent_ok = False
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",
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 '{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:
280
- raise HTTPException(status_code=503, detail="BANXICO_TOKEN no configurado")
281
  resultados = {}
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", {})
@@ -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
- resultados = {}
332
- for indicator, nombre in WB_INDICATORS.items():
333
- d = fetch_worldbank(indicator)
334
- resultados[indicator] = {"nombre": nombre, "valor": d.get("valor"), "aΓ±o": d.get("aΓ±o")}
335
- return {
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 = call_real_agent(req.query, req.session_id)
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", ""),