Spaces:
Sleeping
Sleeping
Download modules/agent_tools.py from Fercor95mx/mx-data-api: direct link, hf CLI and curl.
- Browser
- Download file 33.4 kB
-
https://huggingface.co/spaces/Fercor95mx/mx-data-api/resolve/main/modules/agent_tools.py
- Command line
-
hf download hf://spaces/Fercor95mx/mx-data-api/modules/agent_tools.py
-
curl -L -o agent_tools.py https://huggingface.co/spaces/Fercor95mx/mx-data-api/resolve/main/modules/agent_tools.py
33.4 kB
| """ | |
| 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)}) |