Jeremy Live commited on
Commit
13ca636
Β·
1 Parent(s): 6f7cbc4
Files changed (1) hide show
  1. app.py +54 -52
app.py CHANGED
@@ -572,59 +572,61 @@ async def stream_agent_response(question: str, chat_history: List[List[str]]) ->
572
  response_text = str(response)
573
 
574
  logger.info(f"Extracted response text: {response_text[:200]}...")
575
-
576
- # Check if the response contains an SQL query and it truly looks like SQL
577
- sql_query = extract_sql_query(response_text)
578
- if sql_query and looks_like_sql(sql_query):
579
- logger.info(f"Detected SQL query: {sql_query}")
580
- # Execute the query and update the response
581
- db_connection, _ = setup_database_connection()
582
- if db_connection:
583
- query_result = execute_sql_query(sql_query, db_connection)
584
-
585
- # Add the query and its result to the response
586
- response_text += f"\n\n### πŸ” Resultado de la consulta:\n```sql\n{sql_query}\n```\n\n{query_result}"
587
 
588
- # Try to generate an interactive chart if the result is tabular
589
- try:
590
- if isinstance(query_result, str) and '|' in query_result and '---' in query_result:
591
- # Clean up the markdown table
592
- lines = [line.strip() for line in query_result.split('\n')
593
- if line.strip() and '---' not in line and '|' in line]
594
- if len(lines) > 1: # At least header + 1 data row
595
- # Get column names from the first line
596
- columns = [col.strip() for col in lines[0].split('|')[1:-1]]
597
- # Get data rows
598
- data = []
599
- for line in lines[1:]:
600
- values = [val.strip() for val in line.split('|')[1:-1]]
601
- if len(values) == len(columns):
602
- data.append(dict(zip(columns, values)))
603
-
604
- if data and len(columns) >= 2:
605
- # Determine chart type from user's question
606
- _, desired_type = detect_chart_preferences(question)
607
-
608
- # Choose x/y columns (assume first is category, second numeric)
609
- x_col = columns[0]
610
- y_col = columns[1]
611
-
612
- # Coerce numeric values for y
613
- for row in data:
614
- try:
615
- row[y_col] = float(re.sub(r"[^0-9.\-]", "", str(row[y_col])))
616
- except Exception:
617
- pass
618
-
619
- chart_fig = generate_chart(
620
- data=data,
621
- chart_type=desired_type,
622
- x=x_col,
623
- y=y_col,
624
- title=f"{y_col} por {x_col}"
625
- )
626
- if chart_fig is not None:
627
- logger.info(f"Chart generated from SQL table: type={desired_type}, x={x_col}, y={y_col}, rows={len(data)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
628
  except Exception as e:
629
  logger.error(f"Error generating chart: {str(e)}", exc_info=True)
630
  # Don't fail the whole request if chart generation fails
 
572
  response_text = str(response)
573
 
574
  logger.info(f"Extracted response text: {response_text[:200]}...")
 
 
 
 
 
 
 
 
 
 
 
 
575
 
576
+ # Check if the response contains an SQL query and it truly looks like SQL
577
+ sql_query = extract_sql_query(response_text)
578
+ if sql_query and looks_like_sql(sql_query):
579
+ logger.info(f"Detected SQL query: {sql_query}")
580
+ # Execute the query and update the response
581
+ db_connection, _ = setup_database_connection()
582
+ if db_connection:
583
+ query_result = execute_sql_query(sql_query, db_connection)
584
+
585
+ # Add the query and its result to the response
586
+ response_text += f"\n\n### πŸ” Resultado de la consulta:\n```sql\n{sql_query}\n```\n\n{query_result}"
587
+
588
+ # Try to generate an interactive chart if the result is tabular
589
+ try:
590
+ if isinstance(query_result, str) and '|' in query_result and '---' in query_result:
591
+ # Convert markdown table to DataFrame
592
+
593
+ # Clean up the markdown table
594
+ lines = [line.strip() for line in query_result.split('\n')
595
+ if line.strip() and '---' not in line and '|' in line]
596
+ if len(lines) > 1: # At least header + 1 data row
597
+ # Get column names from the first line
598
+ columns = [col.strip() for col in lines[0].split('|')[1:-1]]
599
+ # Get data rows
600
+ data = []
601
+ for line in lines[1:]:
602
+ values = [val.strip() for val in line.split('|')[1:-1]]
603
+ if len(values) == len(columns):
604
+ data.append(dict(zip(columns, values)))
605
+
606
+ if data and len(columns) >= 2:
607
+ # Determine chart type from user's question
608
+ _, desired_type = detect_chart_preferences(question)
609
+
610
+ # Choose x/y columns (assume first is category, second numeric)
611
+ x_col = columns[0]
612
+ y_col = columns[1]
613
+
614
+ # Coerce numeric values for y
615
+ for row in data:
616
+ try:
617
+ row[y_col] = float(re.sub(r"[^0-9.\-]", "", str(row[y_col])))
618
+ except Exception:
619
+ pass
620
+
621
+ chart_fig = generate_chart(
622
+ data=data,
623
+ chart_type=desired_type,
624
+ x=x_col,
625
+ y=y_col,
626
+ title=f"{y_col} por {x_col}"
627
+ )
628
+ if chart_fig is not None:
629
+ logger.info(f"Chart generated from SQL table: type={desired_type}, x={x_col}, y={y_col}, rows={len(data)}")
630
  except Exception as e:
631
  logger.error(f"Error generating chart: {str(e)}", exc_info=True)
632
  # Don't fail the whole request if chart generation fails