Spaces:
Sleeping
Sleeping
File size: 33,400 Bytes
24431ef 9f5b985 24431ef 9f5b985 24431ef 9f5b985 24431ef 9f5b985 24431ef 9f5b985 24431ef 9f5b985 24431ef 9f5b985 24431ef 9f5b985 24431ef 9f5b985 24431ef 9f5b985 24431ef 9f5b985 24431ef 9f5b985 24431ef 9f5b985 24431ef 9f5b985 24431ef 9f5b985 24431ef 9f5b985 24431ef 9f5b985 24431ef 9f5b985 24431ef 9f5b985 24431ef | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 | """
Capa 3 · Agent Tools
====================
Tools formales para el orquestador LLaMA 3.1 70B.
Cada tool lee directamente del bucket /data o de fuentes verificadas — cero alucinaciones.
Tools disponibles:
- read_banxico -> /data/banxico.json
- search_historico -> /data/banxico_historico.json
- read_worldbank -> /data/worldbank.json
- read_inegi -> Dataset HF Fercor95mx/mx-data-truth-inegi/inegi.json
- search_wikipedia -> Wikipedia API
- read_ift -> /data/ift.json
"""
import json
import os
from datetime import datetime
DATA_PATH = "/data"
# --- JSON Schema de Tools (para LLaMA tool calling) -------------------------
TOOLS = [
{
"type": "function",
"function": {
"name": "search_web",
"description": "Búsqueda web en tiempo real via Tavily. Úsala cuando el dato no está en el bucket: portabilidad reciente, noticias CRT/ATDT, precios actuales, eventos regulatorios 2025-2026.",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "Términos de búsqueda en español, incluye año y contexto México"},
"max_results": {"type": "integer", "description": "Resultados a retornar (default 3, max 5)"}
},
"required": ["query"]
}
}
},
{
"type": "function",
"function": {
"name": "read_banxico",
"description": (
"Lee /data/banxico.json del bucket HF y devuelve datos exactos "
"de Banxico. Úsala para preguntas sobre tipo de cambio USD/MXN, "
"tasa TIIE, tasa objetivo del Banxico, o inflación IPC. "
"NUNCA inventes estos valores — siempre usa esta tool."
),
"parameters": {
"type": "object",
"properties": {
"indicador": {
"type": "string",
"enum": [
"tipo_cambio_usd_mxn",
"tiie_28_dias",
"tasa_objetivo",
"inflacion_ipc",
"todos"
],
"description": "Indicador específico a consultar. Usa 'todos' para resumen completo."
}
},
"required": ["indicador"]
}
}
},
{
"type": "function",
"function": {
"name": "search_historico",
"description": (
"Busca en /data/banxico_historico.json series históricas 2024-2026. "
"Úsala para preguntas sobre tendencias, evolución en el tiempo, "
"comparaciones entre fechas, o máximos/mínimos históricos."
),
"parameters": {
"type": "object",
"properties": {
"serie": {
"type": "string",
"enum": ["SF43718", "SF43783", "SF61745", "SP1"],
"description": (
"ID de serie Banxico: "
"SF43718=tipo_cambio, SF43783=TIIE_28d, "
"SF61745=tasa_objetivo, SP1=inflacion"
)
},
"fecha_inicio": {
"type": "string",
"description": "Fecha inicio en formato DD/MM/YYYY. Opcional."
},
"fecha_fin": {
"type": "string",
"description": "Fecha fin en formato DD/MM/YYYY. Opcional."
},
"ultimos_n": {
"type": "integer",
"description": "Retornar los últimos N registros. Opcional."
},
"query": {
"type": "string",
"description": "Pregunta semántica para búsqueda en ChromaDB. Opcional."
}
},
"required": ["serie"]
}
}
},
{
"type": "function",
"function": {
"name": "read_worldbank",
"description": (
"Lee /data/worldbank.json con 22 indicadores de México del World Bank "
"en 6 categorías: economía, social, comercio, energía, medio ambiente, gobernanza. "
"Úsala para PIB, desempleo, pobreza, exportaciones, emisiones CO2, etc."
),
"parameters": {
"type": "object",
"properties": {
"categoria": {
"type": "string",
"enum": [
"economia", "social", "comercio",
"energia", "medio_ambiente", "gobernanza", "todos"
],
"description": "Categoría de indicadores. Usa 'todos' para resumen completo."
},
"indicador": {
"type": "string",
"description": "Indicador específico opcional."
}
},
"required": ["categoria"]
}
}
},
{
"type": "function",
"function": {
"name": "search_wikipedia",
"description": (
"Busca información conceptual y contextual en Wikipedia. "
"Úsala para preguntas sobre QUÉ ES algo, CÓMO FUNCIONA, HISTORIA o CONTEXTO. "
"NUNCA la uses para datos numéricos — para eso usa las otras tools."
),
"parameters": {
"type": "object",
"properties": {
"termino": {
"type": "string",
"description": "Término a buscar. Ej: 'TIIE México', 'Banco de México'."
},
"idioma": {
"type": "string",
"enum": ["es", "en"],
"description": "Idioma de búsqueda. Por defecto 'es'."
}
},
"required": ["termino"]
}
}
},
{
"type": "function",
"function": {
"name": "read_inegi",
"description": (
"Lee indicadores del INEGI en tiempo real desde el Dataset HF "
"Fercor95mx/mx-data-truth-inegi (alimentado diariamente por Azure Function). "
"Úsala para preguntas sobre población, IGAE (actividad económica), "
"ocupación/desempleo, índice de precios al consumidor (INPC), "
"PIB trimestral, tasa de desocupación, inflación general y subyacente."
),
"parameters": {
"type": "object",
"properties": {
"indicador": {
"type": "string",
"enum": [
"poblacion",
"igae",
"ocupacion",
"precios",
"pib_trimestral",
"tasa_desocupacion",
"inflacion_general",
"inflacion_subyacente",
"inpc_subyacente",
"todos"
],
"description": (
"Indicador INEGI a consultar. "
"poblacion=población total, igae=actividad económica mensual, "
"ocupacion=población ocupada, precios=INPC general, "
"pib_trimestral=PIB trimestral a precios 2018, "
"tasa_desocupacion=desocupación nacional desestacionalizada, "
"inflacion_general=variación anual INPC, "
"inflacion_subyacente=variación anual subyacente, "
"inpc_subyacente=índice subyacente, "
"todos=todos los indicadores disponibles."
)
}
},
"required": ["indicador"]
}
}
},
{
"type": "function",
"function": {
"name": "read_ift",
"description": (
"Lee /data/ift.json con datos del sector telecomunicaciones México (IFT). "
"Úsala para preguntas sobre: Telcel, AT&T, Movistar, Telmex, "
"participación de mercado móvil, ingresos telco, cobertura 4G/5G, "
"portabilidad numérica, TV restringida, regulación telco, "
"agente económico preponderante, banda ancha. "
"NUNCA inventes datos de telecomunicaciones — siempre usa esta tool."
),
"parameters": {
"type": "object",
"properties": {
"categoria": {
"type": "string",
"enum": [
"ingresos",
"participacion_mercado_movil",
"internet_fijo",
"indicadores_conectividad",
"television",
"portabilidad",
"cobertura_5g",
"regulacion",
"historico",
"todo"
],
"description": (
"Categoría de datos telco: "
"ingresos=Q1 2025 por operador, "
"participacion_mercado_movil=líneas por operador, "
"cobertura_5g=estado 5G/4G, "
"regulacion=AEP y contexto regulatorio, "
"todo=resumen ejecutivo completo."
)
}
},
"required": ["categoria"]
}
}
},
]
# --- Implementación de cada tool ---------------------------------------------
def read_banxico(indicador: str) -> dict:
"""Lee banxico.json y retorna el dato solicitado."""
path = os.path.join(DATA_PATH, "banxico.json")
try:
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
if indicador == "todos":
datos_fmt = {}
for k, v in data.items():
if k in ["fuente", "timestamp", "detalle", "actualizado"]:
continue
if isinstance(v, dict):
continue
try:
n = float(v)
if k == "inflacion_ipc" or k == "SP1":
datos_fmt[k] = f"{n:.3f} (índice base — NO usar como % de inflación)"
elif k in ["tipo_cambio_usd_mxn", "SF43718"]:
datos_fmt[k] = f"{n:.4f} MXN/USD"
elif k in ["tiie_28_dias", "SF43783", "tasa_objetivo", "SF61745"]:
datos_fmt[k] = f"{n:.4f}%"
else:
datos_fmt[k] = v
except (TypeError, ValueError):
datos_fmt[k] = v
return {
"fuente": "Banxico SIE API",
"archivo": "banxico.json",
"fecha_extraccion": data.get("timestamp", data.get("actualizado", "N/A")),
"nota_inflacion": "El campo inflacion_ipc es el ÍNDICE INPC base 2018=100, NO el porcentaje de inflación anual.",
"datos": datos_fmt
}
mapa = {
"tipo_cambio_usd_mxn": ["SF43718", "tipo_cambio", "tipo_cambio_usd_mxn"],
"tiie_28_dias": ["SF43783", "tiie_28_dias", "tiie"],
"tasa_objetivo": ["SF61745", "tasa_objetivo", "tasa_interes"],
"inflacion_ipc": ["SP1", "inflacion_ipc", "inflacion"],
}
claves = mapa.get(indicador, [indicador])
buscar_en = [data, data.get("datos", {}), data.get("detalle", {})]
for fuente_data in buscar_en:
if not isinstance(fuente_data, dict):
continue
for clave in claves:
if clave in fuente_data:
valor = fuente_data[clave]
if isinstance(valor, dict):
fecha = valor.get("fecha", data.get("timestamp", "N/A"))
valor = valor.get("valor", str(valor))
else:
fecha = data.get("timestamp", "N/A")
return {
"fuente": "Banxico SIE API",
"archivo": "banxico.json",
"indicador": indicador,
"valor": valor,
"fecha": fecha,
}
return {
"error": f"Indicador '{indicador}' no encontrado en banxico.json",
"claves_disponibles": list(data.keys()),
}
except FileNotFoundError:
return {"error": "banxico.json no encontrado en /data."}
except Exception as e:
return {"error": str(e)}
def search_historico(serie: str, fecha_inicio: str = None,
fecha_fin: str = None, ultimos_n: int = None,
query: str = None) -> dict:
"""Busca en el histórico de Banxico. JSON directo para estadísticas."""
import re as _re
nombres = {
"SF43718": "Tipo de cambio USD/MXN",
"SF43783": "TIIE 28 días",
"SF61745": "Tasa objetivo Banxico",
"SP1": "Inflación IPC"
}
query_text = query or ""
years_in_query = _re.findall(r"\b(202[0-9])\b", query_text)
is_statistical = any(k in query_text.lower() for k in [
"promedio", "average", "mínimo", "minimo", "máximo", "maximo",
"estadísticas", "estadisticas", "statistics", "media", "mean"
])
use_json = years_in_query or is_statistical or not query_text
if not use_json:
try:
from modules.rag_chroma import search_historico_semantico
result = search_historico_semantico(query_text, serie=serie, n_results=20)
if result and "error" not in result and result.get("total", 0) > 0:
result["nombre"] = nombres.get(serie, serie)
result["tool"] = "ChromaDB · semántico"
result["resultados"] = result.get("resultados", [])[:5]
return result
except Exception:
pass
path = os.path.join(DATA_PATH, "banxico_historico.json")
try:
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
registros = None
for clave in [serie, serie.upper(), serie.lower()]:
if clave in data:
raw = data[clave]
if isinstance(raw, list):
registros = raw
elif isinstance(raw, dict) and "registros" in raw:
registros = raw["registros"]
break
if registros is None:
return {"error": f"Serie '{serie}' no encontrada",
"series_disponibles": [k for k in data.keys() if k not in ["fuente","timestamp","periodo"]]}
if years_in_query:
filtrados = [r for r in registros
if any(yr in str(r.get("fecha","")) for yr in years_in_query)]
if filtrados:
registros = filtrados
if fecha_inicio or fecha_fin:
def parse_f(f):
for fmt in ["%d/%m/%Y", "%Y-%m-%d"]:
try:
return datetime.strptime(f, fmt)
except Exception:
pass
return None
fi = parse_f(fecha_inicio) if fecha_inicio else None
ff = parse_f(fecha_fin) if fecha_fin else None
filtrados2 = []
for r in registros:
fr = parse_f(r.get("fecha",""))
if fr:
if fi and fr < fi: continue
if ff and fr > ff: continue
filtrados2.append(r)
if filtrados2:
registros = filtrados2
if ultimos_n:
registros = registros[-ultimos_n:]
valores = []
for r in registros:
try:
v = str(r.get("dato", r.get("valor", ""))).split(" ")[0].replace(",","")
valores.append(float(v))
except Exception:
pass
stats = {}
if valores:
stats = {
"promedio": round(sum(valores)/len(valores), 4),
"minimo": round(min(valores), 4),
"maximo": round(max(valores), 4),
"primero": valores[0],
"ultimo": valores[-1],
}
return {
"fuente": "Banxico SIE API · Histórico · JSON directo",
"serie": serie,
"nombre": nombres.get(serie, serie),
"años_filtrados": years_in_query or "todos",
"total_registros": len(registros),
"estadisticas": stats,
"muestra": registros[-3:] if len(registros) > 3 else registros
}
except FileNotFoundError:
return {"error": "banxico_historico.json no encontrado en /data."}
except Exception as e:
return {"error": str(e)}
def read_worldbank(categoria: str, indicador: str = None) -> dict:
"""Lee worldbank.json."""
path = os.path.join(DATA_PATH, "worldbank.json")
try:
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
def fmt_num(v, key=""):
try:
n = float(v)
if key in ["pib_usd", "exportaciones_usd", "importaciones_usd",
"remesas_usd", "cuenta_corriente_usd"]:
if abs(n) > 1_000_000_000_000:
return f"${n/1_000_000_000_000:,.3f} billones USD"
elif abs(n) > 1_000_000_000:
return f"${n/1_000_000_000:,.2f} mil millones USD"
elif n > 1_000_000_000:
return f"${n/1_000_000_000:,.2f} B USD"
elif n > 1_000_000:
return f"{n:,.0f}"
return v
except (TypeError, ValueError):
return v
if categoria == "todos":
return {
"fuente": "World Bank API",
"archivo": "worldbank.json",
"fecha_extraccion": data.get("timestamp", "N/A"),
"datos": data
}
resultado = None
for clave in [categoria, categoria.lower(), categoria.upper()]:
if clave in data:
resultado = data[clave]
break
if resultado is None:
todas = {k: v for k, v in data.items()
if k not in ["fuente", "timestamp", "pais"] and isinstance(v, dict)}
if todas:
return {
"fuente": "World Bank API",
"nota": f"Categoría '{categoria}' no encontrada — devolviendo todos los datos",
"datos": todas,
}
return {
"error": f"Categoría '{categoria}' no encontrada",
"categorias_disponibles": [k for k in data.keys() if k not in ["fuente","timestamp","pais"]]
}
if indicador and isinstance(resultado, dict):
for k, v in resultado.items():
if indicador.lower() in k.lower():
return {
"fuente": "World Bank API",
"categoria": categoria,
"indicador": k,
"valor": v
}
if isinstance(resultado, dict):
for k, v in resultado.items():
if isinstance(v, dict) and "valor" in v:
v["valor_formateado"] = fmt_num(v["valor"])
return {
"fuente": "World Bank API",
"archivo": "worldbank.json",
"categoria": categoria,
"datos": resultado
}
except FileNotFoundError:
return {"error": "worldbank.json no encontrado en /data."}
except Exception as e:
return {"error": str(e)}
def read_inegi(indicador: str) -> dict:
"""
Lee inegi.json directamente desde el Dataset HF usando la libreria oficial
huggingface_hub. Version instrumentada: cada etapa queda registrada en
'stage' dentro del resultado de error, para diagnostico sin ambiguedad.
"""
import json as _json
import traceback as _traceback
INEGI_REPO = "Fercor95mx/mx-data-truth-inegi"
HF_TOKEN_LOCAL = os.getenv("HF_TOKEN", "")
stage = "initialization"
try:
stage = "import_huggingface_hub"
from huggingface_hub import HfApi, hf_hub_download
stage = "validate_token_presence"
if not HF_TOKEN_LOCAL:
raise RuntimeError("HF_TOKEN no esta disponible en os.environ dentro de este proceso")
stage = "authenticate_token"
api = HfApi(token=HF_TOKEN_LOCAL)
identity = api.whoami()
print(f"INEGI_AUTH_OK account={identity.get('name')} token_len={len(HF_TOKEN_LOCAL)}", flush=True)
stage = "dataset_metadata"
dataset_info = api.dataset_info(repo_id=INEGI_REPO, revision="main")
stage = "download_inegi_json"
local_path = hf_hub_download(
repo_id=INEGI_REPO,
filename="inegi.json",
repo_type="dataset",
revision=dataset_info.sha,
token=HF_TOKEN_LOCAL,
)
print(f"INEGI_DOWNLOAD_OK path={local_path} sha={dataset_info.sha}", flush=True)
stage = "open_inegi_json"
with open(local_path, "r", encoding="utf-8") as f:
data = _json.load(f)
stage = "build_response"
if indicador == "todos":
return {
"ok": True,
"fuente": "INEGI · Banco de Información Económica (BIE-BISE) · Azure extractor",
"archivo": f"inegi.json (Dataset {INEGI_REPO})",
"fecha_extraccion": data.get("timestamp", "N/A"),
"dataset_revision": dataset_info.sha,
"datos": data
}
mapa = {
# Indicadores originales
"poblacion": "poblacion_total",
"igae": "igae_mensual",
"ocupacion": "poblacion_ocupada",
"precios": "inpc",
# Indicadores nuevos (los 9 que extrae Azure Function)
"pib_trimestral": "pib_trimestral",
"tasa_desocupacion": "tasa_desocupacion",
"inflacion_general": "inflacion_general",
"inflacion_subyacente":"inflacion_subyacente",
"inpc_subyacente": "inpc_subyacente",
}
clave = mapa.get(indicador, indicador)
if clave in data:
indicador_data = data[clave]
return {
"ok": True,
"fuente": indicador_data.get("fuente", "INEGI"),
"archivo": f"inegi.json (Dataset {INEGI_REPO})",
"indicador": indicador,
"clave": clave,
"nombre": indicador_data.get("nombre", clave),
"valor": indicador_data.get("valor"),
"fecha": indicador_data.get("fecha"),
"unidad": indicador_data.get("unidad"),
"variacion_pct": indicador_data.get("variacion_pct"),
"dataset_revision": dataset_info.sha,
"fecha_extraccion": data.get("timestamp", "N/A")
}
claves_disponibles = [
k for k in data.keys()
if k not in ["fuente", "timestamp", "extraido_desde", "nota",
"exitosos", "total_series", "errores"]
]
return {
"ok": False,
"stage": "indicator_lookup",
"error_code": "INDICATOR_NOT_FOUND",
"error": f"Indicador '{indicador}' (clave '{clave}') no encontrado en inegi.json",
"claves_disponibles": claves_disponibles
}
except Exception as exc:
error_result = {
"ok": False,
"stage": stage,
"error_code": "INEGI_READ_FAILED",
"error_type": type(exc).__name__,
"error": str(exc),
"repo_id": INEGI_REPO,
"token_present": bool(HF_TOKEN_LOCAL),
"token_length": len(HF_TOKEN_LOCAL),
}
tb = _traceback.format_exc()
print(f"INEGI_READ_FAILED stage={stage} type={type(exc).__name__} error={str(exc)}", flush=True)
print(tb, flush=True)
# Mantener compatibilidad: el orquestador busca la clave "error"
error_result["error"] = f"[{stage}] {type(exc).__name__}: {str(exc)}"
return error_result
def search_wikipedia(termino: str, idioma: str = "es") -> dict:
"""Busca información conceptual en Wikipedia."""
import requests as _req
try:
url = f"https://{idioma}.wikipedia.org/api/rest_v1/page/summary/{termino.replace(' ', '_')}"
r = _req.get(url, timeout=10, headers={"User-Agent": "MXDataIntelligence/1.0"})
if r.status_code == 404:
search_url = f"https://{idioma}.wikipedia.org/w/api.php"
params = {"action": "opensearch", "search": termino, "limit": 3, "format": "json"}
rs = _req.get(search_url, params=params, timeout=10)
if rs.status_code == 200:
results = rs.json()
if results[1]:
primer = results[1][0].replace(" ", "_")
r2 = _req.get(
f"https://{idioma}.wikipedia.org/api/rest_v1/page/summary/{primer}",
timeout=10, headers={"User-Agent": "MXDataIntelligence/1.0"}
)
if r2.status_code == 200:
data = r2.json()
return {
"fuente": f"Wikipedia ({idioma})",
"termino": termino,
"titulo": data.get("title", ""),
"resumen": data.get("extract", "")[:800],
"url": data.get("content_urls", {}).get("desktop", {}).get("page", ""),
}
return {"error": f"No se encontró '{termino}' en Wikipedia ({idioma})"}
r.raise_for_status()
data = r.json()
return {
"fuente": f"Wikipedia ({idioma})",
"termino": termino,
"titulo": data.get("title", ""),
"resumen": data.get("extract", "")[:800],
"url": data.get("content_urls", {}).get("desktop", {}).get("page", ""),
}
except Exception as e:
return {"error": f"Error consultando Wikipedia: {str(e)}"}
def read_ift(categoria: str = "todo") -> dict:
"""Lee /data/ift.json con datos del sector telecomunicaciones México."""
path = os.path.join(DATA_PATH, "ift.json")
try:
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
CATEGORIA_MAP = {
"ingresos": "ingresos_q1_2025",
"participacion_mercado_movil": "participacion_mercado_movil",
"internet_fijo": "internet_fijo_q1_2025",
"indicadores_conectividad": "indicadores_conectividad",
"television": "television_restringida_q1_2025",
"portabilidad": "portabilidad",
"cobertura_5g": "cobertura_5g",
"regulacion": "contexto_regulatorio",
"historico": "serie_historica_ingresos_sector",
"todo": None,
}
if categoria == "todo":
return {
"fuente": data.get("metadatos", {}).get("fuente", "IFT"),
"periodo": data.get("metadatos", {}).get("periodo", "Q1 2025"),
"nota": data.get("metadatos", {}).get("nota", ""),
"resumen": {
"ingresos_sector_q1_2025_millones_mxn":
data.get("ingresos_q1_2025", {}).get("total_sector_millones_mxn"),
"top_operadores_ingresos": [
{k: v for k, v in op.items()
if k in ("marca", "ingreso_millones_mxn", "participacion_pct")}
for op in data.get("ingresos_q1_2025", {}).get("operadores", [])[:5]
],
"participacion_mercado_movil":
data.get("participacion_mercado_movil"),
"indicadores_conectividad":
data.get("indicadores_conectividad"),
"cobertura_5g":
data.get("cobertura_5g"),
"timestamp": data.get("actualizacion", {}).get("timestamp"),
}
}
key = CATEGORIA_MAP.get(categoria)
if key and key in data:
return {
"fuente": data.get("metadatos", {}).get("fuente", "IFT"),
"periodo": data.get("metadatos", {}).get("periodo", "Q1 2025"),
"categoria": categoria,
"datos": data[key],
}
return {
"error": f"Categoría '{categoria}' no encontrada",
"categorias_disponibles": list(CATEGORIA_MAP.keys()),
}
except FileNotFoundError:
return {
"error": "ift.json no encontrado en /data. Ejecuta data_extractor.py primero.",
"sugerencia": "Ve a Administración → Actualizar datos · Capa 2 en la UI."
}
except Exception as e:
return {"error": str(e)}
# --- Dispatcher: ejecuta la tool por nombre ----------------------------------
def search_web_tool(query: str = "", max_results: int = 3, **kwargs) -> str:
"""Búsqueda web en tiempo real via Tavily API."""
import os, requests as _req
api_key = os.getenv("TAVILY_API_KEY", "")
if not api_key:
return json.dumps({"error": "TAVILY_API_KEY no configurada — agrega el secret en HF Space Settings"})
if not query:
return json.dumps({"error": "query vacía"})
try:
payload = {
"api_key": api_key,
"query": query,
"max_results": min(max_results, 5),
"search_depth": "basic",
"include_answer": True,
"include_domains": [
"ift.org.mx", "crt.gob.mx", "atdt.gob.mx",
"banxico.org.mx", "inegi.org.mx",
"eleconomista.com.mx", "expansion.mx",
"milenio.com", "elfinanciero.com.mx",
"eluniversal.com.mx", "reforma.com"
]
}
r = _req.post("https://api.tavily.com/search", json=payload, timeout=15)
r.raise_for_status()
data = r.json()
results = []
for item in data.get("results", [])[:max_results]:
results.append({
"titulo": item.get("title", ""),
"url": item.get("url", ""),
"snippet": item.get("content", "")[:500],
"fecha": item.get("published_date", "reciente")
})
return json.dumps({
"answer": data.get("answer", ""),
"results": results,
"query": query,
"fuente": "Tavily Web Search · tiempo real"
}, ensure_ascii=False)
except Exception as e:
return json.dumps({"error": str(e)})
def execute_tool(tool_name: str, tool_args: dict) -> str:
"""Recibe nombre y argumentos de la tool call y retorna resultado como JSON string."""
REGISTRY = {
"search_web": search_web_tool,
"read_banxico": read_banxico,
"search_historico": search_historico,
"read_worldbank": read_worldbank,
"read_inegi": read_inegi,
"search_wikipedia": search_wikipedia,
"read_ift": read_ift,
}
fn = REGISTRY.get(tool_name)
if fn is None:
return json.dumps({
"error": f"Tool '{tool_name}' no existe. Tools disponibles: {list(REGISTRY.keys())}"
})
try:
result = fn(**tool_args)
return json.dumps(result, ensure_ascii=False, indent=2)
except TypeError as e:
return json.dumps({"error": f"Argumentos inválidos para '{tool_name}': {str(e)}"})
except Exception as e:
return json.dumps({"error": str(e)}) |