-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.py
More file actions
1973 lines (1638 loc) · 72.2 KB
/
Copy pathagent.py
File metadata and controls
1973 lines (1638 loc) · 72.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import logging
import re
import warnings
import os
import colorsys
import random
from langchain_groq import ChatGroq
from langchain_core.tools import tool
from langchain_core.messages import HumanMessage, AIMessage, SystemMessage, ToolMessage, BaseMessage
from langgraph.graph import StateGraph, END
from google.cloud import bigquery
from google.oauth2 import service_account
from typing import Literal, TypedDict, Sequence
import json
import plotly.graph_objects as go
import pandas as pd
# Suppress warnings
warnings.filterwarnings('ignore')
os.environ['GRPC_VERBOSITY'] = 'ERROR'
os.environ['GLOG_minloglevel'] = '2'
PRODUCTION_MODE = True
if PRODUCTION_MODE:
logging.basicConfig(level=logging.CRITICAL)
for name in ['httpx', 'httpcore', 'google', 'urllib3', 'langchain', 'langgraph']:
logging.getLogger(name).setLevel(logging.CRITICAL)
logger = logging.getLogger(__name__)
# Define state
class AgentState(TypedDict):
messages: Sequence[BaseMessage]
# Get API keys
GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
if not GROQ_API_KEY:
raise ValueError("GROQ_API_KEY not found in environment variables")
GROQ_MODEL = os.environ.get("GROQ_MODEL", "openai/gpt-oss-120b")
# Initialize BigQuery with proper credential handling for deployment
PROJECT_ID = os.environ.get("GOOGLE_CLOUD_PROJECT")
if not PROJECT_ID:
raise ValueError("GOOGLE_CLOUD_PROJECT not found in environment variables")
# Get GCP credentials from environment variable
gcp_json_str = os.environ.get("GCP_SERVICE_ACCOUNT_JSON")
if not gcp_json_str:
raise ValueError("GCP_SERVICE_ACCOUNT_JSON not found in environment variables")
try:
# Parse JSON credentials
credentials_dict = json.loads(gcp_json_str)
credentials = service_account.Credentials.from_service_account_info(credentials_dict)
bq_client = bigquery.Client(credentials=credentials, project=PROJECT_ID)
logger.info("✅ BigQuery initialized successfully")
except json.JSONDecodeError as e:
raise ValueError(f"Invalid JSON in GCP_SERVICE_ACCOUNT_JSON: {str(e)}")
except Exception as e:
raise ValueError(f"Failed to initialize BigQuery: {str(e)}")
ECOMMERCE_TABLES = {
"users": "bigquery-public-data.thelook_ecommerce.users",
"orders": "bigquery-public-data.thelook_ecommerce.orders",
"order_items": "bigquery-public-data.thelook_ecommerce.order_items",
"products": "bigquery-public-data.thelook_ecommerce.products",
"inventory_items": "bigquery-public-data.thelook_ecommerce.inventory_items",
"distribution_centers": "bigquery-public-data.thelook_ecommerce.distribution_centers",
"events": "bigquery-public-data.thelook_ecommerce.events",
}
DEFAULT_LIMIT = 100
schema_snippet = """
TheLook Ecommerce Schema:
Available tables (use these exact names):
- users: id, first_name, last_name, email, age, gender, state, city, country, latitude, longitude, traffic_source, created_at
- orders: order_id, user_id, status (Complete, Cancelled, Returned, Processing, Shipped), created_at, returned_at, shipped_at, delivered_at, num_of_item
- order_items: id, order_id, user_id, product_id, inventory_item_id, status, created_at, shipped_at, delivered_at, returned_at, sale_price
- products: id, cost, category, name, brand, retail_price, department, sku, distribution_center_id
- inventory_items: id, product_id, created_at, sold_at, cost, product_category, product_name, product_brand, product_retail_price, product_department, product_sku, product_distribution_center_id
- distribution_centers: id, name, latitude, longitude
- events: id, user_id, sequence_number, session_id, created_at, ip_address, city, state, postal_code, browser, traffic_source, uri, event_type
"""
SYSTEM_PROMPT = f"""You are a BigQuery SQL expert for TheLook Ecommerce data.
RULES:
1. Use simple table names (users, orders, order_items, products, etc.)
2. Return ONLY SQL - no explanations
3. For stacked bar charts: ALWAYS use LIMIT 500 (not 100)
4. For simple queries: Use LIMIT {DEFAULT_LIMIT}
5. Use CROSS JOIN to generate ALL time periods
TIME PERIOD GENERATION:
- Monthly: CROSS JOIN with all 12 months
- Quarterly: CROSS JOIN with quarters 1,2,3,4
- Yearly: CROSS JOIN with array of years
COLUMN NAMING FOR STACKED CHARTS:
Always name columns: x_axis, stack_category, value
CRITICAL: PARSE USER REQUEST CORRECTLY
Read the user's question word by word to identify:
1. TIME dimension (monthly/quarterly/yearly) → becomes x_axis
2. BREAKDOWN dimension (the word after "by") → becomes stack_category
Examples of parsing:
- "monthly revenue by category" → time=month, breakdown=CATEGORY
- "yearly revenue by brand" → time=year, breakdown=BRAND
- "quarterly sales by country" → time=quarter, breakdown=COUNTRY
- "yearly revenue by category" → time=year, breakdown=CATEGORY
DO NOT use brand when user says category!
DO NOT use country when user says category!
DO NOT add extra dimensions!
TEMPLATE - Monthly by Category:
WITH all_months AS (
SELECT DATE_TRUNC(DATE_ADD(DATE '2025-01-01', INTERVAL month MONTH), MONTH) AS month
FROM UNNEST(GENERATE_ARRAY(0, 11)) AS month
),
categories AS (
SELECT DISTINCT category FROM products LIMIT 10
),
revenue_data AS (
SELECT
DATE_TRUNC(DATE(oi.created_at), MONTH) as month,
p.category,
SUM(oi.sale_price) as revenue
FROM order_items oi
JOIN products p ON oi.product_id = p.id
WHERE oi.status = 'Complete' AND EXTRACT(YEAR FROM oi.created_at) = 2025
GROUP BY month, p.category
)
SELECT
FORMAT_DATE('%Y-%m-%d', am.month) as x_axis,
c.category as stack_category,
COALESCE(rd.revenue, 0) as value
FROM all_months am
CROSS JOIN categories c
LEFT JOIN revenue_data rd ON am.month = rd.month AND c.category = rd.category
ORDER BY am.month, value DESC
LIMIT 500
TEMPLATE - Yearly by Category:
WITH all_years AS (
SELECT year FROM UNNEST([2022, 2023, 2024, 2025]) AS year
),
categories AS (
SELECT DISTINCT category FROM products LIMIT 10
),
revenue_data AS (
SELECT
EXTRACT(YEAR FROM oi.created_at) as year,
p.category,
SUM(oi.sale_price) as revenue
FROM order_items oi
JOIN products p ON oi.product_id = p.id
WHERE oi.status = 'Complete'
AND EXTRACT(YEAR FROM oi.created_at) BETWEEN 2022 AND 2025
GROUP BY year, p.category
)
SELECT
CAST(ay.year AS STRING) as x_axis,
c.category as stack_category,
COALESCE(rd.revenue, 0) as value
FROM all_years ay
CROSS JOIN categories c
LEFT JOIN revenue_data rd ON ay.year = rd.year AND c.category = rd.category
ORDER BY ay.year, value DESC
LIMIT 500
TEMPLATE - Yearly by Brand:
WITH all_years AS (
SELECT year FROM UNNEST([2022, 2023, 2024, 2025]) AS year
),
brands AS (
SELECT DISTINCT brand FROM products LIMIT 10
),
revenue_data AS (
SELECT
EXTRACT(YEAR FROM oi.created_at) as year,
p.brand,
SUM(oi.sale_price) as revenue
FROM order_items oi
JOIN products p ON oi.product_id = p.id
WHERE oi.status = 'Complete'
AND EXTRACT(YEAR FROM oi.created_at) BETWEEN 2022 AND 2025
GROUP BY year, p.brand
)
SELECT
CAST(ay.year AS STRING) as x_axis,
b.brand as stack_category,
COALESCE(rd.revenue, 0) as value
FROM all_years ay
CROSS JOIN brands b
LEFT JOIN revenue_data rd ON ay.year = rd.year AND b.brand = rd.brand
ORDER BY ay.year, value DESC
LIMIT 500
TEMPLATE - Quarterly by Category:
WITH all_quarters AS (
SELECT quarter FROM UNNEST([1, 2, 3, 4]) AS quarter
),
categories AS (
SELECT DISTINCT category FROM products LIMIT 10
),
revenue_data AS (
SELECT
EXTRACT(QUARTER FROM oi.created_at) as quarter,
p.category,
SUM(oi.sale_price) as revenue
FROM order_items oi
JOIN products p ON oi.product_id = p.id
WHERE oi.status = 'Complete' AND EXTRACT(YEAR FROM oi.created_at) = 2025
GROUP BY quarter, p.category
)
SELECT
CONCAT('Q', CAST(aq.quarter AS STRING), ' 2025') as x_axis,
c.category as stack_category,
COALESCE(rd.revenue, 0) as value
FROM all_quarters aq
CROSS JOIN categories c
LEFT JOIN revenue_data rd ON aq.quarter = rd.quarter AND c.category = rd.category
ORDER BY aq.quarter, value DESC
LIMIT 500
TEMPLATE - Quarterly by Brand:
WITH all_quarters AS (
SELECT quarter FROM UNNEST([1, 2, 3, 4]) AS quarter
),
brands AS (
SELECT DISTINCT brand FROM products LIMIT 10
),
revenue_data AS (
SELECT
EXTRACT(QUARTER FROM oi.created_at) as quarter,
p.brand,
SUM(oi.sale_price) as revenue
FROM order_items oi
JOIN products p ON oi.product_id = p.id
WHERE oi.status = 'Complete' AND EXTRACT(YEAR FROM oi.created_at) = 2025
GROUP BY quarter, p.brand
)
SELECT
CONCAT('Q', CAST(aq.quarter AS STRING), ' 2025') as x_axis,
b.brand as stack_category,
COALESCE(rd.revenue, 0) as value
FROM all_quarters aq
CROSS JOIN brands b
LEFT JOIN revenue_data rd ON aq.quarter = rd.quarter AND b.brand = rd.brand
ORDER BY aq.quarter, value DESC
LIMIT 500
CRITICAL REMINDER:
If user says "by category" → use p.category
If user says "by brand" → use p.brand
If user says "by country" → use u.country
DO NOT mix them! Use ONLY what user requested!
"""
# Utility Functons
def _strip_code_fences(sql: str) -> str:
"""Remove markdown code fences and clean up the SQL string"""
s = sql.strip()
# Remove markdown code fences with optional sql language identifier
s = re.sub(r'^```(?:sql|SQL)?\s*', '', s, flags=re.MULTILINE)
s = re.sub(r'```\s*$', '', s, flags=re.MULTILINE)
s = re.sub(r'```(?:sql|SQL)?', '', s) # Remove any remaining code fences
# Remove any remaining backticks
s = s.replace('`', '')
# Remove literal \n characters (not actual newlines) - CRITICAL FIX
s = s.replace('\\n', ' ')
# Remove the word "sql" if it appears at the start
s = re.sub(r'^\s*sql\s+', '', s, flags=re.IGNORECASE)
# Replace actual newlines with spaces
s = s.replace('\n', ' ')
s = s.replace('\r', ' ')
# Normalize whitespace - replace multiple spaces with single space
s = re.sub(r'\s+', ' ', s)
return s.strip()
def _transform_sql_internal(sql: str) -> str:
s = _strip_code_fences(sql)
s = re.sub(r"\s+", " ", s).strip()
s = s.replace('`', '')
s = s.replace('bigquery-public-data.thelook_ecommerce.', '')
for short_name, full_name in ECOMMERCE_TABLES.items():
pattern = rf'\b{short_name}\b'
replacement = f'`{full_name}`'
s = re.sub(pattern, replacement, s, flags=re.IGNORECASE)
if "LIMIT" not in s.upper():
# Check if this is a stacked bar query (has CROSS JOIN and stack_category)
if "CROSS JOIN" in s.upper() and "stack_category" in s.lower():
s = s.rstrip(";") + f" LIMIT 500;"
else:
s = s.rstrip(";") + f" LIMIT {DEFAULT_LIMIT};"
return s.strip()
def _is_safe_sql_internal(sql: str) -> bool:
"""Check if SQL is safe (read-only)"""
sql_lower = sql.lower()
# Check for dangerous keywords at word boundaries
dangerous_patterns = [
r'\bdrop\b', r'\bdelete\b', r'\binsert\b', r'\bupdate\b',
r'\balter\b', r'\bcreate\b', r'\btruncate\b', r'\bgrant\b',
r'\brevoke\b', r'\bexec\b', r'\bexecute\b'
]
for pattern in dangerous_patterns:
if re.search(pattern, sql_lower):
return False
return True
def _format_sql_readable(sql: str) -> str:
import re
import sqlparse
sql = re.sub(
r'(WITH\s+\w+|\),\s*\w+)\s+AS\s*\n\s*\(',
lambda m: m.group(0).replace('\n', ' ').replace(' ', ' ').replace(' AS (', ' AS ('),
sql,
flags=re.IGNORECASE
)
s = sqlparse.format(
sql,
keyword_case='upper',
reindent=True,
indent_width=2,
use_space_around_operators=True
)
s = re.sub(
r'\s+(AND|OR)\s+',
r'\n \1 ',
s
)
def format_select(match):
body = match.group(1)
cols = [c.strip() for c in body.split(',')]
return 'SELECT\n ' + ',\n '.join(cols) + '\nFROM'
s = re.sub(
r'SELECT\s+(.*?)\s+FROM',
format_select,
s,
flags=re.IGNORECASE | re.DOTALL
)
s = re.sub(
r'\),\s*(\w+\s+AS\s+\()',
r'),\n\n\1',
s,
flags=re.IGNORECASE
)
s = re.sub(
r'\)\s*\nSELECT',
r')\n\nSELECT',
s,
flags=re.IGNORECASE
)
s = re.sub(r'[ \t]{2,}', ' ', s)
return s.strip()
def _execute_sql(sql: str):
if not _is_safe_sql_internal(sql):
raise ValueError("SQL contains dangerous keywords")
try:
query_job = bq_client.query(sql)
df = query_job.result().to_dataframe()
return df
except Exception as e:
logger.error(f"SQL execution failed: {sql}")
logger.error(f"Error: {str(e)}")
raise
def _detect_query_type(question: str) -> str:
question_lower = question.lower()
list_keywords = ['top', 'list', 'show', 'display', 'get', 'find', 'what are', 'which', 'most', 'highest', 'lowest']
narrative_keywords = ['why', 'how', 'explain', 'describe', 'analyze', 'what is', 'what does']
for keyword in list_keywords:
if keyword in question_lower:
return "list"
for keyword in narrative_keywords:
if keyword in question_lower:
return "narrative"
return "list"
def _format_as_list(df, question: str, row_count: int) -> str:
title = question.strip('?').strip()
if not title[0].isupper():
title = title.capitalize()
result = f"**{title}**\n\n"
columns = df.columns.tolist()
for idx, row in df.head(20).iterrows():
result += f"| {idx + 1} | "
result += " | ".join([str(row[col]) for col in columns])
result += " |\n"
if row_count > 20:
result += f"\n*(Only top 20 of {row_count} total results shown)*"
return result
def _format_as_narrative(df, question: str, row_count: int) -> str:
df_str = df.head(20).to_string(index=False)
return f"Based on the data ({row_count} rows):\n\n{df_str}"
# Visualization Functions
# Custom color palette
CUSTOM_COLORS = ['#fe5208', '#36cdc3', '#5886e8', '#aae8f4', '#ffc600', '#ff9804']
def hex_to_rgb(hex_color):
"""Convert hex color to RGB"""
hex_color = hex_color.lstrip('#')
return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
def rgb_to_hex(rgb):
"""Convert RGB to hex color"""
return '#{:02x}{:02x}{:02x}'.format(int(rgb[0]), int(rgb[1]), int(rgb[2]))
def generate_similar_color(base_color):
"""Generate a color similar to the base color by varying hue, saturation, and lightness"""
# Convert hex to RGB
r, g, b = hex_to_rgb(base_color)
# Convert RGB to HSL (Hue, Saturation, Lightness)
h, l, s = colorsys.rgb_to_hls(r/255.0, g/255.0, b/255.0)
# Vary the hue slightly (±15 degrees)
h = (h + random.uniform(-0.04, 0.04)) % 1.0
# Vary saturation slightly (±10%)
s = max(0.0, min(1.0, s + random.uniform(-0.1, 0.1)))
# Vary lightness slightly (±10%)
l = max(0.0, min(1.0, l + random.uniform(-0.1, 0.1)))
# Convert back to RGB
r, g, b = colorsys.hls_to_rgb(h, l, s)
return rgb_to_hex((r * 255, g * 255, b * 255))
def get_color_palette(num_colors):
"""Get a color palette with the specified number of colors.
First 6 are from CUSTOM_COLORS, rest are similar variations"""
if num_colors <= len(CUSTOM_COLORS):
return CUSTOM_COLORS[:num_colors]
palette = CUSTOM_COLORS.copy()
# Generate additional colors based on the custom palette
remaining = num_colors - len(CUSTOM_COLORS)
for i in range(remaining):
# Cycle through custom colors as base for similar colors
base_color = CUSTOM_COLORS[i % len(CUSTOM_COLORS)]
similar_color = generate_similar_color(base_color)
palette.append(similar_color)
return palette
def _detect_chart_type(question: str, df: pd.DataFrame) -> str:
"""Detect the appropriate chart type based on question and data"""
question_lower = question.lower()
# Check for explicit chart type mentions
if any(word in question_lower for word in ['stacked bar', 'stacked chart', 'breakdown by', 'by quarter', 'by year and', 'share %', 'share by']):
# Check if data has 3 columns (x, category, value) - typical stacked bar structure
if len(df.columns) == 3:
return 'stacked_bar'
elif any(word in question_lower for word in ['bar chart', 'bar graph', 'bars']):
return 'bar'
elif any(word in question_lower for word in ['line chart', 'line graph', 'trend', 'over time', 'monthly', 'yearly']):
return 'line'
elif any(word in question_lower for word in ['pie chart', 'pie graph', 'percentage', 'proportion', 'distribution']):
return 'pie'
elif any(word in question_lower for word in ['scatter', 'correlation']):
return 'scatter'
# Auto-detect based on data structure
if len(df.columns) == 3:
# Check if it looks like stacked bar data (x_axis, category, value)
third_col = df.columns[2]
if any(word in str(third_col).lower() for word in ['value', 'revenue', 'sales', 'count', 'amount']):
return 'stacked_bar'
if len(df) <= 10 and len(df.columns) == 2:
if any(word in question_lower for word in ['percentage', 'share', 'distribution']):
return 'pie'
return 'bar'
elif 'date' in str(df.columns).lower() or 'month' in str(df.columns).lower() or 'year' in str(df.columns).lower():
return 'line'
else:
return 'bar'
def _detect_x_axis_label(x_col: str, question: str, df: pd.DataFrame) -> str:
"""
Dynamically detect X-axis label based on column name, question context, and actual data.
"""
x_col_lower = x_col.lower()
question_lower = question.lower()
# Analyze the actual data in the column to understand its type
sample_values = df[x_col].head(5).astype(str).tolist()
sample_str = ' '.join(sample_values).lower()
# Strategy 1: Check COLUMN NAME patterns first (highest priority)
import re
column_patterns = {
r'month|monthly': 'Month',
r'quarter': 'Quarter',
r'year|yearly': 'Year',
r'date|day|created_at': 'Date',
r'week': 'Week',
}
for pattern, label in column_patterns.items():
if re.search(pattern, x_col_lower):
return label
# Strategy 2: Analyze actual DATA patterns (second priority)
try:
# Check if data looks like dates (YYYY-MM-DD format)
if re.search(r'\d{4}-\d{2}-\d{2}', sample_str):
# Check if question asks for monthly/quarterly/yearly
if any(word in question_lower for word in ['month', 'monthly']):
return 'Month'
elif any(word in question_lower for word in ['quarter', 'quarterly']):
return 'Quarter'
elif any(word in question_lower for word in ['year', 'yearly', 'annual']):
return 'Year'
else:
return 'Month' # Default for dates
# Check if data looks like quarters (Q1, Q2, etc.)
if any(f'q{i}' in sample_str for i in range(1, 5)):
return 'Quarter'
# Check if data looks like years (4-digit numbers)
if all(val.isdigit() and len(val) == 4 for val in sample_values if val.isdigit()):
return 'Year'
# Check if data looks like country names
if any(country in sample_str for country in ['china', 'united states', 'brasil', 'india', 'japan']):
return 'Country'
# Check if data looks like brands
if any(brand in sample_str for brand in ['nike', 'adidas', 'calvin', 'diesel']):
return 'Brand'
except Exception:
pass
# Strategy 3: Check question keywords for TIME dimensions (only if column/data didn't match)
if any(word in question_lower for word in ['month', 'monthly']):
return 'Month'
elif any(word in question_lower for word in ['quarter', 'quarterly', 'q1', 'q2', 'q3', 'q4']):
return 'Quarter'
elif any(word in question_lower for word in ['year', 'yearly', 'annual']):
return 'Year'
elif any(word in question_lower for word in ['day', 'daily', 'date']):
return 'Date'
elif any(word in question_lower for word in ['week', 'weekly']):
return 'Week'
# Strategy 4: Check question keywords for CATEGORICAL dimensions (lowest priority)
elif any(word in question_lower for word in ['category', 'categories']):
return 'Product Category'
elif any(word in question_lower for word in ['brand', 'brands']):
return 'Brand'
elif any(word in question_lower for word in ['country', 'countries']):
return 'Country'
elif any(word in question_lower for word in ['state', 'states']):
return 'State'
elif any(word in question_lower for word in ['city', 'cities']):
return 'City'
elif any(word in question_lower for word in ['department', 'dept']):
return 'Department'
elif any(word in question_lower for word in ['product', 'products']):
return 'Product Name'
elif any(word in question_lower for word in ['customer', 'user', 'buyer']):
return 'Customer'
# Fallback: Format column name nicely
cleaned = x_col.replace('_', ' ').replace('-', ' ')
cleaned = re.sub(r'^(the|a|an)\s+', '', cleaned, flags=re.IGNORECASE)
return cleaned.title()
def _detect_y_axis_label(y_col: str, question: str, df: pd.DataFrame) -> tuple:
"""
Dynamically detect Y-axis label and format based on data type.
Returns:
tuple: (label, is_revenue, is_percentage, is_count)
"""
y_col_lower = y_col.lower()
question_lower = question.lower()
# Check actual data to infer type
sample_values = df[y_col].head(10)
# Detect percentage (values between 0-1 or 0-100)
is_percentage = False
if 'percentage' in question_lower or 'share' in question_lower or '%' in question_lower or 'proportion' in question_lower:
is_percentage = True
elif 'percentage' in y_col_lower or 'share' in y_col_lower or 'percent' in y_col_lower:
is_percentage = True
elif sample_values.max() <= 1.0 and sample_values.min() >= 0:
# Values between 0-1 likely percentage
is_percentage = True
# Detect revenue/money
is_revenue = False
if any(word in question_lower for word in ['revenue', 'sales', 'price', 'cost', 'profit', 'income']):
is_revenue = True
elif any(word in y_col_lower for word in ['revenue', 'sale_price', 'price', 'cost', 'profit']):
is_revenue = True
elif sample_values.max() > 1000 and not is_percentage:
# Large numbers likely revenue
is_revenue = True
# Detect count
is_count = False
if not is_revenue and not is_percentage:
if any(word in question_lower for word in ['number of', 'count', 'quantity', 'how many', 'total']):
is_count = True
elif any(word in y_col_lower for word in ['count', 'quantity', 'total', 'num_']):
is_count = True
elif all(val == int(val) for val in sample_values if not pd.isna(val)):
# All integer values likely counts
is_count = True
# Generate label
if is_percentage:
if 'product' in question_lower:
label = 'Product Share (%)'
elif 'revenue' in question_lower:
label = 'Revenue Share (%)'
elif 'order' in question_lower:
label = 'Order Share (%)'
else:
label = 'Share (%)'
elif is_revenue:
label = 'Revenue ($)'
elif is_count:
if 'product' in question_lower:
label = 'Products Sold'
elif 'order' in question_lower:
label = 'Orders'
elif 'customer' in question_lower or 'user' in question_lower:
label = 'Customers'
else:
label = y_col.replace('_', ' ').title()
else:
label = y_col.replace('_', ' ').title()
return label, is_revenue, is_percentage, is_count
def _create_stacked_bar_chart(df: pd.DataFrame, question: str) -> dict:
"""Create stacked bar chart visualization with custom colors"""
if df.empty or len(df.columns) < 3:
return {"error": "Stacked bar chart requires at least 3 columns (x_axis, category, value)"}
columns = df.columns.tolist()
x_col = columns[0]
stack_col = columns[1]
value_col = columns[2]
try:
question_lower = question.lower()
value_col_lower = value_col.lower()
# Use smart X-axis detection
x_axis_label = _detect_x_axis_label(x_col, question, df)
# Smart metric detection using sample values
sample_values = df[value_col].head(10)
is_percentage = (
'percentage' in question_lower or 'share' in question_lower or '%' in question_lower or
'percentage' in value_col_lower or (sample_values.max() <= 1.0 and sample_values.min() >= 0)
)
is_revenue = (
not is_percentage and
(any(word in question_lower for word in ['revenue', 'sales', 'price']) or
any(word in value_col_lower for word in ['revenue', 'price', 'sale']))
)
is_count = (
not is_percentage and not is_revenue and
(any(word in question_lower for word in ['number of', 'count', 'sold', 'quantity']) or
'count' in value_col_lower)
)
# Generate metric name
if is_percentage:
metric_name = 'Share'
elif is_revenue:
metric_name = 'Revenue'
elif is_count:
if 'product' in question_lower:
metric_name = 'Products Sold'
elif 'order' in question_lower:
metric_name = 'Orders'
else:
metric_name = 'Count'
else:
metric_name = value_col.replace('_', ' ').title()
y_axis_label = f'{metric_name} (%)' if is_percentage else f'{metric_name} ($)' if is_revenue else metric_name
# Formatting Setup based on detection
if is_percentage:
y_tickformat = ',.1%'
hover_format = '%{y:.1%}'
text_template = '%{text:.1%}'
elif is_revenue:
y_tickformat = '$,.0f'
hover_format = '$%{y:,.0f}'
text_template = '$%{text:,.0f}'
elif is_count:
y_tickformat = ',.0f'
hover_format = '%{y:,.0f}'
text_template = '%{text:,.0f}'
else:
y_tickformat = ',.2f'
hover_format = '%{y:,.2f}'
text_template = '%{text:.2f}'
all_x_values = df[x_col].unique()
# Sort x-axis values properly
try:
# Try to sort as dates first
if 'q' in str(all_x_values[0]).lower():
# Quarters: Q1 2025, Q2 2025, etc.
all_x_values = sorted(all_x_values, key=lambda x: (x.split()[-1], x.split()[0]))
elif '-' in str(all_x_values[0]) and len(str(all_x_values[0])) == 10:
# Dates: 2025-01-01, 2025-02-01, etc.
all_x_values = sorted(all_x_values)
elif all(str(x).isdigit() for x in all_x_values):
# Years: 2022, 2023, 2024, 2025
all_x_values = sorted(all_x_values)
else:
# Keep original order
all_x_values = sorted(all_x_values)
except:
# If sorting fails, keep original order
pass
# Pivot and Filter Data
pivot_df = df.pivot_table(
index=x_col,
columns=stack_col,
values=value_col,
aggfunc='sum',
fill_value=0
)
pivot_df = pivot_df.reindex(all_x_values, fill_value=0)
# Select top categories by total value
category_totals = pivot_df.sum().sort_values(ascending=False)
top_categories = category_totals.head(10).index.tolist()
pivot_df = pivot_df[top_categories]
if is_percentage:
# Normalize percentage charts to 100%
pivot_df = pivot_df.apply(lambda x: x / x.sum() if x.sum() > 0 else x, axis=1)
pivot_df = pivot_df.fillna(0)
# Chart Creation
fig = go.Figure()
colors = get_color_palette(len(pivot_df.columns))
for idx, category in enumerate(pivot_df.columns):
color = colors[idx]
fig.add_trace(go.Bar(
name=str(category),
x=pivot_df.index,
y=pivot_df[category],
marker_color=color,
hovertemplate=f'<b>{category}</b><br>%{{x}}<br>Value: {hover_format}<extra></extra>',
text=pivot_df[category],
texttemplate=text_template,
textposition='inside',
textfont=dict(size=10, color='white')
))
# Layout
fig.update_layout(
title=question,
xaxis_title=x_axis_label,
yaxis_title=y_axis_label,
barmode='stack',
template='plotly_white',
hovermode='x unified',
showlegend=True,
legend=dict(
orientation="v", yanchor="top", y=1, xanchor="left", x=1.02,
bgcolor="rgba(255, 255, 255, 0.8)", bordercolor="rgba(0, 0, 0, 0.2)", borderwidth=1
),
height=500,
margin=dict(r=150),
xaxis=dict(showspikes=False),
yaxis=dict(showspikes=False)
)
# Apply Y-axis formatting based on detection
fig.update_yaxes(tickformat=y_tickformat)
return {
"chart_json": fig.to_json(),
"chart_type": "stacked_bar",
"data_points": len(df),
"categories": len(top_categories),
"x_axis": x_col,
"stack_by": stack_col
}
except Exception as e:
logger.error(f"Stacked bar chart error: {str(e)}")
return {"error": f"Failed to create stacked bar chart: {str(e)}"}
def _create_visualization(df: pd.DataFrame, question: str, chart_type: str = None) -> dict:
"""Create interactive Plotly visualization with custom colors"""
if df.empty:
return {"error": "No data to visualize"}
if not chart_type:
chart_type = _detect_chart_type(question, df)
# Handle stacked bar chart
if chart_type == 'stacked_bar':
return _create_stacked_bar_chart(df, question)
columns = df.columns.tolist()
if len(columns) < 2:
return {"error": "Need at least 2 columns for visualization"}
x_col = columns[0]
y_col = columns[1]
df_viz = df.head(20)
try:
# --- Use smart detections ---
x_axis_label = _detect_x_axis_label(x_col, question, df_viz)
y_axis_label, is_revenue, is_percentage, is_count = _detect_y_axis_label(y_col, question, df_viz)
# --- Formatting Setup based on detection ---
if is_percentage:
y_tickformat = ',.1%'
hover_format = '%{y:.1%}'
text_template = '%{text:.1%}'
elif is_revenue:
y_tickformat = '$,.0f'
hover_format = '$%{y:,.0f}'
text_template = '$%{text:,.0f}'
elif is_count:
y_tickformat = ',.0f'
hover_format = '%{y:,.0f}'
text_template = '%{text:,.0f}'
else:
y_tickformat = ',.2f'
hover_format = '%{y:,.2f}'
text_template = '%{text:.2f}'
# --- Chart Creation ---
if chart_type == 'bar':
# Generate colors for bar chart
num_bars = len(df_viz)
bar_colors = get_color_palette(num_bars)
fig = go.Figure(data=[
go.Bar(
x=df_viz[x_col],
y=df_viz[y_col],
marker=dict(
color=bar_colors,
showscale=False
),
text=df_viz[y_col],
texttemplate=text_template,
textposition='outside',
hovertemplate=f'<b>%{{x}}</b><br>{y_axis_label}: {hover_format}<extra></extra>'
)
])
fig.update_layout(
title=question,
xaxis_title=x_axis_label,
yaxis_title=y_axis_label,
template='plotly_white',
hovermode='x',
showlegend=False,
xaxis=dict(showspikes=False),
yaxis=dict(showspikes=False)
)
fig.update_yaxes(tickformat=y_tickformat)
elif chart_type == 'line':
fig = go.Figure(data=[
go.Scatter(
x=df_viz[x_col],
y=df_viz[y_col],
mode='lines+markers',
line=dict(color=CUSTOM_COLORS[0], width=3),
marker=dict(size=8, color=CUSTOM_COLORS[0]),
hovertemplate=f'<b>%{{x}}</b><br>{y_axis_label}: {hover_format}<extra></extra>'
)
])
fig.update_layout(
title=question,
xaxis_title=x_axis_label,
yaxis_title=y_axis_label,
template='plotly_white',
hovermode='x',
xaxis=dict(showgrid=True),
yaxis=dict(showgrid=True)
)
fig.update_yaxes(tickformat=y_tickformat)
elif chart_type == 'pie':
# For pie charts, use different formatting for labels
if is_percentage:
texttemplate = '%{label}<br>%{percent}'
elif is_revenue:
texttemplate = '%{label}<br>$%{value:,.0f}'
else:
texttemplate = '%{label}<br>%{value:,.0f}'
pie_colors = get_color_palette(len(df_viz))
fig = go.Figure(data=[
go.Pie(
labels=df_viz[x_col],
values=df_viz[y_col],
hole=0.3,
marker=dict(colors=pie_colors),
texttemplate=texttemplate,
hovertemplate=f'<b>%{{label}}</b><br>{y_axis_label}: {hover_format}<br>Percentage: %{{percent}}<extra></extra>'
)
])
fig.update_layout(
title=question,
template='plotly_white'
)
elif chart_type == 'scatter':
fig = go.Figure(data=[
go.Scatter(
x=df_viz[x_col],
y=df_viz[y_col],
mode='markers',
marker=dict(
size=10,
color=df_viz[y_col],
colorscale=[
[0, CUSTOM_COLORS[0]],
[0.2, CUSTOM_COLORS[2]],
[0.4, CUSTOM_COLORS[1]],
[0.6, CUSTOM_COLORS[3]],
[0.8, CUSTOM_COLORS[4]],