Fercor95mx commited on
Commit
94c76cc
Β·
verified Β·
1 Parent(s): dc6af93

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +223 -0
main.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ main.py β€” Fer Private AI Β· API REST
3
+ mx-data-api Space Β· Puerto 7860
4
+ """
5
+ import os, json, requests
6
+ from pathlib import Path
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="1.0.0")
13
+
14
+ app.add_middleware(
15
+ CORSMiddleware,
16
+ allow_origins=["*"],
17
+ allow_methods=["*"],
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
+ NVIDIA_BASE_URL = "https://integrate.api.nvidia.com/v1"
25
+ GROQ_BASE_URL = "https://api.groq.com/openai/v1"
26
+
27
+ BANXICO_SERIES = {
28
+ "SF43718": "Tipo de cambio USD/MXN (FIX)",
29
+ "SF46410": "TIIE 28 dΓ­as (%)",
30
+ "SF61745": "Tasa objetivo Banxico (%)",
31
+ "SP74625": "InflaciΓ³n general",
32
+ "SF290383": "Reservas internacionales (MDD)",
33
+ }
34
+
35
+ # ── Models ────────────────────────────────────────────────────────────────────
36
+ class ChatRequest(BaseModel):
37
+ query: str
38
+ session_id: str = "mobile"
39
+
40
+ # ── Helpers ───────────────────────────────────────────────────────────────────
41
+ def fetch_banxico_serie(serie_id: str) -> dict:
42
+ url = f"https://www.banxico.org.mx/SieAPIRest/service/v1/series/{serie_id}/datos/oportuno?token={BANXICO_TOKEN}"
43
+ try:
44
+ r = requests.get(url, timeout=15)
45
+ r.raise_for_status()
46
+ import re
47
+ dato = re.search(r"<dato>([\d.]+)</dato>", r.text)
48
+ fecha = re.search(r"<fecha>([\d/]+)</fecha>", r.text)
49
+ return {
50
+ "serie": serie_id,
51
+ "nombre": BANXICO_SERIES.get(serie_id, serie_id),
52
+ "valor": dato.group(1) if dato else None,
53
+ "fecha": fecha.group(1) if fecha else None,
54
+ }
55
+ except Exception as e:
56
+ return {"serie": serie_id, "error": str(e)}
57
+
58
+ def call_llm(prompt: str) -> dict:
59
+ """Intenta Groq primero (rΓ‘pido), fallback a NVIDIA NIM."""
60
+ import time
61
+ # Groq LPU β€” rΓ‘pido para queries numΓ©ricas/simples
62
+ if GROQ_API_KEY:
63
+ try:
64
+ start = time.time()
65
+ headers = {
66
+ "Authorization": f"Bearer {GROQ_API_KEY}",
67
+ "Content-Type": "application/json"
68
+ }
69
+ payload = {
70
+ "model": "llama-3.3-70b-versatile",
71
+ "messages": [
72
+ {"role": "system", "content": "Eres un experto en economΓ­a mexicana. Responde en espaΓ±ol, de forma concisa y precisa."},
73
+ {"role": "user", "content": prompt}
74
+ ],
75
+ "max_tokens": 1024,
76
+ "temperature": 0.3,
77
+ }
78
+ r = requests.post(f"{GROQ_BASE_URL}/chat/completions",
79
+ headers=headers, json=payload, timeout=15)
80
+ r.raise_for_status()
81
+ data = r.json()
82
+ latencia = int((time.time() - start) * 1000)
83
+ return {
84
+ "respuesta": data["choices"][0]["message"]["content"],
85
+ "modelo": "Llama 3.3 70B Β· Groq LPU",
86
+ "latencia_ms": latencia,
87
+ }
88
+ except Exception:
89
+ pass
90
+
91
+ # Fallback NVIDIA NIM β€” LLaMA 70B
92
+ try:
93
+ start = time.time()
94
+ headers = {
95
+ "Authorization": f"Bearer {NVIDIA_API_KEY}",
96
+ "Content-Type": "application/json"
97
+ }
98
+ payload = {
99
+ "model": "meta/llama-3.1-70b-instruct",
100
+ "messages": [
101
+ {"role": "system", "content": "Eres un experto en economΓ­a mexicana. Responde en espaΓ±ol."},
102
+ {"role": "user", "content": prompt}
103
+ ],
104
+ "max_tokens": 1024,
105
+ "temperature": 0.3,
106
+ }
107
+ r = requests.post(f"{NVIDIA_BASE_URL}/chat/completions",
108
+ headers=headers, json=payload, timeout=45)
109
+ r.raise_for_status()
110
+ data = r.json()
111
+ latencia = int((time.time() - start) * 1000)
112
+ return {
113
+ "respuesta": data["choices"][0]["message"]["content"],
114
+ "modelo": "LLaMA 3.1 70B Β· NVIDIA H100",
115
+ "latencia_ms": latencia,
116
+ }
117
+ except Exception as e:
118
+ return {
119
+ "respuesta": f"Error de inferencia: {e}",
120
+ "modelo": "error",
121
+ "latencia_ms": 0,
122
+ }
123
+
124
+ # ── Endpoints ─────────────────────────────────────────────────────────────────
125
+
126
+ @app.get("/")
127
+ def root():
128
+ return {
129
+ "name": "Fer Private AI Β· API",
130
+ "version": "1.0.0",
131
+ "status": "ok",
132
+ "endpoints": ["/health", "/indicadores", "/telco", "/worldbank", "/chat"],
133
+ "compute": "NVIDIA H100 Β· NIM + Groq LPU",
134
+ "timestamp": datetime.utcnow().isoformat() + "Z",
135
+ }
136
+
137
+ @app.get("/health")
138
+ def health():
139
+ return {
140
+ "status": "ok",
141
+ "timestamp": datetime.utcnow().isoformat() + "Z",
142
+ "compute": "NVIDIA H100 Β· NIM",
143
+ "secrets": {
144
+ "NVIDIA_API_KEY": "βœ…" if NVIDIA_API_KEY else "❌",
145
+ "BANXICO_TOKEN": "βœ…" if BANXICO_TOKEN else "❌",
146
+ "GROQ_API_KEY": "βœ…" if GROQ_API_KEY else "❌",
147
+ }
148
+ }
149
+
150
+ @app.get("/indicadores")
151
+ def indicadores():
152
+ if not BANXICO_TOKEN:
153
+ raise HTTPException(status_code=503, detail="BANXICO_TOKEN no configurado")
154
+ resultados = {}
155
+ for serie_id in BANXICO_SERIES:
156
+ resultados[serie_id] = fetch_banxico_serie(serie_id)
157
+ return {
158
+ "fuente": "Banxico SIE API",
159
+ "timestamp": datetime.utcnow().isoformat() + "Z",
160
+ "indicadores": resultados,
161
+ }
162
+
163
+ @app.get("/telco")
164
+ def telco():
165
+ return {
166
+ "fuente": "IFT Β· Instituto Federal de Telecomunicaciones",
167
+ "timestamp": datetime.utcnow().isoformat() + "Z",
168
+ "mercado_movil": {
169
+ "total_lineas_millones": 127.4,
170
+ "periodo": "Q3 2024",
171
+ "operadores": [
172
+ {"operador": "Telcel", "participacion_pct": 63.4},
173
+ {"operador": "AT&T MΓ©xico", "participacion_pct": 17.5},
174
+ {"operador": "Movistar", "participacion_pct": 17.0},
175
+ {"operador": "Otros MVNOs", "participacion_pct": 2.1},
176
+ ]
177
+ },
178
+ "ingresos_q1_2025_millones_mxn": 148541.1,
179
+ "cobertura_4g_pct_poblacion": 92.0,
180
+ "penetracion_5g_pct": 3.5,
181
+ }
182
+
183
+ @app.get("/worldbank")
184
+ def worldbank():
185
+ WB_INDICATORS = {
186
+ "NY.GDP.MKTP.CD": "PIB MΓ©xico (USD)",
187
+ "FP.CPI.TOTL.ZG": "InflaciΓ³n anual (%)",
188
+ "SL.UEM.TOTL.ZS": "Desempleo (%)",
189
+ }
190
+ resultados = {}
191
+ for indicator, nombre in WB_INDICATORS.items():
192
+ try:
193
+ url = f"https://api.worldbank.org/v2/country/MX/indicator/{indicator}?format=json&mrv=1"
194
+ r = requests.get(url, timeout=15)
195
+ data = r.json()
196
+ if len(data) > 1 and data[1]:
197
+ entry = data[1][0]
198
+ resultados[indicator] = {
199
+ "nombre": nombre,
200
+ "valor": entry.get("value"),
201
+ "aΓ±o": entry.get("date"),
202
+ }
203
+ except Exception as e:
204
+ resultados[indicator] = {"nombre": nombre, "error": str(e)}
205
+ return {
206
+ "fuente": "World Bank API",
207
+ "timestamp": datetime.utcnow().isoformat() + "Z",
208
+ "indicadores": resultados,
209
+ }
210
+
211
+ @app.post("/chat")
212
+ def chat(req: ChatRequest):
213
+ if not req.query.strip():
214
+ raise HTTPException(status_code=400, detail="Query vacΓ­a")
215
+ result = call_llm(req.query)
216
+ return {
217
+ "query": req.query,
218
+ "response": result.get("respuesta", ""),
219
+ "modelo": result.get("modelo", ""),
220
+ "latencia_ms": result.get("latencia_ms", 0),
221
+ "timestamp": datetime.utcnow().isoformat() + "Z",
222
+ "infraestructura": "Fer Private AI Β· datos nunca salen de infraestructura privada",
223
+ }