Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,7 +1,8 @@
|
|
| 1 |
"""
|
| 2 |
-
main.py β Fer Private AI Β· API REST
|
| 3 |
mx-data-api Space Β· Puerto 7860
|
| 4 |
-
|
|
|
|
| 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="
|
| 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 |
-
# ββ
|
| 85 |
-
|
| 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 |
-
|
| 123 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
-
def call_llm_fallback(query: str) -> dict:
|
| 127 |
-
"""Fallback cuando el agente
|
| 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 |
-
|
| 161 |
-
|
| 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 |
-
|
| 180 |
headers={"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"},
|
| 181 |
-
json={
|
| 182 |
-
"
|
| 183 |
-
"
|
| 184 |
-
|
| 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":
|
| 234 |
-
"version":
|
| 235 |
-
"status":
|
| 236 |
-
"novedad":
|
| 237 |
"endpoints": ["/health", "/indicadores", "/telco", "/worldbank", "/chat"],
|
|
|
|
| 238 |
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 239 |
}
|
| 240 |
|
| 241 |
@app.get("/health")
|
| 242 |
def health():
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 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": "
|
| 264 |
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 265 |
-
"agente_real":
|
|
|
|
| 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 |
|