Jeremy Live commited on
Commit
27ba279
1 Parent(s): 9072687

comento segunda llamada al query

Browse files
Files changed (1) hide show
  1. app.py +59 -59
app.py CHANGED
@@ -564,70 +564,70 @@ async def stream_agent_response(question: str, chat_history: List[List[str]]) ->
564
  else:
565
  response_text = str(response)
566
 
567
- logger.info(f"Extracted response text: {response_text[:200]}...")
568
 
569
- # Check if the response contains an SQL query and it truly looks like SQL
570
- sql_query = extract_sql_query(response_text)
571
- if sql_query and looks_like_sql(sql_query):
572
- logger.info(f"Detected SQL query: {sql_query}")
573
- # Execute the query and update the response
574
- db_connection, _ = setup_database_connection()
575
- if db_connection:
576
- query_result = execute_sql_query(sql_query, db_connection)
577
 
578
- # Add the query and its result to the response
579
- response_text += f"\n\n### 馃攳 Resultado de la consulta:\n```sql\n{sql_query}\n```\n\n{query_result}"
580
 
581
- # Try to generate an interactive chart if the result is tabular
582
- try:
583
- if isinstance(query_result, str) and '|' in query_result and '---' in query_result:
584
- # Convert markdown table to DataFrame
585
 
586
- # Clean up the markdown table
587
- lines = [line.strip() for line in query_result.split('\n')
588
- if line.strip() and '---' not in line and '|' in line]
589
- if len(lines) > 1: # At least header + 1 data row
590
- # Get column names from the first line
591
- columns = [col.strip() for col in lines[0].split('|')[1:-1]]
592
- # Get data rows
593
- data = []
594
- for line in lines[1:]:
595
- values = [val.strip() for val in line.split('|')[1:-1]]
596
- if len(values) == len(columns):
597
- data.append(dict(zip(columns, values)))
598
 
599
- if data and len(columns) >= 2:
600
- # Determine chart type from user's question
601
- _, desired_type = detect_chart_preferences(question)
602
-
603
- # Choose x/y columns (assume first is category, second numeric)
604
- x_col = columns[0]
605
- y_col = columns[1]
606
-
607
- # Coerce numeric values for y
608
- for row in data:
609
- try:
610
- row[y_col] = float(re.sub(r"[^0-9.\-]", "", str(row[y_col])))
611
- except Exception:
612
- pass
613
-
614
- chart_fig = generate_chart(
615
- data=data,
616
- chart_type=desired_type,
617
- x=x_col,
618
- y=y_col,
619
- title=f"{y_col} por {x_col}"
620
- )
621
- if chart_fig is not None:
622
- logger.info(f"Chart generated from SQL table: type={desired_type}, x={x_col}, y={y_col}, rows={len(data)}")
623
- except Exception as e:
624
- logger.error(f"Error generating chart: {str(e)}", exc_info=True)
625
- # Don't fail the whole request if chart generation fails
626
- response_text += "\n\n鈿狅笍 No se pudo generar la visualizaci贸n de los datos."
627
- else:
628
- response_text += "\n\n鈿狅笍 No se pudo conectar a la base de datos para ejecutar la consulta."
629
- elif sql_query and not looks_like_sql(sql_query):
630
- logger.info("Detected code block but it does not look like SQL; skipping execution.")
631
 
632
  # If we still have no chart but the user clearly wants one,
633
  # try a second pass to get ONLY a SQL query from the agent and execute it.
 
564
  else:
565
  response_text = str(response)
566
 
567
+ # logger.info(f"Extracted response text: {response_text[:200]}...")
568
 
569
+ # # Check if the response contains an SQL query and it truly looks like SQL
570
+ # sql_query = extract_sql_query(response_text)
571
+ # if sql_query and looks_like_sql(sql_query):
572
+ # logger.info(f"Detected SQL query: {sql_query}")
573
+ # # Execute the query and update the response
574
+ # db_connection, _ = setup_database_connection()
575
+ # if db_connection:
576
+ # query_result = execute_sql_query(sql_query, db_connection)
577
 
578
+ # # Add the query and its result to the response
579
+ # response_text += f"\n\n### 馃攳 Resultado de la consulta:\n```sql\n{sql_query}\n```\n\n{query_result}"
580
 
581
+ # # Try to generate an interactive chart if the result is tabular
582
+ # try:
583
+ # if isinstance(query_result, str) and '|' in query_result and '---' in query_result:
584
+ # # Convert markdown table to DataFrame
585
 
586
+ # # Clean up the markdown table
587
+ # lines = [line.strip() for line in query_result.split('\n')
588
+ # if line.strip() and '---' not in line and '|' in line]
589
+ # if len(lines) > 1: # At least header + 1 data row
590
+ # # Get column names from the first line
591
+ # columns = [col.strip() for col in lines[0].split('|')[1:-1]]
592
+ # # Get data rows
593
+ # data = []
594
+ # for line in lines[1:]:
595
+ # values = [val.strip() for val in line.split('|')[1:-1]]
596
+ # if len(values) == len(columns):
597
+ # data.append(dict(zip(columns, values)))
598
 
599
+ # if data and len(columns) >= 2:
600
+ # # Determine chart type from user's question
601
+ # _, desired_type = detect_chart_preferences(question)
602
+
603
+ # # Choose x/y columns (assume first is category, second numeric)
604
+ # x_col = columns[0]
605
+ # y_col = columns[1]
606
+
607
+ # # Coerce numeric values for y
608
+ # for row in data:
609
+ # try:
610
+ # row[y_col] = float(re.sub(r"[^0-9.\-]", "", str(row[y_col])))
611
+ # except Exception:
612
+ # pass
613
+
614
+ # chart_fig = generate_chart(
615
+ # data=data,
616
+ # chart_type=desired_type,
617
+ # x=x_col,
618
+ # y=y_col,
619
+ # title=f"{y_col} por {x_col}"
620
+ # )
621
+ # if chart_fig is not None:
622
+ # logger.info(f"Chart generated from SQL table: type={desired_type}, x={x_col}, y={y_col}, rows={len(data)}")
623
+ # except Exception as e:
624
+ # logger.error(f"Error generating chart: {str(e)}", exc_info=True)
625
+ # # Don't fail the whole request if chart generation fails
626
+ # response_text += "\n\n鈿狅笍 No se pudo generar la visualizaci贸n de los datos."
627
+ # else:
628
+ # response_text += "\n\n鈿狅笍 No se pudo conectar a la base de datos para ejecutar la consulta."
629
+ # elif sql_query and not looks_like_sql(sql_query):
630
+ # logger.info("Detected code block but it does not look like SQL; skipping execution.")
631
 
632
  # If we still have no chart but the user clearly wants one,
633
  # try a second pass to get ONLY a SQL query from the agent and execute it.