Fercor95mx commited on
Commit
732af91
Β·
verified Β·
1 Parent(s): 0b32350

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +62 -133
main.py CHANGED
@@ -1,7 +1,8 @@
1
  """
2
- main.py β€” Fer Private AI Β· API REST v4.1
3
  mx-data-api Space Β· Puerto 7860
4
- v4.1: Usa HF_TOKEN para llamar al Space privado mx-data-intelligence
 
5
  """
6
  import os, requests, time
7
  from datetime import datetime
@@ -9,7 +10,7 @@ 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="4.1.0")
13
 
14
  app.add_middleware(
15
  CORSMiddleware,
@@ -23,10 +24,6 @@ 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
- HF_TOKEN = os.getenv("HF_TOKEN", "")
27
-
28
- # URL pΓΊblica del Space privado β€” accesible con HF_TOKEN
29
- AGENT_URL = "https://fercor95mx-mx-data-intelligence.hf.space"
30
 
31
  BANXICO_SERIES = {
32
  "SF43718": "Tipo de cambio USD/MXN (FIX)",
@@ -46,9 +43,6 @@ WB_INDICATORS = {
46
  "BX.KLT.DINV.WD.GD.ZS": "IED (% PIB)",
47
  }
48
 
49
- GROQ_BASE_URL = "https://api.groq.com/openai/v1"
50
- NVIDIA_BASE_URL = "https://integrate.api.nvidia.com/v1"
51
-
52
  class ChatRequest(BaseModel):
53
  query: str
54
  session_id: str = "mobile"
@@ -81,56 +75,48 @@ def fetch_worldbank(indicator: str) -> dict:
81
  pass
82
  return {}
83
 
84
- # ── Llamada al agente real ────────────────────────────────────────────────────
85
- def call_real_agent(query: str, session_id: str = "mobile") -> dict:
86
- """
87
- Llama al agent_orchestrator.py real en mx-data-intelligence.
88
- Usa HF_TOKEN para autenticaciΓ³n al Space privado.
89
- Usa INTERNAL_API_KEY para autenticaciΓ³n al endpoint /agent/query.
90
- Fallback a LLM bΓ‘sico si el agente no estΓ‘ disponible.
91
- """
92
- if HF_TOKEN and INTERNAL_API_KEY:
93
- try:
94
- start = time.time()
95
- headers = {
96
- "Content-Type": "application/json",
97
- "Authorization": f"Bearer {HF_TOKEN}",
98
- "x-api-key": INTERNAL_API_KEY,
99
- }
100
- payload = {
101
- "query": query,
102
- "session_id": session_id,
103
- "history": [],
104
- }
105
- r = requests.post(
106
- f"{AGENT_URL}/agent/query",
107
- headers=headers,
108
- json=payload,
109
- timeout=120,
110
- )
111
- r.raise_for_status()
112
- data = r.json()
113
- latencia = int((time.time() - start) * 1000)
114
- return {
115
- "response": data.get("response", "Sin respuesta"),
116
- "modelo": "Agente Real Β· 7 tools Β· NVIDIA H100 + Groq LPU",
117
- "latencia_ms": latencia,
118
- }
119
- except Exception as e:
120
- pass # Fallback abajo
121
 
122
- # ── Fallback: datos reales + LLM ─────────────────────────────────────────
123
- return call_llm_fallback(query)
 
 
 
 
 
 
 
 
124
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
 
126
- def call_llm_fallback(query: str) -> dict:
127
- """Fallback cuando el agente real no estΓ‘ disponible."""
128
  facts = []
129
  for serie_id, nombre in BANXICO_SERIES.items():
130
  d = fetch_banxico(serie_id)
131
  if d.get("valor"):
132
  facts.append(f"β€’ {nombre}: {d['valor']} ({d['fecha']}) β€” Fuente: Banxico")
133
-
134
  wb_map = {
135
  "NY.GDP.MKTP.CD": "PIB MΓ©xico",
136
  "FP.CPI.TOTL.ZG": "InflaciΓ³n anual %",
@@ -145,48 +131,26 @@ def call_llm_fallback(query: str) -> dict:
145
  else:
146
  val = f"{val:.2f}%"
147
  facts.append(f"β€’ {nombre}: {val} ({d.get('aΓ±o','')}) β€” Fuente: World Bank")
148
-
149
  facts += [
150
  "β€’ Telcel: 63.4% participaciΓ³n mercado mΓ³vil β€” Fuente: IFT Q3 2024",
151
  "β€’ AT&T MΓ©xico: 17.5% β€” Fuente: IFT Q3 2024",
152
  "β€’ Movistar: 17.0% vΓ­a acuerdo AT&T β€” Fuente: IFT Q3 2024",
153
- "β€’ Ingresos sector telco Q1 2025: 148,541 M MXN β€” Fuente: IFT",
154
  "β€’ Portabilidad H1 2025: Bait +244,024 / AT&T -752,664 β€” Fuente: IFT",
155
- "β€’ AltΓ‘n Redes: 4.5G LTE β€” NO es 5G comercial",
156
  ]
157
-
158
  facts_str = "\n".join(facts)
159
-
160
- system = """Eres un experto en economΓ­a y telecomunicaciones de MΓ©xico.
161
- REGLAS ABSOLUTAS:
162
- 1. USA ÚNICAMENTE los DATOS VERIFICADOS que aparecen abajo
163
- 2. NUNCA digas 'no tengo acceso a datos en tiempo real' β€” los datos ya estΓ‘n aquΓ­
164
- 3. NUNCA inventes cifras β€” si no estΓ‘ en los datos di 'dato no disponible'
165
- 4. Responde en espaΓ±ol, tono ejecutivo
166
- 5. Cita la fuente de cada dato entre parΓ©ntesis"""
167
-
168
- user = f"""DATOS VERIFICADOS EN TIEMPO REAL (fuentes oficiales):
169
- {facts_str}
170
-
171
- PREGUNTA: {query}
172
-
173
- Responde usando ÚNICAMENTE los datos de arriba. Cita la fuente."""
174
-
175
  if GROQ_API_KEY:
176
  try:
177
  start = time.time()
178
  r = requests.post(
179
- f"{GROQ_BASE_URL}/chat/completions",
180
  headers={"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"},
181
- json={
182
- "model": "llama-3.3-70b-versatile",
183
- "messages": [
184
- {"role": "system", "content": system},
185
- {"role": "user", "content": user}
186
- ],
187
- "max_tokens": 1200,
188
- "temperature": 0.1,
189
- },
190
  timeout=20
191
  )
192
  r.raise_for_status()
@@ -198,77 +162,42 @@ Responde usando ÚNICAMENTE los datos de arriba. Cita la fuente."""
198
  }
199
  except:
200
  pass
201
-
202
- try:
203
- start = time.time()
204
- r = requests.post(
205
- f"{NVIDIA_BASE_URL}/chat/completions",
206
- headers={"Authorization": f"Bearer {NVIDIA_API_KEY}", "Content-Type": "application/json"},
207
- json={
208
- "model": "meta/llama-3.1-70b-instruct",
209
- "messages": [
210
- {"role": "system", "content": system},
211
- {"role": "user", "content": user}
212
- ],
213
- "max_tokens": 1200,
214
- "temperature": 0.1,
215
- },
216
- timeout=45
217
- )
218
- r.raise_for_status()
219
- data = r.json()
220
- return {
221
- "response": data["choices"][0]["message"]["content"],
222
- "modelo": "LLaMA 3.1 70B Β· NVIDIA H100 (fallback)",
223
- "latencia_ms": int((time.time() - start) * 1000),
224
- }
225
- except Exception as e:
226
- return {"response": f"Error: {e}", "modelo": "error", "latencia_ms": 0}
227
 
228
  # ── Endpoints ─────────────────────────────────────────────────────────────────
229
 
230
  @app.get("/")
231
  def root():
232
  return {
233
- "name": "Fer Private AI Β· API",
234
- "version": "4.1.0",
235
- "status": "ok",
236
- "novedad": "v4.1 β€” HF_TOKEN para acceso al agente real en Space privado",
237
  "endpoints": ["/health", "/indicadores", "/telco", "/worldbank", "/chat"],
 
238
  "timestamp": datetime.utcnow().isoformat() + "Z",
239
  }
240
 
241
  @app.get("/health")
242
  def health():
243
- agent_status = "❌ no disponible"
244
- if HF_TOKEN and INTERNAL_API_KEY:
245
- try:
246
- r = requests.get(
247
- f"{AGENT_URL}/agent/health",
248
- headers={
249
- "Authorization": f"Bearer {HF_TOKEN}",
250
- "x-api-key": INTERNAL_API_KEY,
251
- },
252
- timeout=15
253
- )
254
- if r.status_code == 200:
255
- agent_status = "βœ… conectado Β· agente real activo"
256
- else:
257
- agent_status = f"⚠️ status {r.status_code}"
258
- except Exception as e:
259
- agent_status = f"⚠️ {str(e)[:50]}"
260
-
261
  return {
262
  "status": "ok",
263
- "version": "4.1.0",
264
  "timestamp": datetime.utcnow().isoformat() + "Z",
265
- "agente_real": agent_status,
 
266
  "secrets": {
267
  "NVIDIA_API_KEY": "βœ…" if NVIDIA_API_KEY else "❌",
268
  "BANXICO_TOKEN": "βœ…" if BANXICO_TOKEN else "❌",
269
  "GROQ_API_KEY": "βœ…" if GROQ_API_KEY else "❌",
 
270
  "INTERNAL_API_KEY": "βœ…" if INTERNAL_API_KEY else "❌",
271
- "HF_TOKEN": "βœ…" if HF_TOKEN else "❌",
272
  },
273
  }
274
 
 
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
  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,
 
24
  GROQ_API_KEY = os.getenv("GROQ_API_KEY", "")
25
  TAVILY_API_KEY = os.getenv("TAVILY_API_KEY", "")
26
  INTERNAL_API_KEY = os.getenv("INTERNAL_API_KEY", "")
 
 
 
 
27
 
28
  BANXICO_SERIES = {
29
  "SF43718": "Tipo de cambio USD/MXN (FIX)",
 
43
  "BX.KLT.DINV.WD.GD.ZS": "IED (% PIB)",
44
  }
45
 
 
 
 
46
  class ChatRequest(BaseModel):
47
  query: str
48
  session_id: str = "mobile"
 
75
  pass
76
  return {}
77
 
78
+ # ── Agente real ───────────────────────────────────────────────────────────────
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:
86
+ from modules.rag_chroma import init_chroma
87
+ init_chroma(force=False)
88
+ except Exception:
89
+ pass
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
+ from modules.agent_orchestrator import run_agent
97
+ start = time.time()
98
+ response = run_agent(
99
+ user_question=query,
100
+ history=[],
101
+ stream_placeholder=None
102
+ )
103
+ latencia = int((time.time() - start) * 1000)
104
+ return {
105
+ "response": response,
106
+ "modelo": "Agente Real Β· 7 tools Β· NVIDIA H100 + Groq LPU",
107
+ "latencia_ms": latencia,
108
+ }
109
+ except Exception as e:
110
+ # Fallback si el agente falla
111
+ return call_llm_fallback(query, error=str(e))
112
 
113
+ def call_llm_fallback(query: str, error: str = "") -> dict:
114
+ """Fallback con datos reales + LLM cuando el agente no estΓ‘ disponible."""
115
  facts = []
116
  for serie_id, nombre in BANXICO_SERIES.items():
117
  d = fetch_banxico(serie_id)
118
  if d.get("valor"):
119
  facts.append(f"β€’ {nombre}: {d['valor']} ({d['fecha']}) β€” Fuente: Banxico")
 
120
  wb_map = {
121
  "NY.GDP.MKTP.CD": "PIB MΓ©xico",
122
  "FP.CPI.TOTL.ZG": "InflaciΓ³n anual %",
 
131
  else:
132
  val = f"{val:.2f}%"
133
  facts.append(f"β€’ {nombre}: {val} ({d.get('aΓ±o','')}) β€” Fuente: World Bank")
 
134
  facts += [
135
  "β€’ Telcel: 63.4% participaciΓ³n mercado mΓ³vil β€” Fuente: IFT Q3 2024",
136
  "β€’ AT&T MΓ©xico: 17.5% β€” Fuente: IFT Q3 2024",
137
  "β€’ Movistar: 17.0% vΓ­a acuerdo AT&T β€” Fuente: IFT Q3 2024",
 
138
  "β€’ Portabilidad H1 2025: Bait +244,024 / AT&T -752,664 β€” Fuente: IFT",
 
139
  ]
 
140
  facts_str = "\n".join(facts)
141
+ system = """Eres experto en economΓ­a y telecomunicaciones de MΓ©xico.
142
+ REGLAS: USA SOLO los datos verificados abajo. NUNCA digas 'no tengo acceso a datos'. Cita la fuente."""
143
+ user = f"DATOS VERIFICADOS:\n{facts_str}\n\nPREGUNTA: {query}\n\nResponde usando SOLO los datos de arriba."
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  if GROQ_API_KEY:
145
  try:
146
  start = time.time()
147
  r = requests.post(
148
+ "https://api.groq.com/openai/v1/chat/completions",
149
  headers={"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"},
150
+ json={"model": "llama-3.3-70b-versatile", "messages": [
151
+ {"role": "system", "content": system},
152
+ {"role": "user", "content": user}
153
+ ], "max_tokens": 1200, "temperature": 0.1},
 
 
 
 
 
154
  timeout=20
155
  )
156
  r.raise_for_status()
 
162
  }
163
  except:
164
  pass
165
+ return {"response": f"Error en agente: {error}", "modelo": "error", "latencia_ms": 0}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
 
167
  # ── Endpoints ─────────────────────────────────────────────────────────────────
168
 
169
  @app.get("/")
170
  def root():
171
  return {
172
+ "name": "Fer Private AI Β· API",
173
+ "version": "5.0.0",
174
+ "status": "ok",
175
+ "novedad": "v5 β€” run_agent() importado directamente Β· mismo cerebro que Streamlit",
176
  "endpoints": ["/health", "/indicadores", "/telco", "/worldbank", "/chat"],
177
+ "compute": "NVIDIA H100 Β· NIM + Groq LPU",
178
  "timestamp": datetime.utcnow().isoformat() + "Z",
179
  }
180
 
181
  @app.get("/health")
182
  def health():
183
+ agent_ok = False
184
+ try:
185
+ from modules.agent_orchestrator import run_agent
186
+ agent_ok = True
187
+ except Exception as e:
188
+ pass
 
 
 
 
 
 
 
 
 
 
 
 
189
  return {
190
  "status": "ok",
191
+ "version": "5.0.0",
192
  "timestamp": datetime.utcnow().isoformat() + "Z",
193
+ "agente_real": "βœ… importado correctamente" if agent_ok else "❌ error al importar",
194
+ "bucket_data": "βœ…" if os.path.exists("/data/banxico.json") else "❌ /data no montado",
195
  "secrets": {
196
  "NVIDIA_API_KEY": "βœ…" if NVIDIA_API_KEY else "❌",
197
  "BANXICO_TOKEN": "βœ…" if BANXICO_TOKEN else "❌",
198
  "GROQ_API_KEY": "βœ…" if GROQ_API_KEY else "❌",
199
+ "TAVILY_API_KEY": "βœ…" if TAVILY_API_KEY else "❌",
200
  "INTERNAL_API_KEY": "βœ…" if INTERNAL_API_KEY else "❌",
 
201
  },
202
  }
203