Commit
·
af9a042
1
Parent(s):
c5f62ea
quito logica de ejecutar la consulta
Browse files
app.py
CHANGED
|
@@ -542,79 +542,14 @@ async def stream_agent_response(question: str, chat_history: List[List[str]]) ->
|
|
| 542 |
# Check if the response contains an SQL query and it truly looks like SQL
|
| 543 |
sql_query = extract_sql_query(response_text)
|
| 544 |
if sql_query and looks_like_sql(sql_query):
|
| 545 |
-
logger.info(
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
query_result = execute_sql_query(sql_query, db_connection)
|
| 549 |
-
|
| 550 |
-
# Add the query and its result to the response
|
| 551 |
-
response_text += f"\n\n### 🔍 Resultado de la consulta:\n```sql\n{sql_query}\n```\n\n{query_result}"
|
| 552 |
-
|
| 553 |
-
# Try to generate an interactive chart if the result is tabular
|
| 554 |
-
try:
|
| 555 |
-
if isinstance(query_result, str) and '|' in query_result and '---' in query_result:
|
| 556 |
-
# Convert markdown table to DataFrame
|
| 557 |
-
|
| 558 |
-
# Clean up the markdown table
|
| 559 |
-
lines = [line.strip() for line in query_result.split('\n')
|
| 560 |
-
if line.strip() and '---' not in line and '|' in line]
|
| 561 |
-
if len(lines) > 1: # At least header + 1 data row
|
| 562 |
-
# Get column names from the first line
|
| 563 |
-
columns = [col.strip() for col in lines[0].split('|')[1:-1]]
|
| 564 |
-
# Get data rows
|
| 565 |
-
data = []
|
| 566 |
-
for line in lines[1:]:
|
| 567 |
-
values = [val.strip() for val in line.split('|')[1:-1]]
|
| 568 |
-
if len(values) == len(columns):
|
| 569 |
-
data.append(dict(zip(columns, values)))
|
| 570 |
-
|
| 571 |
-
if data and len(columns) >= 2:
|
| 572 |
-
# Determine chart type from user's question (supports pie chart)
|
| 573 |
-
q_lower = question.lower()
|
| 574 |
-
if any(k in q_lower for k in ["gráfico circular", "grafico circular", "pie", "pastel"]):
|
| 575 |
-
desired_type = 'pie'
|
| 576 |
-
elif any(k in q_lower for k in ["línea", "linea", "line"]):
|
| 577 |
-
desired_type = 'line'
|
| 578 |
-
elif any(k in q_lower for k in ["dispersión", "dispersion", "scatter"]):
|
| 579 |
-
desired_type = 'scatter'
|
| 580 |
-
elif any(k in q_lower for k in ["histograma", "histogram"]):
|
| 581 |
-
desired_type = 'histogram'
|
| 582 |
-
else:
|
| 583 |
-
desired_type = 'bar'
|
| 584 |
-
|
| 585 |
-
# Choose x/y columns (assume first is category, second numeric)
|
| 586 |
-
x_col = columns[0]
|
| 587 |
-
# pick first numeric column different to x
|
| 588 |
-
y_col = None
|
| 589 |
-
for col in columns[1:]:
|
| 590 |
-
try:
|
| 591 |
-
pd.to_numeric(data[0][col])
|
| 592 |
-
y_col = col
|
| 593 |
-
break
|
| 594 |
-
except Exception:
|
| 595 |
-
continue
|
| 596 |
-
if y_col:
|
| 597 |
-
chart_fig = generate_chart(
|
| 598 |
-
data=data,
|
| 599 |
-
chart_type=desired_type,
|
| 600 |
-
x=x_col,
|
| 601 |
-
y=y_col,
|
| 602 |
-
title=f"{y_col} por {x_col}"
|
| 603 |
-
)
|
| 604 |
-
if chart_fig is not None:
|
| 605 |
-
logger.info(f"Chart generated from SQL table: type={desired_type}, x={x_col}, y={y_col}, rows={len(data)}")
|
| 606 |
-
chart_state = {"data": data, "x_col": x_col, "y_col": y_col, "title": f"{y_col} por {x_col}", "chart_type": desired_type}
|
| 607 |
-
except Exception as e:
|
| 608 |
-
logger.error(f"Error generating chart: {str(e)}", exc_info=True)
|
| 609 |
-
# Don't fail the whole request if chart generation fails
|
| 610 |
-
response_text += "\n\n⚠️ No se pudo generar la visualización de los datos."
|
| 611 |
-
else:
|
| 612 |
-
response_text += "\n\n⚠️ No se pudo conectar a la base de datos para ejecutar la consulta."
|
| 613 |
elif sql_query and not looks_like_sql(sql_query):
|
| 614 |
logger.info("Detected code block but it does not look like SQL; skipping execution.")
|
| 615 |
|
| 616 |
# If we still have no chart but the user clearly wants one,
|
| 617 |
-
# try a second pass to get ONLY a SQL query from the agent and
|
| 618 |
if chart_fig is None:
|
| 619 |
q_lower = question.lower()
|
| 620 |
wants_chart = any(k in q_lower for k in ["gráfico", "grafico", "chart", "graph", "pastel", "pie"])
|
|
@@ -629,40 +564,12 @@ async def stream_agent_response(question: str, chat_history: List[List[str]]) ->
|
|
| 629 |
sql_only_text = str(sql_only_resp)
|
| 630 |
sql_query2 = extract_sql_query(sql_only_text)
|
| 631 |
if sql_query2 and looks_like_sql(sql_query2):
|
| 632 |
-
logger.info(
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
# Try robust markdown table parse
|
| 639 |
-
data_list = parse_markdown_table(query_result) if isinstance(query_result, str) else None
|
| 640 |
-
if data_list:
|
| 641 |
-
# Infer columns
|
| 642 |
-
columns = list(data_list[0].keys())
|
| 643 |
-
x_col = columns[0]
|
| 644 |
-
y_col = None
|
| 645 |
-
for col in columns[1:]:
|
| 646 |
-
try:
|
| 647 |
-
pd.to_numeric(data_list[0][col])
|
| 648 |
-
y_col = col
|
| 649 |
-
break
|
| 650 |
-
except Exception:
|
| 651 |
-
continue
|
| 652 |
-
if y_col:
|
| 653 |
-
desired_type = 'pie' if any(k in q_lower for k in ["gráfico circular", "grafico circular", "pie", "pastel"]) else 'bar'
|
| 654 |
-
chart_fig = generate_chart(
|
| 655 |
-
data=data_list,
|
| 656 |
-
chart_type=desired_type,
|
| 657 |
-
x=x_col,
|
| 658 |
-
y=y_col,
|
| 659 |
-
title=f"{y_col} por {x_col}"
|
| 660 |
-
)
|
| 661 |
-
if chart_fig is not None:
|
| 662 |
-
logger.info("Chart generated from second-pass SQL execution (markdown parse).")
|
| 663 |
-
chart_state = {"data": data_list, "x_col": x_col, "y_col": y_col, "title": f"{y_col} por {x_col}", "chart_type": desired_type}
|
| 664 |
-
else:
|
| 665 |
-
logger.info("No DB connection on second pass; skipping.")
|
| 666 |
except Exception as e:
|
| 667 |
logger.error(f"Second-pass SQL synthesis failed: {e}")
|
| 668 |
|
|
|
|
| 542 |
# Check if the response contains an SQL query and it truly looks like SQL
|
| 543 |
sql_query = extract_sql_query(response_text)
|
| 544 |
if sql_query and looks_like_sql(sql_query):
|
| 545 |
+
logger.info("SQL query detected; showing as Markdown only (no execution).")
|
| 546 |
+
# Show the SQL as Markdown inside the chatbot, without executing it
|
| 547 |
+
response_text += f"\n\n### 🔍 Resultado de la consulta:\n```sql\n{sql_query}\n```"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 548 |
elif sql_query and not looks_like_sql(sql_query):
|
| 549 |
logger.info("Detected code block but it does not look like SQL; skipping execution.")
|
| 550 |
|
| 551 |
# If we still have no chart but the user clearly wants one,
|
| 552 |
+
# try a second pass to get ONLY a SQL query from the agent and present it as Markdown.
|
| 553 |
if chart_fig is None:
|
| 554 |
q_lower = question.lower()
|
| 555 |
wants_chart = any(k in q_lower for k in ["gráfico", "grafico", "chart", "graph", "pastel", "pie"])
|
|
|
|
| 564 |
sql_only_text = str(sql_only_resp)
|
| 565 |
sql_query2 = extract_sql_query(sql_only_text)
|
| 566 |
if sql_query2 and looks_like_sql(sql_query2):
|
| 567 |
+
logger.info("Second pass SQL detected; showing as Markdown only (no execution).")
|
| 568 |
+
# Append query as Markdown to response_text for visibility
|
| 569 |
+
response_text += (
|
| 570 |
+
f"\n\n### 🔍 Resultado de la consulta (2ª pasada):\n"
|
| 571 |
+
f"```sql\n{sql_query2}\n```"
|
| 572 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 573 |
except Exception as e:
|
| 574 |
logger.error(f"Second-pass SQL synthesis failed: {e}")
|
| 575 |
|