Spaces:
Runtime error
Runtime error
lll
Browse files- my_tools.py +69 -5
my_tools.py
CHANGED
|
@@ -201,7 +201,12 @@ def analyze_table(table_md: str, question: str) -> str:
|
|
| 201 |
verifica la conmutatividad de la matriz; en otro caso, devuelve el CSV equivalente.
|
| 202 |
"""
|
| 203 |
try:
|
| 204 |
-
lines = [l for l in table_md.splitlines() if l.strip() and '---' not in l]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
rows = [[c.strip() for c in l.strip().strip('|').split('|')] for l in lines]
|
| 206 |
if len(rows) < 2:
|
| 207 |
return "Tabla Markdown mal formateada o vacía."
|
|
@@ -372,10 +377,11 @@ scrape_tool = FunctionTool.from_defaults(
|
|
| 372 |
name="scrape_wiki_table",
|
| 373 |
description="Extrae tabla de sección específica de Wikipedia."
|
| 374 |
)
|
|
|
|
| 375 |
fallback_tool = FunctionTool.from_defaults(
|
| 376 |
-
fn=lambda q: "
|
| 377 |
name="no_tool_solution",
|
| 378 |
-
description="
|
| 379 |
)
|
| 380 |
|
| 381 |
all_tools = [
|
|
@@ -405,7 +411,6 @@ tool_descriptions = "\n".join([
|
|
| 405 |
}.get(t.metadata.name, "")
|
| 406 |
for t in all_tools
|
| 407 |
])
|
| 408 |
-
|
| 409 |
# -------------------------------------------------------------------
|
| 410 |
# 6) PROMPT DE SISTEMA MEJORADO with few-shot examples
|
| 411 |
# -------------------------------------------------------------------
|
|
@@ -413,6 +418,7 @@ system_prompt = f"""
|
|
| 413 |
You are Alfred, a ReAct agent. Your goal is to answer correctly using the available tools.
|
| 414 |
|
| 415 |
Strict guidelines:
|
|
|
|
| 416 |
|
| 417 |
1️. ALWAYS use the available tools first if the question requires information you cannot deduce internally.
|
| 418 |
2️. When a tool is used, ONLY answer based on the tool output. DO NOT add or invent any content not explicitly present in the tool output.
|
|
@@ -482,6 +488,64 @@ alfred_agent = ReActAgent.from_tools(
|
|
| 482 |
handle_parsing_errors=True
|
| 483 |
)
|
| 484 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 485 |
def basic_agent_response(question: str) -> str:
|
| 486 |
"""
|
| 487 |
Detecta "Excel adjunto" o usa ReActAgent.query para el resto.
|
|
@@ -501,4 +565,4 @@ def basic_agent_response(question: str) -> str:
|
|
| 501 |
return "No se generó una respuesta válida."
|
| 502 |
except Exception as e:
|
| 503 |
return f"Error crítico del agente: {e}"
|
| 504 |
-
|
|
|
|
| 201 |
verifica la conmutatividad de la matriz; en otro caso, devuelve el CSV equivalente.
|
| 202 |
"""
|
| 203 |
try:
|
| 204 |
+
#lines = [l for l in table_md.splitlines() if l.strip() and '---' not in l]
|
| 205 |
+
# quitamos separadores y líneas vacías; aseguramos salto tras el encabezado
|
| 206 |
+
lines = [
|
| 207 |
+
l for l in table_md.strip().splitlines()
|
| 208 |
+
if l.strip() and not l.lstrip().startswith('|---')
|
| 209 |
+
]
|
| 210 |
rows = [[c.strip() for c in l.strip().strip('|').split('|')] for l in lines]
|
| 211 |
if len(rows) < 2:
|
| 212 |
return "Tabla Markdown mal formateada o vacía."
|
|
|
|
| 377 |
name="scrape_wiki_table",
|
| 378 |
description="Extrae tabla de sección específica de Wikipedia."
|
| 379 |
)
|
| 380 |
+
|
| 381 |
fallback_tool = FunctionTool.from_defaults(
|
| 382 |
+
fn=lambda q: "I cannot answer with the available tools.",
|
| 383 |
name="no_tool_solution",
|
| 384 |
+
description="Returns the standard sentence when no tool can help."
|
| 385 |
)
|
| 386 |
|
| 387 |
all_tools = [
|
|
|
|
| 411 |
}.get(t.metadata.name, "")
|
| 412 |
for t in all_tools
|
| 413 |
])
|
|
|
|
| 414 |
# -------------------------------------------------------------------
|
| 415 |
# 6) PROMPT DE SISTEMA MEJORADO with few-shot examples
|
| 416 |
# -------------------------------------------------------------------
|
|
|
|
| 418 |
You are Alfred, a ReAct agent. Your goal is to answer correctly using the available tools.
|
| 419 |
|
| 420 |
Strict guidelines:
|
| 421 |
+
STOP: After you output "Observation:", your *very next* message **must** be the final answer and **must** be EXACTLY the observation text unchanged, or the sentence "I cannot answer with the available tools." No extra words.
|
| 422 |
|
| 423 |
1️. ALWAYS use the available tools first if the question requires information you cannot deduce internally.
|
| 424 |
2️. When a tool is used, ONLY answer based on the tool output. DO NOT add or invent any content not explicitly present in the tool output.
|
|
|
|
| 488 |
handle_parsing_errors=True
|
| 489 |
)
|
| 490 |
|
| 491 |
+
# --- auxiliar: extraer observación limpia o fallback ----------
|
| 492 |
+
def _extract_observation(raw: str) -> str:
|
| 493 |
+
"""
|
| 494 |
+
Si el agente produjo un paso con 'Observation:', devuelve exactamente
|
| 495 |
+
ese texto (sin espacios iniciales/finales). De lo contrario devuelve raw.
|
| 496 |
+
"""
|
| 497 |
+
if "Observation:" in raw:
|
| 498 |
+
# ejemplo: "Observation: Verduras: ...\nFinal Answer: ..."
|
| 499 |
+
obs = raw.split("Observation:", 1)[1].strip()
|
| 500 |
+
# cortamos si accidentalmente quedó un "Final Answer:" concatenado
|
| 501 |
+
if "Final Answer:" in obs:
|
| 502 |
+
obs = obs.split("Final Answer:", 1)[0].strip()
|
| 503 |
+
# si el fallback-tool fue llamado, obs ya contiene la frase estándar
|
| 504 |
+
return obs
|
| 505 |
+
return raw.strip()
|
| 506 |
+
|
| 507 |
+
# --------------------------------------------------------------
|
| 508 |
+
|
| 509 |
+
def basic_agent_response(question: str) -> str:
|
| 510 |
+
"""
|
| 511 |
+
- Maneja el caso especial de Excel adjunto.
|
| 512 |
+
- Ejecuta el ReActAgent y limpia la salida para cumplir las reglas SAIA.
|
| 513 |
+
"""
|
| 514 |
+
try:
|
| 515 |
+
lower_q = question.lower()
|
| 516 |
+
|
| 517 |
+
# 1) Caso Excel adjunto ------------------------------------------------
|
| 518 |
+
if "attached excel" in lower_q or "archivo excel" in lower_q:
|
| 519 |
+
excel_result = read_excel_data("data/attached.xlsx")
|
| 520 |
+
return (
|
| 521 |
+
excel_result
|
| 522 |
+
if "Error" not in excel_result
|
| 523 |
+
else "The Excel file is not available."
|
| 524 |
+
)
|
| 525 |
+
|
| 526 |
+
# 2) Ejecutar agente ---------------------------------------------------
|
| 527 |
+
print(f"[DEBUG] ➜ Pregunta: {question}")
|
| 528 |
+
raw_resp = alfred_agent.query(question) # puede ser ChatMessage o str
|
| 529 |
+
|
| 530 |
+
# 3) Normalizar respuesta ---------------------------------------------
|
| 531 |
+
# a) si es ChatMessage
|
| 532 |
+
if hasattr(raw_resp, "response") and raw_resp.response is not None:
|
| 533 |
+
cleaned = _extract_observation(str(raw_resp.response))
|
| 534 |
+
else:
|
| 535 |
+
cleaned = _extract_observation(str(raw_resp))
|
| 536 |
+
|
| 537 |
+
# 4) Garantizar fallback único -----------------------------------------
|
| 538 |
+
if not cleaned:
|
| 539 |
+
cleaned = "I cannot answer with the available tools."
|
| 540 |
+
|
| 541 |
+
return cleaned
|
| 542 |
+
|
| 543 |
+
# 5) Manejo de errores -----------------------------------------------------
|
| 544 |
+
except Exception as e:
|
| 545 |
+
print(f"[ERROR] {e}")
|
| 546 |
+
return "I cannot answer with the available tools."
|
| 547 |
+
|
| 548 |
+
'''
|
| 549 |
def basic_agent_response(question: str) -> str:
|
| 550 |
"""
|
| 551 |
Detecta "Excel adjunto" o usa ReActAgent.query para el resto.
|
|
|
|
| 565 |
return "No se generó una respuesta válida."
|
| 566 |
except Exception as e:
|
| 567 |
return f"Error crítico del agente: {e}"
|
| 568 |
+
'''
|