Spaces:
Sleeping
Sleeping
Update modules/agent_orchestrator.py
Browse files- modules/agent_orchestrator.py +196 -94
modules/agent_orchestrator.py
CHANGED
|
@@ -1,11 +1,13 @@
|
|
| 1 |
"""
|
| 2 |
-
Capa 3 · Orquestador v4
|
| 3 |
=========================================================
|
| 4 |
Modelos:
|
| 5 |
-
- LLaMA 3.1 8B
|
| 6 |
-
- LLaMA 3.1 70B
|
| 7 |
-
- Mixtral 8x7B
|
| 8 |
-
v4.1:
|
|
|
|
|
|
|
| 9 |
"""
|
| 10 |
|
| 11 |
import json
|
|
@@ -20,22 +22,22 @@ from modules.observability import QueryTrace
|
|
| 20 |
NVIDIA_API_KEY = os.getenv("NVIDIA_API_KEY", "")
|
| 21 |
NVIDIA_BASE_URL = "https://integrate.api.nvidia.com/v1"
|
| 22 |
|
| 23 |
-
# Groq
|
| 24 |
GROQ_API_KEY = os.getenv("GROQ_API_KEY", "")
|
| 25 |
GROQ_BASE_URL = "https://api.groq.com/openai/v1"
|
| 26 |
|
| 27 |
-
# Tavily
|
| 28 |
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY", "")
|
| 29 |
TAVILY_URL = "https://api.tavily.com/search"
|
| 30 |
|
| 31 |
-
#
|
| 32 |
-
MODEL_CLASSIFIER = "meta/llama-3.1-8b-instruct" # Clasificador SIMPLE/
|
| 33 |
-
MODEL_NUMERICAL = "llama-3.3-70b-versatile"
|
| 34 |
-
MODEL_NARRATIVE = "meta/llama-3.1-70b-instruct"
|
| 35 |
-
MODEL_VALIDATOR = "meta/llama-3.1-8b-instruct"
|
| 36 |
-
MODEL_SYNTHESIS = "meta/llama-3.1-70b-instruct"
|
| 37 |
|
| 38 |
-
#
|
| 39 |
SYSTEM_STRICT = """Eres el Agente Económico de la plataforma MX Data Intelligence.
|
| 40 |
Tu objetivo es proveer datos macroeconómicos y de telecomunicaciones de México 100% verídicos.
|
| 41 |
Fuentes oficiales: Banxico, World Bank, INEGI, IFT.
|
|
@@ -70,7 +72,13 @@ REGLAS ESTRICTAS — sin excepciones:
|
|
| 70 |
NUNCA atribuyas datos semestrales a un reporte Q1. Son períodos diferentes.
|
| 71 |
Si preguntan por Q1 específico: "El reporte IFT Q1 2025 no desglosa saldos numéricos de portabilidad. El dato disponible es el consolidado H1 2025."
|
| 72 |
Si preguntan por período no disponible: "No tengo ese dato. Consulta ift.org.mx/portabilidad"
|
| 73 |
-
15.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
"""
|
| 75 |
|
| 76 |
PROMPT_CLASSIFIER = """Clasifica esta pregunta económica en UNA de estas 3 categorías:
|
|
@@ -103,7 +111,7 @@ MULTI_KEYWORDS = [
|
|
| 103 |
"multi", "completo", "integral", "compara", "vs", "versus"
|
| 104 |
]
|
| 105 |
|
| 106 |
-
#
|
| 107 |
TELCO_KEYWORDS = [
|
| 108 |
"telcel", "att", "at&t", "movistar", "telmex", "telnorte",
|
| 109 |
"telecomunicaciones", "telco", "telefonia movil", "telefonía móvil",
|
|
@@ -118,8 +126,19 @@ TELCO_KEYWORDS = [
|
|
| 118 |
"agente economico preponderante", "aep telecom",
|
| 119 |
]
|
| 120 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
-
#
|
| 123 |
|
| 124 |
def needs_multi_source(question: str) -> bool:
|
| 125 |
q = question.lower()
|
|
@@ -134,7 +153,7 @@ def needs_multi_source(question: str) -> bool:
|
|
| 134 |
_current_trace = None
|
| 135 |
|
| 136 |
def call_model(model: str, messages: list, max_tokens: int = 700) -> tuple:
|
| 137 |
-
"""Llamada
|
| 138 |
headers = {
|
| 139 |
"Authorization": f"Bearer {NVIDIA_API_KEY}",
|
| 140 |
"Content-Type": "application/json",
|
|
@@ -157,7 +176,6 @@ def call_model(model: str, messages: list, max_tokens: int = 700) -> tuple:
|
|
| 157 |
r.raise_for_status()
|
| 158 |
data = r.json()
|
| 159 |
result = data["choices"][0]["message"].get("content", "")
|
| 160 |
-
# Track tokens from API response or estimate
|
| 161 |
if _current_trace:
|
| 162 |
usage = data.get("usage", {})
|
| 163 |
input_tokens = usage.get("prompt_tokens", sum(len(m.get("content","")) for m in messages) // 4)
|
|
@@ -174,9 +192,8 @@ def call_model(model: str, messages: list, max_tokens: int = 700) -> tuple:
|
|
| 174 |
|
| 175 |
|
| 176 |
def call_model_groq(model: str, messages: list, max_tokens: int = 700) -> tuple:
|
| 177 |
-
"""Llamada a Groq API
|
| 178 |
if not GROQ_API_KEY:
|
| 179 |
-
# Fallback a NVIDIA si no hay Groq key
|
| 180 |
return call_model("meta/llama-3.1-70b-instruct", messages, max_tokens)
|
| 181 |
headers = {
|
| 182 |
"Authorization": f"Bearer {GROQ_API_KEY}",
|
|
@@ -209,18 +226,16 @@ def call_model_groq(model: str, messages: list, max_tokens: int = 700) -> tuple:
|
|
| 209 |
except requests.exceptions.Timeout:
|
| 210 |
if attempt < 2:
|
| 211 |
continue
|
| 212 |
-
# Fallback a NVIDIA en timeout
|
| 213 |
return call_model("meta/llama-3.1-70b-instruct", messages, max_tokens)
|
| 214 |
except Exception as e:
|
| 215 |
if attempt < 2:
|
| 216 |
continue
|
| 217 |
-
# Fallback a NVIDIA en error
|
| 218 |
return call_model("meta/llama-3.1-70b-instruct", messages, max_tokens)
|
| 219 |
return call_model("meta/llama-3.1-70b-instruct", messages, max_tokens)
|
| 220 |
|
| 221 |
|
| 222 |
def search_web(query: str, max_results: int = 3) -> dict:
|
| 223 |
-
"""
|
| 224 |
if not TAVILY_API_KEY:
|
| 225 |
return {"error": "TAVILY_API_KEY no configurada", "results": []}
|
| 226 |
try:
|
|
@@ -276,22 +291,28 @@ def classify_question(question: str) -> str:
|
|
| 276 |
|
| 277 |
|
| 278 |
async def fetch_tool_async(tool_name: str, args: dict) -> tuple:
|
| 279 |
-
"""Ejecuta una tool de forma
|
| 280 |
loop = asyncio.get_event_loop()
|
| 281 |
result = await loop.run_in_executor(None, execute_tool, tool_name, args)
|
| 282 |
return tool_name, result
|
| 283 |
|
| 284 |
|
| 285 |
async def prefetch_all_parallel(placeholder=None) -> str:
|
| 286 |
-
"""Ejecuta las
|
|
|
|
|
|
|
| 287 |
if placeholder:
|
| 288 |
placeholder.markdown("*Consultando Banxico + World Bank + INEGI en paralelo...*")
|
| 289 |
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 295 |
|
| 296 |
results = await asyncio.gather(*tasks, return_exceptions=True)
|
| 297 |
|
|
@@ -303,7 +324,6 @@ async def prefetch_all_parallel(placeholder=None) -> str:
|
|
| 303 |
"alfabetizacion_pct", "acceso_electricidad_pct", "area_forestal_pct"]
|
| 304 |
|
| 305 |
def fmt_valor(k, v, meta=None):
|
| 306 |
-
# FIX v4: usar valor_fmt_es del World Bank si está disponible
|
| 307 |
if isinstance(meta, dict) and "valor_fmt_es" in meta:
|
| 308 |
return meta["valor_fmt_es"]
|
| 309 |
try:
|
|
@@ -327,13 +347,31 @@ async def prefetch_all_parallel(placeholder=None) -> str:
|
|
| 327 |
except (TypeError, ValueError):
|
| 328 |
return v
|
| 329 |
|
|
|
|
|
|
|
| 330 |
for tool_name, result in results:
|
| 331 |
label = labels.get(tool_name, tool_name)
|
| 332 |
if isinstance(result, Exception):
|
| 333 |
-
|
|
|
|
| 334 |
continue
|
| 335 |
try:
|
| 336 |
-
data
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 337 |
datos = data.get("datos", data.get("datos_disponibles", data))
|
| 338 |
if isinstance(datos, dict):
|
| 339 |
resumen = {}
|
|
@@ -349,18 +387,22 @@ async def prefetch_all_parallel(placeholder=None) -> str:
|
|
| 349 |
else:
|
| 350 |
parts.append(f"[{label}]: {str(datos)[:300]}")
|
| 351 |
except Exception as e:
|
| 352 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 353 |
|
| 354 |
return "\n".join(parts)
|
| 355 |
|
| 356 |
|
| 357 |
def validate_response(response: str, data_context: str, question: str = "") -> str:
|
| 358 |
"""
|
| 359 |
-
|
| 360 |
-
1. Critic-Loop Python
|
| 361 |
-
2. LLaMA 8B
|
| 362 |
"""
|
| 363 |
-
# Paso 1: Critic-Loop matemático (Python, sin LLM)
|
| 364 |
raw_data = load_raw_data_for_validation()
|
| 365 |
final, iterations, n_errors = critic_loop(
|
| 366 |
draft=response,
|
|
@@ -370,10 +412,8 @@ def validate_response(response: str, data_context: str, question: str = "") -> s
|
|
| 370 |
model=MODEL_VALIDATOR,
|
| 371 |
system_prompt=SYSTEM_STRICT,
|
| 372 |
)
|
| 373 |
-
# Si el critic loop corrigió algo, usar esa versión
|
| 374 |
response = final
|
| 375 |
|
| 376 |
-
# Paso 2: LLaMA 8B — validación semántica
|
| 377 |
msgs = [
|
| 378 |
{"role": "system", "content": PROMPT_VALIDATOR},
|
| 379 |
{"role": "user", "content": f"DATOS REALES:\n{data_context}\n\nRESPUESTA A VALIDAR:\n{response}"}
|
|
@@ -385,7 +425,7 @@ def validate_response(response: str, data_context: str, question: str = "") -> s
|
|
| 385 |
|
| 386 |
|
| 387 |
def synthesize_response(data_context: str, question: str, placeholder=None) -> str:
|
| 388 |
-
"""LLaMA 70B redacta la respuesta final
|
| 389 |
if placeholder:
|
| 390 |
placeholder.markdown("*Redactando respuesta final...*")
|
| 391 |
|
|
@@ -409,7 +449,7 @@ def synthesize_response(data_context: str, question: str, placeholder=None) -> s
|
|
| 409 |
return answer
|
| 410 |
|
| 411 |
|
| 412 |
-
#
|
| 413 |
|
| 414 |
def call_llm_with_tools(messages: list, stream_placeholder=None) -> str:
|
| 415 |
if not NVIDIA_API_KEY:
|
|
@@ -417,64 +457,139 @@ def call_llm_with_tools(messages: list, stream_placeholder=None) -> str:
|
|
| 417 |
|
| 418 |
user_question = messages[-1].get("content", "") if messages else ""
|
| 419 |
|
| 420 |
-
#
|
| 421 |
cached = get_cached(user_question)
|
| 422 |
if cached:
|
| 423 |
if stream_placeholder:
|
| 424 |
stream_placeholder.markdown(cached)
|
| 425 |
return cached
|
| 426 |
|
| 427 |
-
#
|
| 428 |
global _current_trace
|
| 429 |
trace = QueryTrace(user_question)
|
| 430 |
_current_trace = trace
|
| 431 |
|
| 432 |
-
#
|
| 433 |
import re as _re_orch
|
| 434 |
q_lower = user_question.lower()
|
| 435 |
|
| 436 |
-
#
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
]
|
| 443 |
is_inegi = any(k in q_lower for k in INEGI_KEYWORDS)
|
| 444 |
if is_inegi:
|
| 445 |
if stream_placeholder:
|
| 446 |
-
stream_placeholder.markdown("*Consulta INEGI →
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
)
|
| 456 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 457 |
msgs_inegi = [
|
| 458 |
{"role": "system", "content": SYSTEM_STRICT},
|
| 459 |
{"role": "user", "content":
|
| 460 |
-
f"
|
| 461 |
-
f"
|
| 462 |
-
f"
|
| 463 |
-
f"NO digas 'no disponible'. Responde en español.\n\n"
|
| 464 |
f"PREGUNTA: {user_question}"
|
| 465 |
}
|
| 466 |
]
|
| 467 |
-
answer_inegi, _ = call_model(MODEL_SYNTHESIS, msgs_inegi, max_tokens=
|
| 468 |
-
result_inegi = answer_inegi or
|
| 469 |
if stream_placeholder:
|
| 470 |
stream_placeholder.markdown(result_inegi)
|
| 471 |
-
trace.set_route("INEGI")
|
| 472 |
trace.finish()
|
| 473 |
_current_trace = None
|
| 474 |
set_cached(user_question, result_inegi)
|
| 475 |
return result_inegi
|
| 476 |
|
| 477 |
-
#
|
| 478 |
WB_KEYWORDS = [
|
| 479 |
"exportaciones", "exportacion", "importaciones", "importacion",
|
| 480 |
"world bank", "banco mundial", "worldbank", "remesas",
|
|
@@ -488,7 +603,6 @@ def call_llm_with_tools(messages: list, stream_placeholder=None) -> str:
|
|
| 488 |
if is_worldbank:
|
| 489 |
if stream_placeholder:
|
| 490 |
stream_placeholder.markdown("*Consulta World Bank → bucket directo...*")
|
| 491 |
-
# Detectar categoría específica
|
| 492 |
if any(k in q_lower for k in ["exportacion", "importacion", "remesa", "cuenta corriente", "comercio"]):
|
| 493 |
cat_wb = "comercio"
|
| 494 |
elif any(k in q_lower for k in ["pobreza", "poblacion", "desempleo", "alfabetizacion", "social"]):
|
|
@@ -500,18 +614,11 @@ def call_llm_with_tools(messages: list, stream_placeholder=None) -> str:
|
|
| 500 |
elif any(k in q_lower for k in ["energia", "petroleo"]):
|
| 501 |
cat_wb = "energia"
|
| 502 |
else:
|
| 503 |
-
cat_wb = "todos"
|
| 504 |
raw = execute_tool("read_worldbank", {"categoria": cat_wb})
|
| 505 |
-
# Si pregunta sobre población, agregar categoría social explícitamente
|
| 506 |
if any(k in q_lower for k in ["poblacion", "población", "personas", "habitantes"]):
|
| 507 |
raw_social = execute_tool("read_worldbank", {"categoria": "social"})
|
| 508 |
raw = raw + "\n[SOCIAL WB]:\n" + raw_social
|
| 509 |
-
raw += (
|
| 510 |
-
"\nNOTA: En los datos de World Bank, busca el indicador 'poblacion_total' "
|
| 511 |
-
"o 'SP.POP.TOTL'. La población total de México es aproximadamente 130 millones "
|
| 512 |
-
"de personas según el indicador SP.POP.TOTL del Banco Mundial. "
|
| 513 |
-
"USA ese dato para responder."
|
| 514 |
-
)
|
| 515 |
trace.set_route("WORLDBANK")
|
| 516 |
trace.add_tool("read_worldbank")
|
| 517 |
result_wb = synthesize_response(raw[:3000], user_question, stream_placeholder)
|
|
@@ -519,12 +626,11 @@ def call_llm_with_tools(messages: list, stream_placeholder=None) -> str:
|
|
| 519 |
set_cached(user_question, result_wb)
|
| 520 |
return result_wb
|
| 521 |
|
| 522 |
-
#
|
| 523 |
is_telco = any(k in q_lower for k in TELCO_KEYWORDS)
|
| 524 |
if is_telco:
|
| 525 |
if stream_placeholder:
|
| 526 |
stream_placeholder.markdown("*Consulta telco → IFT datos abiertos...*")
|
| 527 |
-
# Preguntas de análisis cruzado → siempre "todo" para tener todos los datos
|
| 528 |
is_cross = any(k in q_lower for k in [
|
| 529 |
"relacion", "relación", "entre", "compara", "vs", "versus",
|
| 530 |
"y el", "e ingreso", "e ingresos", "analisis", "análisis", "resumen"
|
|
@@ -538,7 +644,6 @@ def call_llm_with_tools(messages: list, stream_placeholder=None) -> str:
|
|
| 538 |
elif any(k in q_lower for k in ["ingres", "revenue", "factur"]):
|
| 539 |
categoria_ift = "ingresos"
|
| 540 |
elif any(k in q_lower for k in ["portabilidad"]):
|
| 541 |
-
# PORTABILIDAD: datos hardcodeados verificados — sin LLM para evitar alucinaciones
|
| 542 |
result_port = (
|
| 543 |
"**Portabilidad Numérica México — Datos verificados H1 2025**\n\n"
|
| 544 |
"| Operador | Saldo H1 2025 | Resultado |\n"
|
|
@@ -575,7 +680,7 @@ def call_llm_with_tools(messages: list, stream_placeholder=None) -> str:
|
|
| 575 |
set_cached(user_question, result_telco)
|
| 576 |
return result_telco
|
| 577 |
|
| 578 |
-
#
|
| 579 |
years_found = _re_orch.findall(r"\b(202[0-9])\b", user_question)
|
| 580 |
is_historical = bool(years_found) or any(k in q_lower for k in [
|
| 581 |
"promedio", "histórico", "historico", "average", "mínimo", "minimo",
|
|
@@ -584,7 +689,7 @@ def call_llm_with_tools(messages: list, stream_placeholder=None) -> str:
|
|
| 584 |
"sf43718", "sf43783", "sf61745", "sp1", "serie", "2024", "2025"
|
| 585 |
])
|
| 586 |
|
| 587 |
-
#
|
| 588 |
if stream_placeholder:
|
| 589 |
stream_placeholder.markdown("*Clasificando pregunta...*")
|
| 590 |
|
|
@@ -593,7 +698,7 @@ def call_llm_with_tools(messages: list, stream_placeholder=None) -> str:
|
|
| 593 |
else:
|
| 594 |
complexity = classify_question(user_question)
|
| 595 |
|
| 596 |
-
#
|
| 597 |
if complexity == "SIMPLE":
|
| 598 |
if stream_placeholder:
|
| 599 |
stream_placeholder.markdown("*Consulta simple → bucket directo...*")
|
|
@@ -602,10 +707,7 @@ def call_llm_with_tools(messages: list, stream_placeholder=None) -> str:
|
|
| 602 |
if any(k in q for k in ["poblacion", "población", "personas hay", "habitantes",
|
| 603 |
"igae", "ocupacion", "ocupados", "inegi", "inpc",
|
| 604 |
"desocupacion", "desocupación"]):
|
| 605 |
-
|
| 606 |
-
# Si INEGI no tiene poblacion_total → complementar con World Bank
|
| 607 |
-
raw_wb = execute_tool("read_worldbank", {"categoria": "social"})
|
| 608 |
-
raw = raw_inegi + "\n[WORLD BANK COMPLEMENTO]:\n" + raw_wb
|
| 609 |
elif any(k in q for k in ["tipo de cambio", "exchange", "usd", "mxn", "tasa", "tiie", "inflacion", "inflación"]):
|
| 610 |
raw = execute_tool("read_banxico", {"indicador": "todos"})
|
| 611 |
elif any(k in q for k in ["pib", "gdp", "exportaciones", "exportacion", "importaciones",
|
|
@@ -622,7 +724,7 @@ def call_llm_with_tools(messages: list, stream_placeholder=None) -> str:
|
|
| 622 |
set_cached(user_question, result)
|
| 623 |
return result
|
| 624 |
|
| 625 |
-
#
|
| 626 |
if complexity == "NUMERICA":
|
| 627 |
if stream_placeholder:
|
| 628 |
stream_placeholder.markdown("*Pregunta numérica → histórico...*")
|
|
@@ -702,7 +804,7 @@ def call_llm_with_tools(messages: list, stream_placeholder=None) -> str:
|
|
| 702 |
stream_placeholder.markdown(validated)
|
| 703 |
return validated
|
| 704 |
|
| 705 |
-
#
|
| 706 |
if needs_multi_source(user_question):
|
| 707 |
try:
|
| 708 |
loop = asyncio.get_event_loop()
|
|
@@ -741,7 +843,7 @@ def call_llm_with_tools(messages: list, stream_placeholder=None) -> str:
|
|
| 741 |
stream_placeholder.markdown(validated)
|
| 742 |
return validated
|
| 743 |
|
| 744 |
-
#
|
| 745 |
headers = {
|
| 746 |
"Authorization": f"Bearer {NVIDIA_API_KEY}",
|
| 747 |
"Content-Type": "application/json",
|
|
|
|
| 1 |
"""
|
| 2 |
+
Capa 3 · Orquestador v4 -- Multi-Modelo Anti-Alucinacion
|
| 3 |
=========================================================
|
| 4 |
Modelos:
|
| 5 |
+
- LLaMA 3.1 8B -> Clasificador + Validador
|
| 6 |
+
- LLaMA 3.1 70B -> Analisis numerico, narrativo y sintesis
|
| 7 |
+
- Mixtral 8x7B -> Dashboard
|
| 8 |
+
v4.1: Integracion read_ift (telecomunicaciones Mexico)
|
| 9 |
+
v4.2: Fix bloque INEGI -- eliminada instruccion hardcodeada de poblacion,
|
| 10 |
+
ahora pasa datos reales (IGAE, PIB, INPC, etc.) sin sesgar al LLM.
|
| 11 |
"""
|
| 12 |
|
| 13 |
import json
|
|
|
|
| 22 |
NVIDIA_API_KEY = os.getenv("NVIDIA_API_KEY", "")
|
| 23 |
NVIDIA_BASE_URL = "https://integrate.api.nvidia.com/v1"
|
| 24 |
|
| 25 |
+
# Groq -- Llama 3.3 70B numerico -- mas rapido
|
| 26 |
GROQ_API_KEY = os.getenv("GROQ_API_KEY", "")
|
| 27 |
GROQ_BASE_URL = "https://api.groq.com/openai/v1"
|
| 28 |
|
| 29 |
+
# Tavily -- busqueda web en tiempo real
|
| 30 |
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY", "")
|
| 31 |
TAVILY_URL = "https://api.tavily.com/search"
|
| 32 |
|
| 33 |
+
# --- Modelos -------------------------------------------------------------------
|
| 34 |
+
MODEL_CLASSIFIER = "meta/llama-3.1-8b-instruct" # Clasificador SIMPLE/NUMERICA/NARRATIVA
|
| 35 |
+
MODEL_NUMERICAL = "llama-3.3-70b-versatile" # Analisis numerico via Groq LPU
|
| 36 |
+
MODEL_NARRATIVE = "meta/llama-3.1-70b-instruct" # Analisis narrativo y contexto complejo
|
| 37 |
+
MODEL_VALIDATOR = "meta/llama-3.1-8b-instruct" # Validador anti-alucinacion
|
| 38 |
+
MODEL_SYNTHESIS = "meta/llama-3.1-70b-instruct" # Sintesis final bilingue
|
| 39 |
|
| 40 |
+
# --- System prompts --------------------------------------------------------------
|
| 41 |
SYSTEM_STRICT = """Eres el Agente Económico de la plataforma MX Data Intelligence.
|
| 42 |
Tu objetivo es proveer datos macroeconómicos y de telecomunicaciones de México 100% verídicos.
|
| 43 |
Fuentes oficiales: Banxico, World Bank, INEGI, IFT.
|
|
|
|
| 72 |
NUNCA atribuyas datos semestrales a un reporte Q1. Son períodos diferentes.
|
| 73 |
Si preguntan por Q1 específico: "El reporte IFT Q1 2025 no desglosa saldos numéricos de portabilidad. El dato disponible es el consolidado H1 2025."
|
| 74 |
Si preguntan por período no disponible: "No tengo ese dato. Consulta ift.org.mx/portabilidad"
|
| 75 |
+
15. INEGI — CRÍTICO: Los datos de INEGI (población, IGAE, PIB trimestral, INPC, tasa de desocupación,
|
| 76 |
+
inflación general y subyacente) provienen del Dataset HF Fercor95mx/mx-data-truth-inegi, alimentado
|
| 77 |
+
diariamente por extracción directa del Banco de Información Económica (BIE-BISE) del INEGI.
|
| 78 |
+
Usa el valor, fecha y unidad EXACTOS que vengan en los datos — nunca inventes ni asumas un valor
|
| 79 |
+
de tu conocimiento general, aunque te parezca plausible. Si el campo solicitado no aparece en los
|
| 80 |
+
datos, dilo explícitamente y sugiere consultar inegi.org.mx — no rellenes con otro indicador distinto.
|
| 81 |
+
16. REGLA GENERAL ANTI-ALUCINACIÓN: Si no tienes el dato exacto en el bucket, responde: "No cuento con ese dato en mi fuente actual. Te recomiendo consultar [fuente oficial]." NUNCA inventes justificaciones de por qué no tienes el dato.
|
| 82 |
"""
|
| 83 |
|
| 84 |
PROMPT_CLASSIFIER = """Clasifica esta pregunta económica en UNA de estas 3 categorías:
|
|
|
|
| 111 |
"multi", "completo", "integral", "compara", "vs", "versus"
|
| 112 |
]
|
| 113 |
|
| 114 |
+
# -- Keywords telecomunicaciones --------------------------------------------------
|
| 115 |
TELCO_KEYWORDS = [
|
| 116 |
"telcel", "att", "at&t", "movistar", "telmex", "telnorte",
|
| 117 |
"telecomunicaciones", "telco", "telefonia movil", "telefonía móvil",
|
|
|
|
| 126 |
"agente economico preponderante", "aep telecom",
|
| 127 |
]
|
| 128 |
|
| 129 |
+
# -- Keywords INEGI -- v4.2: ampliado con los 9 indicadores reales ---------------
|
| 130 |
+
INEGI_KEYWORDS = [
|
| 131 |
+
"poblacion", "población", "personas hay", "cuantas personas",
|
| 132 |
+
"cuántas personas", "habitantes", "igae", "ocupacion", "ocupados",
|
| 133 |
+
"inegi", "inpc", "desocupacion", "desocupación", "actividad economica",
|
| 134 |
+
"actividad económica", "pib trimestral", "producto interno bruto trimestral",
|
| 135 |
+
"tasa de desocupacion", "tasa de desocupación", "inflacion general",
|
| 136 |
+
"inflación general", "inflacion subyacente", "inflación subyacente",
|
| 137 |
+
"indice de precios", "índice de precios", "indice nacional de precios",
|
| 138 |
+
]
|
| 139 |
+
|
| 140 |
|
| 141 |
+
# --- Helpers -----------------------------------------------------------------------
|
| 142 |
|
| 143 |
def needs_multi_source(question: str) -> bool:
|
| 144 |
q = question.lower()
|
|
|
|
| 153 |
_current_trace = None
|
| 154 |
|
| 155 |
def call_model(model: str, messages: list, max_tokens: int = 700) -> tuple:
|
| 156 |
+
"""Llamada generica a cualquier modelo via NVIDIA API."""
|
| 157 |
headers = {
|
| 158 |
"Authorization": f"Bearer {NVIDIA_API_KEY}",
|
| 159 |
"Content-Type": "application/json",
|
|
|
|
| 176 |
r.raise_for_status()
|
| 177 |
data = r.json()
|
| 178 |
result = data["choices"][0]["message"].get("content", "")
|
|
|
|
| 179 |
if _current_trace:
|
| 180 |
usage = data.get("usage", {})
|
| 181 |
input_tokens = usage.get("prompt_tokens", sum(len(m.get("content","")) for m in messages) // 4)
|
|
|
|
| 192 |
|
| 193 |
|
| 194 |
def call_model_groq(model: str, messages: list, max_tokens: int = 700) -> tuple:
|
| 195 |
+
"""Llamada a Groq API -- mas rapido para analisis numerico."""
|
| 196 |
if not GROQ_API_KEY:
|
|
|
|
| 197 |
return call_model("meta/llama-3.1-70b-instruct", messages, max_tokens)
|
| 198 |
headers = {
|
| 199 |
"Authorization": f"Bearer {GROQ_API_KEY}",
|
|
|
|
| 226 |
except requests.exceptions.Timeout:
|
| 227 |
if attempt < 2:
|
| 228 |
continue
|
|
|
|
| 229 |
return call_model("meta/llama-3.1-70b-instruct", messages, max_tokens)
|
| 230 |
except Exception as e:
|
| 231 |
if attempt < 2:
|
| 232 |
continue
|
|
|
|
| 233 |
return call_model("meta/llama-3.1-70b-instruct", messages, max_tokens)
|
| 234 |
return call_model("meta/llama-3.1-70b-instruct", messages, max_tokens)
|
| 235 |
|
| 236 |
|
| 237 |
def search_web(query: str, max_results: int = 3) -> dict:
|
| 238 |
+
"""Busqueda web en tiempo real via Tavily API."""
|
| 239 |
if not TAVILY_API_KEY:
|
| 240 |
return {"error": "TAVILY_API_KEY no configurada", "results": []}
|
| 241 |
try:
|
|
|
|
| 291 |
|
| 292 |
|
| 293 |
async def fetch_tool_async(tool_name: str, args: dict) -> tuple:
|
| 294 |
+
"""Ejecuta una tool de forma asincrona."""
|
| 295 |
loop = asyncio.get_event_loop()
|
| 296 |
result = await loop.run_in_executor(None, execute_tool, tool_name, args)
|
| 297 |
return tool_name, result
|
| 298 |
|
| 299 |
|
| 300 |
async def prefetch_all_parallel(placeholder=None) -> str:
|
| 301 |
+
"""Ejecuta las tools en paralelo con asyncio.gather().
|
| 302 |
+
INEGI: llama indicadores especificos en vez de todos para evitar
|
| 303 |
+
enviar 399 registros historicos al LLM."""
|
| 304 |
if placeholder:
|
| 305 |
placeholder.markdown("*Consultando Banxico + World Bank + INEGI en paralelo...*")
|
| 306 |
|
| 307 |
+
# Indicadores INEGI especificos - NO usar todos (399 registros)
|
| 308 |
+
INEGI_INDS = ["igae", "inflacion_general", "tasa_desocupacion",
|
| 309 |
+
"precios", "pib_trimestral", "ocupacion"]
|
| 310 |
+
|
| 311 |
+
tasks = (
|
| 312 |
+
[fetch_tool_async("read_banxico", {"indicador": "todos"}),
|
| 313 |
+
fetch_tool_async("read_worldbank", {"categoria": "economia"})]
|
| 314 |
+
+ [fetch_tool_async("read_inegi", {"indicador": ind}) for ind in INEGI_INDS]
|
| 315 |
+
)
|
| 316 |
|
| 317 |
results = await asyncio.gather(*tasks, return_exceptions=True)
|
| 318 |
|
|
|
|
| 324 |
"alfabetizacion_pct", "acceso_electricidad_pct", "area_forestal_pct"]
|
| 325 |
|
| 326 |
def fmt_valor(k, v, meta=None):
|
|
|
|
| 327 |
if isinstance(meta, dict) and "valor_fmt_es" in meta:
|
| 328 |
return meta["valor_fmt_es"]
|
| 329 |
try:
|
|
|
|
| 347 |
except (TypeError, ValueError):
|
| 348 |
return v
|
| 349 |
|
| 350 |
+
inegi_parts = [] # acumular resultados INEGI individuales
|
| 351 |
+
|
| 352 |
for tool_name, result in results:
|
| 353 |
label = labels.get(tool_name, tool_name)
|
| 354 |
if isinstance(result, Exception):
|
| 355 |
+
if tool_name != "read_inegi":
|
| 356 |
+
parts.append(f"[{label}]: Error - {result}")
|
| 357 |
continue
|
| 358 |
try:
|
| 359 |
+
data = json.loads(result)
|
| 360 |
+
|
| 361 |
+
# INEGI: cada resultado es un indicador especifico {ok, nombre, valor, fecha, unidad}
|
| 362 |
+
if tool_name == "read_inegi":
|
| 363 |
+
if data.get("ok") and data.get("valor") is not None:
|
| 364 |
+
nombre = data.get("nombre", data.get("indicador", ""))
|
| 365 |
+
valor = data.get("valor")
|
| 366 |
+
fecha = data.get("fecha", "")
|
| 367 |
+
unidad = data.get("unidad", "")
|
| 368 |
+
var = data.get("variacion_pct")
|
| 369 |
+
v_fmt = fmt_valor(nombre, valor)
|
| 370 |
+
var_str = f" ({var:+.2f}% var.anual)" if var is not None else ""
|
| 371 |
+
inegi_parts.append(f"{nombre}={v_fmt}{var_str} [{fecha}]")
|
| 372 |
+
continue
|
| 373 |
+
|
| 374 |
+
# Banxico y World Bank: procesamiento normal
|
| 375 |
datos = data.get("datos", data.get("datos_disponibles", data))
|
| 376 |
if isinstance(datos, dict):
|
| 377 |
resumen = {}
|
|
|
|
| 387 |
else:
|
| 388 |
parts.append(f"[{label}]: {str(datos)[:300]}")
|
| 389 |
except Exception as e:
|
| 390 |
+
if tool_name != "read_inegi":
|
| 391 |
+
parts.append(f"[{label}]: Error procesando - {e}")
|
| 392 |
+
|
| 393 |
+
# Agregar INEGI consolidado
|
| 394 |
+
if inegi_parts:
|
| 395 |
+
parts.append("[INEGI]: " + " | ".join(inegi_parts))
|
| 396 |
|
| 397 |
return "\n".join(parts)
|
| 398 |
|
| 399 |
|
| 400 |
def validate_response(response: str, data_context: str, question: str = "") -> str:
|
| 401 |
"""
|
| 402 |
+
Validacion en 2 pasos:
|
| 403 |
+
1. Critic-Loop Python -- verificacion matematica deterministica (~1ms)
|
| 404 |
+
2. LLaMA 8B -- validacion semantica y de fuentes
|
| 405 |
"""
|
|
|
|
| 406 |
raw_data = load_raw_data_for_validation()
|
| 407 |
final, iterations, n_errors = critic_loop(
|
| 408 |
draft=response,
|
|
|
|
| 412 |
model=MODEL_VALIDATOR,
|
| 413 |
system_prompt=SYSTEM_STRICT,
|
| 414 |
)
|
|
|
|
| 415 |
response = final
|
| 416 |
|
|
|
|
| 417 |
msgs = [
|
| 418 |
{"role": "system", "content": PROMPT_VALIDATOR},
|
| 419 |
{"role": "user", "content": f"DATOS REALES:\n{data_context}\n\nRESPUESTA A VALIDAR:\n{response}"}
|
|
|
|
| 425 |
|
| 426 |
|
| 427 |
def synthesize_response(data_context: str, question: str, placeholder=None) -> str:
|
| 428 |
+
"""LLaMA 70B redacta la respuesta final bilingue."""
|
| 429 |
if placeholder:
|
| 430 |
placeholder.markdown("*Redactando respuesta final...*")
|
| 431 |
|
|
|
|
| 449 |
return answer
|
| 450 |
|
| 451 |
|
| 452 |
+
# --- Orquestador principal --------------------------------------------------------
|
| 453 |
|
| 454 |
def call_llm_with_tools(messages: list, stream_placeholder=None) -> str:
|
| 455 |
if not NVIDIA_API_KEY:
|
|
|
|
| 457 |
|
| 458 |
user_question = messages[-1].get("content", "") if messages else ""
|
| 459 |
|
| 460 |
+
# -- CACHE SEMANTICO -- antes de cualquier procesamiento ----------------------
|
| 461 |
cached = get_cached(user_question)
|
| 462 |
if cached:
|
| 463 |
if stream_placeholder:
|
| 464 |
stream_placeholder.markdown(cached)
|
| 465 |
return cached
|
| 466 |
|
| 467 |
+
# -- TRAZA DE OBSERVABILIDAD --------------------------------------------------
|
| 468 |
global _current_trace
|
| 469 |
trace = QueryTrace(user_question)
|
| 470 |
_current_trace = trace
|
| 471 |
|
| 472 |
+
# -- PASO 0: Pre-clasificacion Python (sin LLM) --------------------------------
|
| 473 |
import re as _re_orch
|
| 474 |
q_lower = user_question.lower()
|
| 475 |
|
| 476 |
+
# -- INEGI: detectar keywords -> responder directo con read_inegi -------------
|
| 477 |
+
# v4.2 FIX: se elimino la instruccion hardcodeada que forzaba al LLM a buscar
|
| 478 |
+
# "128,455,567" -- esa instruccion sesgaba la respuesta sin importar el dato
|
| 479 |
+
# real devuelto por read_inegi(). Ahora se pasan los datos reales (poblacion,
|
| 480 |
+
# IGAE, PIB trimestral, INPC, tasa de desocupacion, inflacion, etc.) sin
|
| 481 |
+
# ninguna instruccion que prejuzgue el contenido.
|
|
|
|
| 482 |
is_inegi = any(k in q_lower for k in INEGI_KEYWORDS)
|
| 483 |
if is_inegi:
|
| 484 |
if stream_placeholder:
|
| 485 |
+
stream_placeholder.markdown("*Consulta INEGI → Dataset HF en tiempo real...*")
|
| 486 |
+
trace.set_route("INEGI")
|
| 487 |
+
trace.add_tool("read_inegi")
|
| 488 |
+
|
| 489 |
+
# Detectar indicador específico para llamar read_inegi con precisión
|
| 490 |
+
# en vez de cargar el JSON completo con "todos" (399 registros = demasiado para el LLM)
|
| 491 |
+
# ORDEN IMPORTANTE: específicos primero, genéricos después
|
| 492 |
+
if any(k in q_lower for k in ["igae", "actividad economica", "actividad económica"]):
|
| 493 |
+
indicador_inegi = "igae"
|
| 494 |
+
elif any(k in q_lower for k in ["pib trimestral", "producto interno bruto trimestral"]):
|
| 495 |
+
indicador_inegi = "pib_trimestral"
|
| 496 |
+
elif any(k in q_lower for k in ["tasa de desocupacion", "tasa de desocupación", "desocupacion", "desocupación"]):
|
| 497 |
+
indicador_inegi = "tasa_desocupacion"
|
| 498 |
+
elif any(k in q_lower for k in ["inflacion general", "inflación general"]):
|
| 499 |
+
indicador_inegi = "inflacion_general"
|
| 500 |
+
elif any(k in q_lower for k in ["inflacion subyacente", "inflación subyacente"]):
|
| 501 |
+
indicador_inegi = "inflacion_subyacente"
|
| 502 |
+
elif any(k in q_lower for k in ["inpc subyacente", "índice nacional de precios subyacente"]):
|
| 503 |
+
indicador_inegi = "inpc_subyacente"
|
| 504 |
+
elif any(k in q_lower for k in ["inpc", "precios al consumidor", "indice de precios", "índice de precios"]):
|
| 505 |
+
# INPC genérico va después de INPC subyacente para evitar captura prematura
|
| 506 |
+
indicador_inegi = "precios"
|
| 507 |
+
elif any(k in q_lower for k in ["ocupacion", "ocupados", "ocupada", "empleo", "trabajan", "personas trabajan", "personas ocupadas"]):
|
| 508 |
+
# ocupacion va antes de poblacion para que "personas trabajan" no active poblacion
|
| 509 |
+
indicador_inegi = "ocupacion"
|
| 510 |
+
elif any(k in q_lower for k in ["poblacion", "población", "habitantes", "personas hay", "cuantas personas", "cuántas personas"]):
|
| 511 |
+
indicador_inegi = "poblacion"
|
| 512 |
+
else:
|
| 513 |
+
indicador_inegi = "todos"
|
| 514 |
+
|
| 515 |
+
raw_inegi = execute_tool("read_inegi", {"indicador": indicador_inegi})
|
| 516 |
+
|
| 517 |
+
# v4.3 FIX: si read_inegi() falla, el error NUNCA se manda al LLM de
|
| 518 |
+
# síntesis -- antes el LLM "suavizaba" errores técnicos (401, descarga
|
| 519 |
+
# fallida, etc.) convirtiéndolos en disculpas genéricas tipo "no tengo
|
| 520 |
+
# información", ocultando el fallo real. Ahora se corta el pipeline
|
| 521 |
+
# y se muestra el error técnico exacto (stage + tipo + mensaje) para
|
| 522 |
+
# poder diagnosticarlo de inmediato.
|
| 523 |
+
try:
|
| 524 |
+
inegi_check = json.loads(raw_inegi)
|
| 525 |
+
except Exception:
|
| 526 |
+
inegi_check = {"error": "respuesta de read_inegi no es JSON válido", "raw": raw_inegi[:300]}
|
| 527 |
+
|
| 528 |
+
if isinstance(inegi_check, dict) and inegi_check.get("error"):
|
| 529 |
+
stage_info = inegi_check.get("stage", "desconocida")
|
| 530 |
+
error_type = inegi_check.get("error_type", "")
|
| 531 |
+
error_msg = inegi_check.get("error", "error desconocido")
|
| 532 |
+
result_inegi = (
|
| 533 |
+
f"⚠️ No fue posible consultar INEGI en este momento.\n\n"
|
| 534 |
+
f"**Detalle técnico:** `{error_type}` en etapa `{stage_info}`\n\n"
|
| 535 |
+
f"`{error_msg}`\n\n"
|
| 536 |
+
f"Este es un error de la integración técnica, no significa que el dato no exista. "
|
| 537 |
+
f"Reintenta en unos segundos o revisa Administración → Debug INEGI."
|
| 538 |
+
)
|
| 539 |
+
if stream_placeholder:
|
| 540 |
+
stream_placeholder.markdown(result_inegi)
|
| 541 |
+
trace.finish()
|
| 542 |
+
_current_trace = None
|
| 543 |
+
# No cachear errores -- para que el próximo intento sí re-ejecute
|
| 544 |
+
return result_inegi
|
| 545 |
+
|
| 546 |
+
# Formatear dato INEGI en lenguaje natural para que el LLM no confunda
|
| 547 |
+
# el JSON tecnico con "dato no publicado"
|
| 548 |
+
try:
|
| 549 |
+
inegi_parsed = json.loads(raw_inegi)
|
| 550 |
+
if inegi_parsed.get("ok") and inegi_parsed.get("valor") is not None:
|
| 551 |
+
nombre = inegi_parsed.get("nombre", inegi_parsed.get("indicador", "indicador"))
|
| 552 |
+
valor = inegi_parsed.get("valor")
|
| 553 |
+
fecha = inegi_parsed.get("fecha", "N/A")
|
| 554 |
+
unidad = inegi_parsed.get("unidad", "")
|
| 555 |
+
fuente = inegi_parsed.get("fuente", "INEGI BIE-BISE")
|
| 556 |
+
var_pct = inegi_parsed.get("variacion_pct")
|
| 557 |
+
var_str = f", variacion anual: {var_pct:+.4f}%" if var_pct is not None else ""
|
| 558 |
+
inegi_context = (
|
| 559 |
+
f"DATO OFICIAL INEGI DISPONIBLE:\n"
|
| 560 |
+
f"Indicador: {nombre}\n"
|
| 561 |
+
f"Valor: {valor}\n"
|
| 562 |
+
f"Fecha: {fecha}\n"
|
| 563 |
+
f"Unidad: {unidad}\n"
|
| 564 |
+
f"Fuente: {fuente}{var_str}\n"
|
| 565 |
+
f"Dataset: Fercor95mx/mx-data-truth-inegi (verificado)\n\n"
|
| 566 |
+
f"INSTRUCCION: El dato EXISTE y esta disponible arriba. "
|
| 567 |
+
f"Usalo EXACTAMENTE como aparece — valor={valor}, fecha={fecha}."
|
| 568 |
+
)
|
| 569 |
+
else:
|
| 570 |
+
inegi_context = f"DATO INEGI:\n{raw_inegi[:1000]}"
|
| 571 |
+
except Exception:
|
| 572 |
+
inegi_context = f"DATO INEGI:\n{raw_inegi[:1000]}"
|
| 573 |
+
|
| 574 |
msgs_inegi = [
|
| 575 |
{"role": "system", "content": SYSTEM_STRICT},
|
| 576 |
{"role": "user", "content":
|
| 577 |
+
f"{inegi_context}\n\n"
|
| 578 |
+
f"Responde la siguiente pregunta usando EXCLUSIVAMENTE el dato mostrado arriba. "
|
| 579 |
+
f"Menciona el valor exacto, la fecha y la fuente. Responde en espanol.\n\n"
|
|
|
|
| 580 |
f"PREGUNTA: {user_question}"
|
| 581 |
}
|
| 582 |
]
|
| 583 |
+
answer_inegi, _ = call_model(MODEL_SYNTHESIS, msgs_inegi, max_tokens=500)
|
| 584 |
+
result_inegi = answer_inegi or raw_inegi[:500]
|
| 585 |
if stream_placeholder:
|
| 586 |
stream_placeholder.markdown(result_inegi)
|
|
|
|
| 587 |
trace.finish()
|
| 588 |
_current_trace = None
|
| 589 |
set_cached(user_question, result_inegi)
|
| 590 |
return result_inegi
|
| 591 |
|
| 592 |
+
# -- WORLD BANK: detectar keywords -> responder directo con read_worldbank ----
|
| 593 |
WB_KEYWORDS = [
|
| 594 |
"exportaciones", "exportacion", "importaciones", "importacion",
|
| 595 |
"world bank", "banco mundial", "worldbank", "remesas",
|
|
|
|
| 603 |
if is_worldbank:
|
| 604 |
if stream_placeholder:
|
| 605 |
stream_placeholder.markdown("*Consulta World Bank → bucket directo...*")
|
|
|
|
| 606 |
if any(k in q_lower for k in ["exportacion", "importacion", "remesa", "cuenta corriente", "comercio"]):
|
| 607 |
cat_wb = "comercio"
|
| 608 |
elif any(k in q_lower for k in ["pobreza", "poblacion", "desempleo", "alfabetizacion", "social"]):
|
|
|
|
| 614 |
elif any(k in q_lower for k in ["energia", "petroleo"]):
|
| 615 |
cat_wb = "energia"
|
| 616 |
else:
|
| 617 |
+
cat_wb = "todos"
|
| 618 |
raw = execute_tool("read_worldbank", {"categoria": cat_wb})
|
|
|
|
| 619 |
if any(k in q_lower for k in ["poblacion", "población", "personas", "habitantes"]):
|
| 620 |
raw_social = execute_tool("read_worldbank", {"categoria": "social"})
|
| 621 |
raw = raw + "\n[SOCIAL WB]:\n" + raw_social
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 622 |
trace.set_route("WORLDBANK")
|
| 623 |
trace.add_tool("read_worldbank")
|
| 624 |
result_wb = synthesize_response(raw[:3000], user_question, stream_placeholder)
|
|
|
|
| 626 |
set_cached(user_question, result_wb)
|
| 627 |
return result_wb
|
| 628 |
|
| 629 |
+
# -- TELCO: detectar keywords IFT -> responder directo con read_ift -----------
|
| 630 |
is_telco = any(k in q_lower for k in TELCO_KEYWORDS)
|
| 631 |
if is_telco:
|
| 632 |
if stream_placeholder:
|
| 633 |
stream_placeholder.markdown("*Consulta telco → IFT datos abiertos...*")
|
|
|
|
| 634 |
is_cross = any(k in q_lower for k in [
|
| 635 |
"relacion", "relación", "entre", "compara", "vs", "versus",
|
| 636 |
"y el", "e ingreso", "e ingresos", "analisis", "análisis", "resumen"
|
|
|
|
| 644 |
elif any(k in q_lower for k in ["ingres", "revenue", "factur"]):
|
| 645 |
categoria_ift = "ingresos"
|
| 646 |
elif any(k in q_lower for k in ["portabilidad"]):
|
|
|
|
| 647 |
result_port = (
|
| 648 |
"**Portabilidad Numérica México — Datos verificados H1 2025**\n\n"
|
| 649 |
"| Operador | Saldo H1 2025 | Resultado |\n"
|
|
|
|
| 680 |
set_cached(user_question, result_telco)
|
| 681 |
return result_telco
|
| 682 |
|
| 683 |
+
# -- HISTORICO: detectar año o keywords estadisticos -> forzar NUMERICA -------
|
| 684 |
years_found = _re_orch.findall(r"\b(202[0-9])\b", user_question)
|
| 685 |
is_historical = bool(years_found) or any(k in q_lower for k in [
|
| 686 |
"promedio", "histórico", "historico", "average", "mínimo", "minimo",
|
|
|
|
| 689 |
"sf43718", "sf43783", "sf61745", "sp1", "serie", "2024", "2025"
|
| 690 |
])
|
| 691 |
|
| 692 |
+
# -- PASO 1: Clasificador LLaMA 8B ---------------------------------------------
|
| 693 |
if stream_placeholder:
|
| 694 |
stream_placeholder.markdown("*Clasificando pregunta...*")
|
| 695 |
|
|
|
|
| 698 |
else:
|
| 699 |
complexity = classify_question(user_question)
|
| 700 |
|
| 701 |
+
# -- PASO 2A: SIMPLE -> bucket directo -----------------------------------------
|
| 702 |
if complexity == "SIMPLE":
|
| 703 |
if stream_placeholder:
|
| 704 |
stream_placeholder.markdown("*Consulta simple → bucket directo...*")
|
|
|
|
| 707 |
if any(k in q for k in ["poblacion", "población", "personas hay", "habitantes",
|
| 708 |
"igae", "ocupacion", "ocupados", "inegi", "inpc",
|
| 709 |
"desocupacion", "desocupación"]):
|
| 710 |
+
raw = execute_tool("read_inegi", {"indicador": "todos"})
|
|
|
|
|
|
|
|
|
|
| 711 |
elif any(k in q for k in ["tipo de cambio", "exchange", "usd", "mxn", "tasa", "tiie", "inflacion", "inflación"]):
|
| 712 |
raw = execute_tool("read_banxico", {"indicador": "todos"})
|
| 713 |
elif any(k in q for k in ["pib", "gdp", "exportaciones", "exportacion", "importaciones",
|
|
|
|
| 724 |
set_cached(user_question, result)
|
| 725 |
return result
|
| 726 |
|
| 727 |
+
# -- PASO 2B: NUMERICA -> LLaMA 70B + historico --------------------------------
|
| 728 |
if complexity == "NUMERICA":
|
| 729 |
if stream_placeholder:
|
| 730 |
stream_placeholder.markdown("*Pregunta numérica → histórico...*")
|
|
|
|
| 804 |
stream_placeholder.markdown(validated)
|
| 805 |
return validated
|
| 806 |
|
| 807 |
+
# -- PASO 2C: NARRATIVA multi-fuente -> paralelo + LLaMA 70B -------------------
|
| 808 |
if needs_multi_source(user_question):
|
| 809 |
try:
|
| 810 |
loop = asyncio.get_event_loop()
|
|
|
|
| 843 |
stream_placeholder.markdown(validated)
|
| 844 |
return validated
|
| 845 |
|
| 846 |
+
# -- PASO 2D: NARRATIVA mono-fuente -> tool calling con LLaMA 70B --------------
|
| 847 |
headers = {
|
| 848 |
"Authorization": f"Bearer {NVIDIA_API_KEY}",
|
| 849 |
"Content-Type": "application/json",
|