File size: 36,574 Bytes
e28e1ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c69638
e28e1ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import pandas as pd
import streamlit as st

# βœ… Fix OpenMP library conflict (common with PyTorch/NumPy)
os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'

# --- Visualization imports ---
try:
    import matplotlib.pyplot as plt
    import plotly.express as px
    import plotly.graph_objects as go
    VISUALIZATION_AVAILABLE = True
except ImportError:
    st.warning("πŸ“Š Visualization libraries not available. Install: pip install matplotlib plotly")
    VISUALIZATION_AVAILABLE = False

# --- Modular Imports ---
from db_utils import get_engine, get_db
from llm_utils import get_llm, get_sql_prompt
from chroma_utils import get_chroma_client, get_chroma_collection, get_embedding_model
from pdf_utils import extract_pdf_text

# --- Voice functionality imports (with error handling) ---
# (No need to import from agents, these are defined locally)
import json
from difflib import SequenceMatcher
from langchain.chains import LLMChain

# βœ… Custom CSS for Styling
st.markdown(
    """
    <style>
    /* Background and font styles */
    body {
        background-color: #f4f4f4;
        font-family: 'Arial', sans-serif;
    }
    
    /* Title Styling */
    .title {
        color: #2E86C1;
        text-align: center;
        font-size: 40px;
        font-weight: bold;
    }
    
    /* Text Area Styling */
    .stTextArea > div > textarea {
        border-radius: 10px;
        border: 2px solid #3498db;
        padding: 10px;
        font-size: 16px;
        height: 150px !important;  /* Increased height */
    }

    /* Button Styling */
    .stButton > button {
        background-color: #3498db;
        color: white;
        font-size: 18px;
        border-radius: 10px;
        padding: 10px 20px;
        border: none;
        transition: 0.3s;
    }
    
    .stButton > button:hover {
        background-color: #2980b9;
    }

    /* SQL Query Box */
    .stCode {
        background-color: #1e272e;
        color: #ecf0f1;
        font-size: 16px;
        border-radius: 10px;
    }

    /* Dataframe Table */
    .stDataFrame {
        border-radius: 10px;
        overflow: hidden;
        box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.1);
    }
    </style>
    """,
    unsafe_allow_html=True
)

# βœ… Streamlit Chat UI with Session History
st.markdown('<h3 class="title">Multi-Model RAG System</h3>', unsafe_allow_html=True)
st.write("       Chat with the agent. Your session history will be preserved below.")

# Initialize session state for chat history
if 'chat_history' not in st.session_state:
    st.session_state['chat_history'] = [] 
# Each item: {'role': 'user'/'agent', 'content': str, 'sql': str or None, 'df': DataFrame or None}

# Initialize session state for voice input
if 'pending_voice_query' not in st.session_state:
    st.session_state['pending_voice_query'] = None

## --- Modular Setup ---
engine = get_engine()
db = get_db(engine)
llm = get_llm()
sql_prompt = get_sql_prompt()

# βœ… Function to Format Schema as Markdown
def format_schema_markdown(schema_info):
    import re
    tables = re.findall(r'CREATE TABLE \"([^\"]+)\" \((.*?)\)', schema_info, re.DOTALL)
    md = '**Database Tables and Columns:**\n'
    for table, cols in tables:
        col_names = re.findall(r'\"([^\"]+)\"', cols)
        md += f'- **{table}**: ' + ', '.join(f'`{col}`' for col in col_names) + '\\n'
    return md

# Helper: Detect if a question is a follow-up
followup_starters = [
    'and ', 'also', 'from which', 'which', 'what about', 'where', 'who', 'how many', 'show me those', 'give me those'
]
def is_followup_question(q):
    ql = q.strip().lower()
    return any(ql.startswith(st) for st in followup_starters)

PROMPT_JSONL_PATH = 'prompts.jsonl'
def load_prompt_examples(jsonl_path):
    examples = []
    try:
        with open(jsonl_path, 'r', encoding='utf-8') as f:
            for line in f:
                examples.append(json.loads(line))
    except Exception:
        pass
    return examples

prompt_examples = load_prompt_examples(PROMPT_JSONL_PATH)

# Initialize ChromaDB and embedding model with persistence
try:
    with st.spinner("πŸ”„ Initializing persistent vector database..."):
        chroma_client = get_chroma_client()
        chroma_collection = get_chroma_collection(chroma_client)
        embedding_model = get_embedding_model()
        
        # Try to initialize from existing JSONL if database is empty
        from chroma_utils import initialize_from_jsonl, check_database_stats
        initialize_from_jsonl(PROMPT_JSONL_PATH)
        
        # Show database statistics
        stats = check_database_stats()
        if stats["status"] == "healthy":
            st.success(f"βœ… Vector database ready: {stats['total_items']} prompts loaded")
        else:
            st.warning(f"⚠️ Database status: {stats['status']}")
            
except Exception as e:
    st.error(f"❌ Vector search initialization failed: {str(e)}")
    chroma_client = None
    chroma_collection = None
    embedding_model = None

# (No need to import run_query_chain; define and use locally)

with st.sidebar:
    st.markdown('---')
    st.markdown('### Upload PDF, CSV, or Excel files to query their content')
    uploaded_files = st.file_uploader(
        "Upload one or more files (PDF, CSV, Excel)",
        type=["pdf", "csv", "xlsx", "xls"],
        accept_multiple_files=True
    )
    if 'uploaded_dfs' not in st.session_state:
        st.session_state['uploaded_dfs'] = {}
    if 'uploaded_texts' not in st.session_state:
        st.session_state['uploaded_texts'] = {}
    for uploaded_file in uploaded_files or []:
        filename = uploaded_file.name
        if filename.endswith('.csv'):
            df = pd.read_csv(uploaded_file)
            st.session_state['uploaded_dfs'][filename] = df
            st.success(f"CSV loaded: {filename} (shape: {df.shape})")
        elif filename.endswith(('.xlsx', '.xls')):
            df = pd.read_excel(uploaded_file)
            st.session_state['uploaded_dfs'][filename] = df
            st.success(f"Excel loaded: {filename} (shape: {df.shape})")
        elif filename.endswith('.pdf'):
            text = extract_pdf_text(uploaded_file)
            st.session_state['uploaded_texts'][filename] = text
            st.success(f"PDF loaded: {filename} (chars: {len(text)})")
    
    # Show uploaded DataFrames
    if st.session_state['uploaded_dfs']:
        st.markdown('#### Uploaded DataFrames:')
        for fname, df in st.session_state['uploaded_dfs'].items():
            st.write(f"**{fname}**")
            st.dataframe(df.head())
    # Show uploaded PDF text (first 500 chars)
    if st.session_state['uploaded_texts']:
        st.markdown('#### Uploaded PDF Text (preview):')
        for fname, text in st.session_state['uploaded_texts'].items():
            st.write(f"**{fname}**: {text[:500]}{'...' if len(text) > 500 else ''}")


# === Local Definition: run_query_chain ===
def run_query_chain(user_query):
    schema_info = db.get_table_info()
    # Check for meta/schema questions
    meta_keywords = [
        'list of tables', 'show tables', 'schema details', 'database schema', 'table names', 'what tables', 'describe schema', 'show schema', 'database structure', 'column', 'columns'
    ]
    if any(kw in user_query.lower() for kw in meta_keywords):
        st.write("[DEBUG] Detected meta/schema question.")
        return None, format_schema_markdown(schema_info)
    # Check for direct table details or table preview requests
    import re
    table_match = re.search(r'(?:give me|show|display|list|fetch|get) (.+?)(?: details)?$', user_query.lower())
    if table_match:
        stopwords = {'me', 'the', 'a', 'an', 'all', 'of', 'my', 'our', 'their', 'this', 'that'}
        table_candidate = table_match.group(1)
        table_candidate = ' '.join([w for w in table_candidate.split() if w not in stopwords]).strip()
        # Remove trailing 'table' or 'data' if present
        for suffix in [' table', ' data']:
            if table_candidate.lower().endswith(suffix):
                table_candidate = table_candidate[: -len(suffix)].strip()
        schema_tables = ['Location', 'Product', 'Sales']
        matched_table = None
        for t in schema_tables:
            if table_candidate.lower() == t.lower():
                matched_table = t
                break
        if matched_table:
            try:
                df = pd.read_sql(f'SELECT * FROM "{matched_table}" LIMIT 10', engine)
                st.session_state['last_result_df'] = df
                return f'SELECT * FROM "{matched_table}" LIMIT 10', df
            except Exception as e:
                st.write(f"[DEBUG] SQL Error: {e}")
                return None, f"SQL Error: {e}"
    # --- Enhanced follow-up logic ---
    if 'last_data_question' in st.session_state and is_followup_question(user_query):
        context = st.session_state['last_data_question']
        last_df = st.session_state.get('last_result_df')
        st.write(f"[DEBUG] Follow-up detected. Last context: {context}")
        if last_df is not None and 'Product Name' in last_df.columns:
            product_names = last_df['Product Name'].tolist()
            if product_names:
                in_clause = ', '.join([f'"{p}"' for p in product_names])
                sql = f'SELECT * FROM "Product" WHERE "Product Name" IN ({in_clause})'
                try:
                    df = pd.read_sql(sql, engine)
                    st.session_state['last_result_df'] = df
                    return sql, df
                except Exception as e:
                    st.write(f"[DEBUG] SQL Error (follow-up): {e}")
                    return sql, f"SQL Error: {e}"
        user_query = f"Previous question: {context}\nFollow-up: {user_query}"
    # Check for similar prompt in ChromaDB (semantic search)
    # (You can add semantic search logic here if needed)
    # Check for similar prompt in prompts.jsonl (string similarity)
    best_example, score = None, 0
    for ex in prompt_examples:
        s = SequenceMatcher(None, user_query.lower(), ex['prompt'].lower()).ratio()
        if s > score:
            score = s
            best_example = ex
    if best_example and score > 0.85:
        try:
            df = pd.read_sql(best_example['sql'], engine)
            st.session_state['last_result_df'] = df
            return best_example['sql'], df
        except Exception as e:
            st.write(f"[DEBUG] SQL Error (string sim): {e}")
            return best_example['sql'], f"SQL Error: {e}"
    # Context-aware follow-up: prepend last non-meta user question if this is a follow-up
    if 'last_data_question' in st.session_state and is_followup_question(user_query):
        context = st.session_state['last_data_question']
        user_query = f"Previous question: {context}\nFollow-up: {user_query}"
    sql_generation_chain = LLMChain(llm=llm, prompt=sql_prompt)
    generated_sql = sql_generation_chain.invoke({"question": user_query, "schema": schema_info})
    if isinstance(generated_sql, dict):
        for key in ["sql", "text", "output", "result"]:
            if key in generated_sql and isinstance(generated_sql[key], str):
                generated_sql = generated_sql[key]
                break
        else:
            generated_sql = str(generated_sql)
    if isinstance(generated_sql, str) and not generated_sql.strip().lower().startswith("select"):
        for line in generated_sql.splitlines():
            if line.strip().lower().startswith("select"):
                generated_sql = line.strip()
                break
    if not (generated_sql.strip().lower().startswith("select")):
        fallback_query = f"Write a SQL query for: {user_query}"
        generated_sql = sql_generation_chain.invoke({"question": fallback_query, "schema": schema_info})
        if isinstance(generated_sql, dict):
            for key in ["sql", "text", "output", "result"]:
                if key in generated_sql and isinstance(generated_sql[key], str):
                    generated_sql = generated_sql[key]
                    break
            else:
                generated_sql = str(generated_sql)
        if isinstance(generated_sql, str) and not generated_sql.strip().lower().startswith("select"):
            for line in generated_sql.splitlines():
                if line.strip().lower().startswith("select"):
                    generated_sql = line.strip()
                    break
    if not (generated_sql.strip().lower().startswith("select")):
        st.write("[DEBUG] No valid SQL generated.")
        return None, "No SQL query could be generated for your request. Please rephrase or be more specific."
    try:
        df = pd.read_sql(generated_sql, engine)
        st.session_state['last_data_question'] = user_query if not is_followup_question(user_query) else st.session_state.get('last_data_question', user_query)
        st.session_state['last_result_df'] = df
        # --- Add new prompt/SQL to prompts.jsonl ---
        with open(PROMPT_JSONL_PATH, "a", encoding="utf-8") as f:
            f.write(json.dumps({"prompt": user_query, "sql": generated_sql}) + "\n")
        return generated_sql, df
    except Exception as e:
        return generated_sql, f"SQL Error: {e}"

def create_data_visualization(df: pd.DataFrame, chart_key: str):
    """
    Create visualization options for DataFrame
    """
    if not VISUALIZATION_AVAILABLE or df.empty:
        return
    
    st.markdown("### πŸ“Š Data Visualization")
    
    # Create visualization options
    col1, col2, col3 = st.columns(3)
    
    with col1:
        show_bar = st.checkbox("πŸ“Š Bar Chart", key=f"bar_{chart_key}")
    with col2:
        show_pie = st.checkbox("πŸ₯§ Pie Chart", key=f"pie_{chart_key}")
    with col3:
        show_line = st.checkbox("πŸ“ˆ Line Chart", key=f"line_{chart_key}")
    
    if show_bar or show_pie or show_line:
        # Get column options for visualization
        numeric_cols = df.select_dtypes(include=['number']).columns.tolist()
        text_cols = df.select_dtypes(include=['object', 'string']).columns.tolist()
        
        col_x, col_y = st.columns(2)
        
        with col_x:
            x_col = st.selectbox(
                "Select X-axis column:",
                options=df.columns.tolist(),
                key=f"x_col_{chart_key}"
            )
        
        with col_y:
            y_col = st.selectbox(
                "Select Y-axis column:",
                options=numeric_cols if numeric_cols else df.columns.tolist(),
                key=f"y_col_{chart_key}"
            )
        
        if x_col and y_col:
            try:
                # Create visualizations based on selection
                if show_bar:
                    st.subheader("πŸ“Š Bar Chart")
                    if len(df) > 20:
                        # For large datasets, aggregate or show top 20
                        plot_df = df.groupby(x_col)[y_col].sum().reset_index().head(20)
                    else:
                        plot_df = df
                    
                    fig_bar = px.bar(plot_df, x=x_col, y=y_col, 
                                   title=f"{y_col} by {x_col}")
                    st.plotly_chart(fig_bar, use_container_width=True)
                
                if show_pie:
                    st.subheader("πŸ₯§ Pie Chart")
                    # Aggregate data for pie chart
                    if len(df) > 10:
                        # Show top 10 categories for pie chart
                        pie_df = df.groupby(x_col)[y_col].sum().reset_index()
                        pie_df = pie_df.nlargest(10, y_col)
                    else:
                        pie_df = df.groupby(x_col)[y_col].sum().reset_index()
                    
                    fig_pie = px.pie(pie_df, values=y_col, names=x_col,
                                   title=f"{y_col} Distribution by {x_col}")
                    st.plotly_chart(fig_pie, use_container_width=True)
                
                if show_line:
                    st.subheader("πŸ“ˆ Line Chart")
                    fig_line = px.line(df, x=x_col, y=y_col,
                                     title=f"{y_col} Trend by {x_col}")
                    st.plotly_chart(fig_line, use_container_width=True)
                    
            except Exception as e:
                st.error(f"Visualization error: {e}")
                st.info("πŸ’‘ Tip: Make sure you select appropriate columns for the chart type")

# === Chat Input Section ===
st.markdown("---")

user_query = None

# Check for pending voice query from session state
if 'pending_voice_query' in st.session_state and st.session_state['pending_voice_query']:
    user_query = st.session_state['pending_voice_query']
    # Clear the pending query to avoid reprocessing
    st.session_state['pending_voice_query'] = None

# Regular text input
text_query = st.chat_input("πŸ’¬ Ask about your business data or upload files to analyze...")
if text_query:
    user_query = text_query

# When user submits a query
if user_query:
    generated_sql, df_results = run_query_chain(user_query)
    st.session_state['chat_history'].append({
        'role': 'user',
        'content': user_query,
        'sql': None,
        'df': None
    })
    st.session_state['chat_history'].append({
        'role': 'agent',
        'content': "Here is the generated SQL and results.",
        'sql': generated_sql,
        'df': df_results
    })

# Add a button to display the schema in the chat UI
if st.button('Show Database Schema'):
    schema_info = db.get_table_info()
    st.session_state['chat_history'].append({
        'role': 'agent',
        'content': format_schema_markdown(schema_info),
        'sql': None,
        'df': None
    })

# Show all prompts in ChromaDB
if st.button("Show all prompts in vector DB"):
    if chroma_collection is not None:
        try:
            chroma_data = chroma_collection.get()
            st.write("Prompts in Vector DB:")
            for i, doc in enumerate(chroma_data.get('documents', [])):
                sql = chroma_data.get('metadatas', [])[i].get('sql', '')
                st.write(f"{i+1}. Prompt: {doc}")
                st.code(sql, language='sql')
        except Exception as e:
            st.error(f"Error accessing vector DB: {e}")
    else:
        st.warning("Vector DB not available. Please check ChromaDB initialization.")

# Display chat history
for msg in st.session_state['chat_history']:
    if msg['role'] == 'user':
        with st.chat_message('user'):
            st.markdown(msg.get('content', ''))
    else:
        with st.chat_message('assistant'):
            sql = msg.get('sql')
            df = msg.get('df')
            response_content = msg.get('content', '')
            
            # If the agent's response is a SQL query, show it and the result
            if sql and isinstance(sql, str) and sql.strip().lower().startswith('select'):
                st.markdown(response_content)
                st.code(sql, language='sql')
                
                if isinstance(df, pd.DataFrame):
                    if df.empty:
                        st.info('No results found for this query.')
                    else:
                        # Add visualization options above the dataframe
                        if VISUALIZATION_AVAILABLE:
                            create_data_visualization(df, f"viz1_{hash(sql)}")
                        
                        st.subheader("πŸ“‹ Query Results")
                        st.dataframe(df)
                        
                        # --- Save as CSV and View buttons ---
                        col1, col2 = st.columns(2)
                        with col1:
                            csv_filename = "chat_agent_output.csv"
                            st.download_button(
                                label="Download as CSV",
                                data=df.to_csv(index=False).encode('utf-8'),
                                file_name=csv_filename,
                                mime='text/csv',
                                key=f"csv_{sql}"
                            )
                        with col2:
                            view_name = st.text_input(f"Enter view name to save as DB view (for this result):", key=f"view_{sql}")
                            if st.button("Save as View", key=f"btn_view_{sql}") and view_name:
                                safe_view_name = ''.join(c for c in view_name if c.isalnum() or c == '_')
                                create_view_sql = f'''CREATE VIEW IF NOT EXISTS "{safe_view_name}" AS {sql.strip().rstrip(';')};'''
                                try:
                                    engine.execute(create_view_sql)
                                    st.success(f"View '{safe_view_name}' created successfully!")
                                except Exception as ve:
                                    st.error(f"Error creating view: {ve}")
                elif isinstance(df, str) and df.startswith('SQL Error:'):
                    st.error(df)
            # If the agent's response is a plain message (not SQL), show as markdown only
            elif sql and not sql.strip().lower().startswith('select'):
                st.markdown(sql)
            else:
                st.markdown(response_content)
                if isinstance(df, pd.DataFrame):
                    if df.empty:
                        st.info('No results found for this query.')
                    else:
                        # Add visualization options above the dataframe
                        if VISUALIZATION_AVAILABLE:
                            create_data_visualization(df, f"viz2_{hash(msg.get('content', ''))}")
                        
                        st.subheader("πŸ“‹ Query Results")
                        st.dataframe(df)
                        
                        # --- Save as CSV and View buttons ---
                        col1, col2 = st.columns(2)
                        with col1:
                            csv_filename = "chat_agent_output.csv"
                            st.download_button(
                                label="Download as CSV",
                                data=df.to_csv(index=False).encode('utf-8'),
                                file_name=csv_filename,
                                mime='text/csv',
                                key=f"csv_{msg.get('content', '')}"
                            )
                        with col2:
                            view_name = st.text_input(f"Enter view name to save as DB view (for this result):", key=f"view_{msg.get('content', '')}")
                            if st.button("Save as View", key=f"btn_view_{msg.get('content', '')}") and view_name:
                                safe_view_name = ''.join(c for c in view_name if c.isalnum() or c == '_')
                                # Use the last SQL if available
                                sql_to_use = sql if sql else ""
                                create_view_sql = f'''CREATE VIEW IF NOT EXISTS "{safe_view_name}" AS {sql_to_use.strip().rstrip(';')};'''
                                try:
                                    engine.execute(create_view_sql)
                                    st.success(f"View '{safe_view_name}' created successfully!")
                                except Exception as ve:
                                    st.error(f"Error creating view: {ve}")
                elif isinstance(df, str) and df.startswith('SQL Error:'):
                    st.error(df)

# === Prompt Tuning Agent Section ===
from langchain.prompts import PromptTemplate

# Helper: Suggest a better prompt using LLM
prompt_tuning_template = PromptTemplate(
    input_variables=["draft", "schema"],
    template="""
    You are an expert SQL query writer and prompt improvement assistant for a SQLite database. Given the following database schema:
    {schema}

    The user has written this draft prompt/question:
    "{draft}"

    Your job is to:
    - Suggest a clearer, more specific, and effective prompt that will help generate a correct SQL query for SQLite.
    - Use the exact table and column names as shown in the schema (including case, spaces, and special characters).
    - If the draft is already good, return it as is. Otherwise, rewrite it to be more explicit, mentioning relevant tables/columns if possible.
    - If the user's intent requires columns from multiple tables, make sure the improved prompt is clear about the relationship (e.g., join keys) and the aggregation or ranking needed.
    - Only return the improved prompt, no explanations.
    
    Example:
    Draft: top 3 product with highest revenue
    Improved: Show the top 3 products by total revenue, using the "Product Name" from the "Product" table and summing "Revenue (USD)" from the "Sales" table. Join "Product" and "Sales" on "Product ID". Order by total revenue descending and limit to 3 results.
    """
)

def suggest_better_prompt(draft, schema_info):
    chain = LLMChain(llm=llm, prompt=prompt_tuning_template)
    improved = chain.invoke({"draft": draft, "schema": schema_info})
    # Extract string if dict
    if isinstance(improved, dict):
        for key in ["text", "output", "result"]:
            if key in improved and isinstance(improved[key], str):
                improved = improved[key]
                break
        else:
            improved = str(improved)
    return improved.strip()

def generate_sql_for_prompt(prompt, schema_info):
    # --- Patch: Always refer to schema before generating SQL ---
    # If prompt does not mention schema, prepend schema info for LLM context
    schema_hint = f"Refer to this schema for table and column names:\n{schema_info}\n"
    prompt_with_schema = f"{schema_hint}{prompt}" if 'CREATE TABLE' not in prompt else prompt
    sql_chain = LLMChain(llm=llm, prompt=sql_prompt)
    sql = sql_chain.invoke({"question": prompt_with_schema, "schema": schema_info})
    if isinstance(sql, dict):
        for key in ["sql", "text", "output", "result"]:
            if key in sql and isinstance(sql[key], str):
                sql = sql[key]
                break
        else:
            sql = str(sql)
    # Extract SQL if explanation is included
    if isinstance(sql, str) and not sql.strip().lower().startswith("select"):
        for line in sql.splitlines():
            if line.strip().lower().startswith("select"):
                sql = line.strip()
                break
    # --- Patch: Auto-quote all table and column names for SQLite ---
    def auto_quote_sql(sql_str, schema_info):
        import re
        # Find all table and column names from schema
        tables = re.findall(r'CREATE TABLE "([^"]+)" \((.*?)\)', schema_info, re.DOTALL)
        table_names = [t[0] for t in tables]
        col_names = []
        for _, cols in tables:
            col_names += re.findall(r'"([^"]+)"', cols)
        # Quote table names not already quoted
        for t in table_names:
            # Only quote if not already quoted
            sql_str = re.sub(rf'(?<!["])\b{re.escape(t)}\b(?!["])', f'"{t}"', sql_str)
        # Quote column names not already quoted
        for c in col_names:
            # Only quote if not already quoted and not part of a string literal
            sql_str = re.sub(rf'(?<![\.\"])(?<!["])\b{re.escape(c)}\b(?!["])', f'"{c}"', sql_str)
        return sql_str
    sql = auto_quote_sql(sql, schema_info)
    return sql.strip()

def save_prompt_sql_pair(prompt, sql):
    # Save to prompts.jsonl
    with open(PROMPT_JSONL_PATH, "a", encoding="utf-8") as f:
        f.write(json.dumps({"prompt": prompt, "sql": sql}) + "\n")
    
    # Save to ChromaDB (if available)
    if chroma_collection is not None and embedding_model is not None:
        try:
            query_emb = embedding_model.encode([prompt], convert_to_numpy=True)
            existing_ids = chroma_collection.get().get('ids', [])
            next_id = str(len(existing_ids) + 1)
            
            chroma_collection.add(
                embeddings=query_emb,
                documents=[prompt],
                metadatas=[{"sql": sql}],
                ids=[next_id]
            )
        except Exception as e:
            st.warning(f"Could not save to vector DB: {e}")
    else:
        st.info("Vector DB not available - saved to local file only")

# === Streamlit Tabs: Main Agent and Prompt Tuning Agent ===


# === Multi-Agent Integration ===
from langchain.agents import initialize_agent, AgentType, Tool

# --- SQL Query Tool ---
def run_sql_query(sql: str) -> str:
    # Always limit result size for LLM safety
    import re
    sql_lc = sql.lower()
    if sql_lc.startswith("select") and "limit" not in sql_lc:
        # Add LIMIT 20 to queries without a limit
        if ";" in sql:
            sql = re.sub(r';\s*$', '', sql)
        sql += " LIMIT 20"
    try:
        df = pd.read_sql(sql, engine)
        return df.to_csv(index=False)
    except Exception as e:
        return f"SQL Error: {e}"

sql_query_tool = Tool(
    name="run_sql_query",
    func=run_sql_query,
    description="Execute a SQL query on the business database and return results as CSV."
)

# --- SQL Generation Tool ---
def generate_sql_tool(question: str) -> str:
    sql = generate_sql_for_prompt(question, db.get_table_info())
    return sql

sql_gen_tool = Tool(
    name="generate_sql",
    func=generate_sql_tool,
    description="Convert a natural language question to an optimized SQL query for the business database."
)

# --- PDF Q&A Tool ---
def ask_pdf_tool(question: str) -> str:
    pdf_files = list(st.session_state.get('uploaded_texts', {}).keys())
    if not pdf_files:
        return "No PDF uploaded."
    pdf_text = st.session_state['uploaded_texts'][pdf_files[0]]
    def chunk_text(text, chunk_size=800, overlap=100):
        chunks = []
        start = 0
        while start < len(text):
            end = min(start + chunk_size, len(text))
            chunk = text[start:end]
            chunks.append(chunk)
            start += chunk_size - overlap
        return chunks
    pdf_chunks = chunk_text(pdf_text)
    chunk_embeddings = embedding_model.encode(pdf_chunks, convert_to_numpy=True)
    from numpy import dot
    from numpy.linalg import norm
    q_emb = embedding_model.encode([question], convert_to_numpy=True)[0]
    sims = [dot(q_emb, chunk_emb)/(norm(q_emb)*norm(chunk_emb)) for chunk_emb in chunk_embeddings]
    best_idx = int(max(range(len(sims)), key=lambda i: sims[i]))
    best_chunk = pdf_chunks[best_idx]
    context_prompt = f"Context from PDF:\n{best_chunk}\n\nQuestion: {question}\nAnswer:"
    answer = llm.invoke(context_prompt)
    if isinstance(answer, dict):
        answer = answer.get('text', str(answer))
    return answer

pdf_qa_tool = Tool(
    name="ask_pdf",
    func=ask_pdf_tool,
    description="Answer questions based on the uploaded PDF content using semantic search and LLM."
)

# --- Initialize Multi-Agent ---

# --- Enhanced Multi-Agent with Context-Aware Reasoning ---

from langchain.memory import ConversationBufferMemory
multi_tools = [sql_query_tool, sql_gen_tool, pdf_qa_tool]
conversation_memory = ConversationBufferMemory(
    memory_key="chat_history",
    return_messages=True
)
multi_agent = initialize_agent(
    tools=multi_tools,
    llm=llm,
    agent=AgentType.CONVERSATIONAL_REACT_DESCRIPTION,
    memory=conversation_memory,
    verbose=True
)

# Helper: Analyze sales drop for a product using previous DataFrame
def analyze_sales_drop(product_name=None, product_id=None):
    # Use last DataFrame and question from session state
    last_df = st.session_state.get('last_result_df')
    last_question = st.session_state.get('last_data_question', '')
    if last_df is None:
        return "No previous data available for analysis."
    # Try to detect sales drop by comparing sales over time
    if product_name and 'Product Name' in last_df.columns:
        df_product = last_df[last_df['Product Name'] == product_name]
    elif product_id and 'Product ID' in last_df.columns:
        df_product = last_df[last_df['Product ID'] == product_id]
    else:
        df_product = last_df
    # If sales data available
    if 'Revenue (USD)' in df_product.columns and 'Month' in df_product.columns:
        trend = df_product.groupby('Month')['Revenue (USD)'].sum().sort_index()
        if len(trend) > 1:
            diffs = trend.diff().fillna(0)
            drop_months = [m for m, d in zip(trend.index, diffs) if d < 0]
            if drop_months:
                return f"Sales dropped in months: {', '.join(map(str, drop_months))}. Trend: {trend.to_dict()}"
            else:
                return f"No sales drop detected. Trend: {trend.to_dict()}"
        else:
            return "Not enough data to detect sales trend."
    return "Sales data not available for this product."

tab1, tab2, tab3, tab4 = st.tabs(["SQL Chat Agent", "Prompt Tuning Agent", "PDF Q&A Agent", "Multi-Agent Q&A"])


# --- PDF Q&A Agent Tab ---
with tab3:
    st.markdown("### PDF Q&A Agent")
    st.write("Ask questions about the uploaded PDF. The agent will answer using semantic search and LLM.")
    pdf_files = list(st.session_state.get('uploaded_texts', {}).keys())
    if not pdf_files:
        st.warning("No PDF uploaded. Please upload a PDF in the sidebar.")
    else:
        selected_pdf = st.selectbox("Select PDF to query:", pdf_files)
        pdf_text = st.session_state['uploaded_texts'][selected_pdf]
        user_pdf_question = st.text_input("Ask a question about the PDF:")
        if user_pdf_question:
            def chunk_text(text, chunk_size=800, overlap=100):
                chunks = []
                start = 0
                while start < len(text):
                    end = min(start + chunk_size, len(text))
                    chunk = text[start:end]
                    chunks.append(chunk)
                    start += chunk_size - overlap
                return chunks
            pdf_chunks = chunk_text(pdf_text)
            chunk_embeddings = embedding_model.encode(pdf_chunks, convert_to_numpy=True)
            from numpy import dot
            from numpy.linalg import norm
            q_emb = embedding_model.encode([user_pdf_question], convert_to_numpy=True)[0]
            sims = [dot(q_emb, chunk_emb)/(norm(q_emb)*norm(chunk_emb)) for chunk_emb in chunk_embeddings]
            best_idx = int(max(range(len(sims)), key=lambda i: sims[i]))
            best_chunk = pdf_chunks[best_idx]
            context_prompt = f"Context from PDF:\n{best_chunk}\n\nQuestion: {user_pdf_question}\nAnswer:"
            answer = llm.invoke(context_prompt)
            if isinstance(answer, dict):
                answer = answer.get('text', str(answer))
            st.markdown("**PDF Q&A Response:**")
            st.write(answer)

with tab4:
    st.markdown("### Multi-Agent Q&A")
    st.write("Ask any complex question. The agent will use SQL, prompt tuning, and PDF Q&A tools as needed.")
    user_multi_question = st.text_input("Ask a question across tools (SQL + PDF + Prompt):")
    # multi_agent is already initialized above
    if user_multi_question:
        # Context-aware follow-up detection
        followup_keywords = ["why sales got reduce", "why did sales drop", "reason for sales drop", "sales decrease"]
        matched = any(k in user_multi_question.lower() for k in followup_keywords)
        product_name = None
        product_id = None
        import re
        name_match = re.search(r'product name ([\w\s]+)', user_multi_question.lower())
        id_match = re.search(r'productid (\d+)', user_multi_question.lower())
        if name_match:
            product_name = name_match.group(1).strip()
        if id_match:
            product_id = id_match.group(1).strip()
        if matched:
            analysis = analyze_sales_drop(product_name=product_name, product_id=product_id)
            st.markdown(f"**Sales Drop Analysis:**\n{analysis}")
            st.session_state['chat_history'].append({'role': 'user', 'content': user_multi_question})
            st.session_state['chat_history'].append({'role': 'agent', 'content': analysis})
        else:
            response = multi_agent.run(user_multi_question)
            st.markdown("**Agent Response:**")
            st.write(response)
            st.session_state['chat_history'].append({'role': 'user', 'content': user_multi_question})
            st.session_state['chat_history'].append({'role': 'agent', 'content': response})