Spaces:
Sleeping
Sleeping
Download app.py from prithvi55/talk2data: direct link, hf CLI and curl.
- Browser
- Download file 64.2 kB
-
https://huggingface.co/spaces/prithvi55/talk2data/resolve/main/app.py
- Command line
-
hf download hf://spaces/prithvi55/talk2data/app.py
-
curl -L -o app.py https://huggingface.co/spaces/prithvi55/talk2data/resolve/main/app.py
64.2 kB
import os
import pandas as pd
import streamlit as st
import re
# โ
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, extract_csv_text, extract_excel_text, extract_json_text, extract_docx_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
# === Document Storage Functions ===
def chunk_text(text, chunk_size=800, overlap=100):
"""Split text into overlapping chunks"""
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
def store_document_chunks(filename, text, file_type, chroma_collection, embedding_model):
"""Store document chunks in vector database with metadata"""
try:
if not text or not text.strip():
st.warning(f"No text content found in {filename}")
return False
# Create chunks based on file type
if file_type in ['pdf', 'txt', 'docx']:
# For text documents, use standard chunking
chunks = chunk_text(text, chunk_size=800, overlap=100)
chunk_type = "text_chunk"
elif file_type in ['csv', 'excel']:
# For structured data, treat entire content as context
chunks = [text] # Store the summary as a single chunk
chunk_type = "data_summary"
else:
chunks = chunk_text(text, chunk_size=800, overlap=100)
chunk_type = "text_chunk"
# Generate embeddings for all chunks
chunk_embeddings = embedding_model.encode(chunks, convert_to_numpy=True)
# Get existing IDs to avoid conflicts
existing_data = chroma_collection.get()
existing_ids = existing_data.get('ids', [])
# Remove existing chunks for this file (if any)
file_ids_to_remove = [id for id in existing_ids if id.startswith(f"doc_{filename}_")]
if file_ids_to_remove:
chroma_collection.delete(ids=file_ids_to_remove)
st.info(f"Removed {len(file_ids_to_remove)} existing chunks for {filename}")
# Add new chunks
chunk_ids = []
chunk_documents = []
chunk_metadatas = []
embeddings_list = []
for i, (chunk, embedding) in enumerate(zip(chunks, chunk_embeddings)):
chunk_id = f"doc_{filename}_{i}"
chunk_ids.append(chunk_id)
chunk_documents.append(chunk)
chunk_metadatas.append({
"filename": filename,
"file_type": file_type,
"chunk_index": i,
"chunk_type": chunk_type,
"total_chunks": len(chunks),
"source": "uploaded_document"
})
embeddings_list.append(embedding.tolist())
# Add to ChromaDB
chroma_collection.add(
embeddings=embeddings_list,
documents=chunk_documents,
metadatas=chunk_metadatas,
ids=chunk_ids
)
# st.success(f"โ
Stored {len(chunks)} chunks from {filename} in vector database") # Hidden for cleaner UI
return True
except Exception as e:
st.error(f"โ Error storing chunks for {filename}: {str(e)}")
return False
def create_csv_context(df, filename):
"""Create comprehensive context for CSV data that can be used for queries"""
try:
context_parts = []
# Basic info
context_parts.append(f"Dataset: {filename}")
context_parts.append(f"Shape: {df.shape[0]} rows ร {df.shape[1]} columns")
# Column information with data types and sample values
context_parts.append("\nColumns and Data Types:")
for col in df.columns:
dtype = str(df[col].dtype)
non_null_count = df[col].count()
# Get sample values (excluding nulls)
sample_values = df[col].dropna().head(3).tolist()
sample_str = ", ".join([str(v)[:50] for v in sample_values])
context_parts.append(f"- {col} ({dtype}): {non_null_count}/{len(df)} non-null values")
if sample_str:
context_parts.append(f" Sample values: {sample_str}")
# Summary statistics for numeric columns
numeric_cols = df.select_dtypes(include=['number']).columns
if len(numeric_cols) > 0:
context_parts.append("\nNumeric Column Statistics:")
for col in numeric_cols[:5]: # Limit to first 5 numeric columns
stats = df[col].describe()
context_parts.append(f"- {col}: min={stats['min']:.2f}, max={stats['max']:.2f}, mean={stats['mean']:.2f}")
# Sample data
context_parts.append(f"\nSample Data (first 5 rows):")
context_parts.append(df.head().to_string(index=False))
# Unique values for categorical columns (if small enough)
categorical_cols = df.select_dtypes(include=['object']).columns
for col in categorical_cols[:3]: # Limit to first 3 categorical columns
unique_vals = df[col].unique()
if len(unique_vals) <= 10:
context_parts.append(f"\nUnique values in {col}: {', '.join(map(str, unique_vals))}")
else:
context_parts.append(f"\nUnique values in {col}: {len(unique_vals)} unique values")
context_parts.append(f"Sample values: {', '.join(map(str, unique_vals[:5]))}")
return "\n".join(context_parts)
except Exception as e:
return f"Error creating CSV context: {str(e)}"
# โ
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', 'break this down', 'break it down',
'group by', 'group this', 'filter by', 'filter this', 'sort by', 'order by',
'can you', 'could you', 'please', 'now', 'then', 'next', 'also show',
'what if', 'how about', 'instead', 'rather', 'but', 'however', 'compare',
'vs ', 'versus', 'against', 'difference', 'change this', 'modify this',
'add ', 'include', 'exclude', 'remove', 'without', 'only', 'just',
'for the', 'in the', 'during', 'between', 'from the', 'to the'
]
followup_patterns = [
r'\b(this|that|it|these|those)\b', # Referential pronouns
r'\b(same|previous|last|above|before)\b', # Temporal references
r'\b(more|less|greater|smaller|higher|lower)\b', # Comparative terms
r'\b(details?|breakdown|analysis|summary)\b', # Analysis requests
r'\b(why|how|when|where)\s+(did|does|is|are|was|were)\b', # Question patterns
]
def is_followup_question(q):
ql = q.strip().lower()
# Check starter words
if any(ql.startswith(st) for st in followup_starters):
return True
# Check patterns using regex
import re
for pattern in followup_patterns:
if re.search(pattern, ql):
return True
# Check if question is very short (likely a follow-up)
if len(ql.split()) <= 3 and any(word in ql for word in ['what', 'how', 'why', 'where', 'when', 'who']):
return True
return False
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)
# === Utility Functions ===
def extract_llm_content(response):
"""
Extract text content from various LLM response formats
"""
if hasattr(response, 'content'):
return response.content
elif isinstance(response, dict):
return response.get('text', response.get('content', str(response)))
else:
return str(response)
def fix_duplicate_columns(df):
"""
Fix duplicate column names in DataFrame by adding suffixes
"""
if df is None or df.empty:
return df
# Get column names
columns = df.columns.tolist()
# Check for duplicates
seen = {}
new_columns = []
for col in columns:
if col in seen:
seen[col] += 1
new_columns.append(f"{col}_{seen[col]}")
else:
seen[col] = 1
new_columns.append(col)
# Only rename if there were duplicates
if len(set(columns)) != len(columns):
df.columns = new_columns
return df
def build_conversation_context(max_exchanges=3):
"""
Build enhanced context from recent chat history including results
"""
if 'chat_history' not in st.session_state or not st.session_state['chat_history']:
return ""
history = st.session_state['chat_history']
recent_history = history[-max_exchanges*2:] if len(history) > max_exchanges*2 else history
context_parts = ["Recent conversation context:"]
for i in range(0, len(recent_history), 2):
if i + 1 < len(recent_history):
user_msg = recent_history[i]
agent_msg = recent_history[i + 1]
context_parts.append(f"Q: {user_msg.get('content', '')}")
# Include SQL if available
if agent_msg.get('sql'):
context_parts.append(f"SQL: {agent_msg['sql']}")
# Include result summary if available
if agent_msg.get('df') is not None and hasattr(agent_msg['df'], 'shape'):
df = agent_msg['df']
context_parts.append(f"Result: {df.shape[0]} rows returned")
if df.shape[0] > 0:
# Add column names for reference
context_parts.append(f"Columns: {', '.join(df.columns.tolist())}")
context_parts.append("---")
return "\n".join(context_parts) if len(context_parts) > 1 else ""
def get_enhanced_context_for_followup(user_query):
"""
Create enhanced context for follow-up questions
"""
context_parts = []
# Add conversation context
conv_context = build_conversation_context(max_exchanges=2)
if conv_context:
context_parts.append(conv_context)
# Add last result columns if available for column references
if 'last_result_df' in st.session_state and st.session_state['last_result_df'] is not None:
df = st.session_state['last_result_df']
if hasattr(df, 'columns'):
context_parts.append(f"Available columns from last result: {', '.join(df.columns.tolist())}")
# Add sample values for categorical columns
categorical_cols = df.select_dtypes(include=['object']).columns
if len(categorical_cols) > 0:
sample_values = []
for col in categorical_cols[:3]: # Limit to first 3 categorical columns
unique_vals = df[col].unique()[:5] # First 5 unique values
sample_values.append(f"{col}: {', '.join(map(str, unique_vals))}")
if sample_values:
context_parts.append(f"Sample values: {'; '.join(sample_values)}")
# Add last data question
if 'last_data_question' in st.session_state:
context_parts.append(f"Last main question: {st.session_state['last_data_question']}")
return "\n\n".join(context_parts) if context_parts else ""
# 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()
# Hide vector DB status/info messages unless error or warning
if stats["status"] != "healthy":
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, Excel, Word, or JSON files to query their content')
uploaded_files = st.file_uploader(
"Upload one or more files (PDF, CSV, Excel, DOCX, JSON)",
type=["pdf", "csv", "xlsx", "xls", "json", "docx"],
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
# Create comprehensive CSV context for vector storage
csv_context = create_csv_context(df, filename)
st.session_state['uploaded_texts'][filename] = csv_context
# Store in vector database
if chroma_collection is not None and embedding_model is not None:
store_document_chunks(filename, csv_context, 'csv', chroma_collection, embedding_model)
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
# Create comprehensive Excel context for vector storage
excel_context = create_csv_context(df, filename) # Same logic as CSV
st.session_state['uploaded_texts'][filename] = excel_context
# Store in vector database
if chroma_collection is not None and embedding_model is not None:
store_document_chunks(filename, excel_context, 'excel', chroma_collection, embedding_model)
st.success(f"Excel loaded: {filename} (shape: {df.shape})")
elif filename.endswith('.json'):
# Extract text summary for Q&A
text, error = extract_json_text(uploaded_file)
if text:
st.session_state['uploaded_texts'][filename] = text
# Store in vector database
if chroma_collection is not None and embedding_model is not None:
store_document_chunks(filename, text, 'json', chroma_collection, embedding_model)
st.success(f"JSON loaded: {filename} (chars: {len(text)})")
else:
st.error(f"JSON error: {error}")
elif filename.endswith('.pdf'):
text, error = extract_pdf_text(uploaded_file)
if text:
st.session_state['uploaded_texts'][filename] = text
# Store in vector database
if chroma_collection is not None and embedding_model is not None:
store_document_chunks(filename, text, 'pdf', chroma_collection, embedding_model)
st.success(f"PDF loaded: {filename} (chars: {len(text)})")
else:
st.error(f"PDF error: {error}")
elif filename.endswith('.docx'):
text, error = extract_docx_text(uploaded_file)
if text:
st.session_state['uploaded_texts'][filename] = text
# Store in vector database
if chroma_collection is not None and embedding_model is not None:
store_document_chunks(filename, text, 'docx', chroma_collection, embedding_model)
st.success(f"Word document loaded: {filename} (chars: {len(text)})")
else:
st.error(f"DOCX error: {error}")
# 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 File Text (preview):')
for fname, text in st.session_state['uploaded_texts'].items():
st.write(f"**{fname}**: {text[:500]}{'...' if len(text) > 500 else ''}")
# Vector Database Status
if chroma_collection is not None:
with st.expander("๐ Vector Database Status", expanded=False):
try:
# Get collection stats
collection_data = chroma_collection.get(include=['metadatas'])
total_items = len(collection_data.get('ids', []))
if total_items > 0:
# Count by source type
metadatas = collection_data.get('metadatas', [])
source_counts = {}
doc_counts = {}
for meta in metadatas:
source = meta.get('source', 'unknown')
filename = meta.get('filename', 'unknown')
source_counts[source] = source_counts.get(source, 0) + 1
if filename != 'unknown':
doc_counts[filename] = doc_counts.get(filename, 0) + 1
st.write(f"**Total chunks stored:** {total_items}")
if doc_counts:
st.write("**Documents in vector database:**")
for doc, count in doc_counts.items():
st.write(f"- {doc}: {count} chunks")
if source_counts:
st.write("**Content by source:**")
for source, count in source_counts.items():
if source == 'uploaded_document':
st.write(f"- ๐ Uploaded documents: {count} chunks")
elif source == 'jsonl_import':
st.write(f"- ๐พ Imported prompts: {count} items")
else:
st.write(f"- {source}: {count} items")
# Add clear documents button
col1, col2 = st.columns(2)
with col1:
if st.button("๐๏ธ Clear Document Chunks", help="Remove all uploaded document chunks from vector database"):
try:
# Get all document chunk IDs
all_data = chroma_collection.get()
doc_ids = [id for id in all_data.get('ids', []) if id.startswith('doc_')]
if doc_ids:
chroma_collection.delete(ids=doc_ids)
# st.success(f"Removed {len(doc_ids)} document chunks from vector database") # Hidden for cleaner UI
st.rerun()
else:
st.info("No document chunks to remove")
except Exception as e:
st.error(f"Error clearing documents: {e}")
with col2:
if st.button("๐ Refresh Status", help="Refresh vector database status"):
st.rerun()
else:
st.write("No items in vector database yet.")
except Exception as e:
st.write(f"Error checking database status: {e}")
# === 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)
df = fix_duplicate_columns(df)
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)
df = fix_duplicate_columns(df)
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)
df = fix_duplicate_columns(df)
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}"
# Enhanced context-aware follow-up handling
if 'last_data_question' in st.session_state and is_followup_question(user_query):
st.write(f"[DEBUG] Enhanced follow-up detected")
# Build enhanced context
enhanced_context = get_enhanced_context_for_followup(user_query)
if enhanced_context:
user_query = f"{enhanced_context}\n\nCurrent follow-up question: {user_query}"
else:
# Fallback to simple context
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)
# Fix duplicate column names
df = fix_duplicate_columns(df)
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
st.write("๐ค Voice recording functionality has been removed.")
user_query = st.chat_input("๐ฌ Ask about your business data or upload files to analyze...", key="main_chat_input")
# If you want to convert speech to text, send this audio to an ASR model
# 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...", key="secondary_chat_input")
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
})
# Agent 1 Scope checkbox to show metadata information
agent1_scope = st.checkbox('Agent 1 Scope', help="Show database table information")
if agent1_scope:
st.subheader("๐ Agent 1 Scope - Database Tables")
# Database Schema Section - Just show table names
schema_info = db.get_table_info()
# Parse schema and display just table names
tables = re.findall(r'CREATE TABLE \"([^\"]+)\" \((.*?)\)', schema_info, re.DOTALL)
if tables:
st.markdown("**Available Tables:**")
table_names = [table_name for table_name, _ in tables]
# Display table names in a simple format
for i, table_name in enumerate(table_names, 1):
st.write(f"{i}. **{table_name}**")
else:
st.write("No tables found in database")
# Show all prompts in ChromaDB checkbox
show_prompts = st.checkbox("Show Vector DB Prompts", help="Display all prompts stored in vector database")
if show_prompts:
st.subheader("๐ง Vector Database Prompts")
if chroma_collection is not None:
try:
chroma_data = chroma_collection.get()
documents = chroma_data.get('documents', [])
metadatas = chroma_data.get('metadatas', [])
if documents:
st.write(f"**Total prompts: {len(documents)}**")
for i, doc in enumerate(documents):
metadata = metadatas[i] if i < len(metadatas) else {}
sql = metadata.get('sql', 'No SQL available')
with st.expander(f"Prompt {i+1}: {doc[:50]}{'...' if len(doc) > 50 else ''}", expanded=False):
st.write("**Prompt:**")
st.write(doc)
st.write("**SQL:**")
st.code(sql, language='sql')
else:
st.info("No prompts found in vector database")
except Exception as e:
st.error(f"Error accessing vector DB: {e}")
else:
st.warning("Vector database not available")
# Agent 2 Scope checkbox (disabled - not used)
agent2_scope = st.checkbox('Agent 2 Scope', disabled=True, help="Agent 2 functionality - Currently not implemented")
if agent2_scope:
st.info("๐ง Agent 2 is not yet implemented")
# Agent 3 Scope checkbox (disabled - not used)
agent3_scope = st.checkbox('Agent 3 Scope', disabled=True, help="Agent 3 functionality - Currently not implemented")
if agent3_scope:
st.info("๐ง Agent 3 is not yet implemented")
# 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:
# Fix duplicate column names
df = fix_duplicate_columns(df)
# 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}") # Hidden for cleaner UI
pass
else:
# st.info("Vector DB not available - saved to local file only") # Hidden for cleaner UI
pass
# === 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)
df = fix_duplicate_columns(df)
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."
)
# --- Document Q&A Tool (Enhanced with Vector DB) ---
def ask_document_tool(question: str) -> str:
"""Answer questions using documents stored in vector database"""
try:
if chroma_collection is None or embedding_model is None:
return "Vector database not available. Please check your setup."
# Get question embedding
question_embedding = embedding_model.encode([question], convert_to_numpy=True)
# Search vector database for relevant document chunks
try:
results = chroma_collection.query(
query_embeddings=question_embedding.tolist(),
n_results=5, # Get top 5 most relevant chunks
include=['documents', 'metadatas', 'distances']
)
if not results['documents'] or not results['documents'][0]:
return "No relevant documents found. Please upload some documents first."
# Process results to build context
contexts = []
sources = []
for i, (doc, metadata, distance) in enumerate(zip(
results['documents'][0],
results['metadatas'][0],
results['distances'][0]
)):
if distance < 1.5: # Only include reasonably relevant chunks
file_type = metadata.get('file_type', 'unknown')
filename = metadata.get('filename', 'unknown')
chunk_type = metadata.get('chunk_type', 'text_chunk')
if chunk_type == 'data_summary':
contexts.append(f"[Data from {filename}]:\n{doc}")
else:
contexts.append(f"[Text from {filename}]:\n{doc}")
sources.append(f"{filename} ({file_type})")
if not contexts:
return "No sufficiently relevant content found for your question."
# Build comprehensive prompt
context_text = "\n\n".join(contexts[:3]) # Use top 3 contexts
unique_sources = list(set(sources[:3]))
# Different prompts for data vs text questions
if any('data_summary' in str(meta.get('chunk_type', '')) for meta in results['metadatas'][0][:3]):
# Data-focused prompt
prompt = f"""Based on the following data sources, answer the question:
Context from uploaded files:
{context_text}
Question: {question}
Instructions:
- Provide a clear, data-driven answer
- Reference specific data points when relevant
- If the question requires analysis not directly shown in the context, indicate what additional analysis would be needed
- Mention which files the answer is based on
Answer:"""
else:
# Text-focused prompt
prompt = f"""Based on the following document content, answer the question:
Context from uploaded documents:
{context_text}
Question: {question}
Instructions:
- Provide a comprehensive answer based on the context
- Quote relevant parts when helpful
- If the answer is not fully contained in the context, indicate this clearly
- Mention which documents the answer is based on
Answer:"""
# Get LLM response
answer = llm.invoke(prompt)
answer_text = extract_llm_content(answer)
# Add source information
source_info = f"\n\n๐ Sources: {', '.join(unique_sources)}"
return answer_text + source_info
except Exception as e:
st.error(f"Error querying vector database: {str(e)}")
return f"Error searching documents: {str(e)}"
except Exception as e:
return f"Error in document query: {str(e)}"
document_qa_tool = Tool(
name="ask_documents",
func=ask_document_tool,
description="Answer questions based on uploaded documents (PDF, CSV, Excel, JSON) using semantic search across the vector database."
)
# --- Data Analysis Tool for CSV/Excel ---
def analyze_data_tool(question: str) -> str:
"""Analyze uploaded CSV/Excel data using pandas operations"""
try:
uploaded_dfs = st.session_state.get('uploaded_dfs', {})
if not uploaded_dfs:
return "No CSV or Excel files uploaded for analysis."
# For now, use the first uploaded DataFrame
filename = list(uploaded_dfs.keys())[0]
df = uploaded_dfs[filename]
# Create a prompt to generate pandas code
columns_info = []
for col in df.columns:
dtype = str(df[col].dtype)
sample_vals = df[col].dropna().head(3).tolist()
columns_info.append(f"- {col} ({dtype}): sample values {sample_vals}")
columns_str = "\n".join(columns_info)
analysis_prompt = f"""Given a pandas DataFrame called 'df' with the following structure:
Filename: {filename}
Shape: {df.shape}
Columns:
{columns_str}
Question: {question}
Generate Python code using pandas to answer this question. The code should:
1. Use the variable 'df' for the DataFrame
2. Be safe to execute (no file operations, imports, etc.)
3. Return a result that answers the question
4. Handle potential errors gracefully
Provide only the Python code, no explanations:"""
# Get code from LLM
code_response = llm.invoke(analysis_prompt)
code = extract_llm_content(code_response)
# Clean up the code
code = code.strip()
if code.startswith('```python'):
code = code[9:]
if code.startswith('```'):
code = code[3:]
if code.endswith('```'):
code = code[:-3]
code = code.strip()
# Execute the code safely
try:
# Create a safe execution environment
safe_globals = {
'df': df,
'pd': pd,
'np': __import__('numpy'),
'len': len,
'str': str,
'int': int,
'float': float,
'sum': sum,
'max': max,
'min': min,
'round': round
}
# Execute the code
local_vars = {}
exec(code, safe_globals, local_vars)
# Try to get the result
if 'result' in local_vars:
result = local_vars['result']
else:
# If no explicit result variable, evaluate the last expression
lines = code.strip().split('\n')
last_line = lines[-1].strip()
if not (last_line.startswith('print') or last_line.startswith('df')):
result = eval(last_line, safe_globals, local_vars)
else:
result = "Code executed successfully, but no result to display."
# Format the result
if hasattr(result, 'to_string'): # DataFrame or Series
if len(str(result)) > 2000: # Truncate if too long
result_str = str(result)[:2000] + "...\n(Result truncated)"
else:
result_str = str(result)
else:
result_str = str(result)
return f"Analysis of {filename}:\n\n{result_str}\n\nCode used:\n```python\n{code}\n```"
except Exception as e:
return f"Error executing analysis: {str(e)}\n\nGenerated code:\n```python\n{code}\n```"
except Exception as e:
return f"Error in data analysis: {str(e)}"
data_analysis_tool = Tool(
name="analyze_data",
func=analyze_data_tool,
description="Analyze uploaded CSV/Excel data using pandas operations. Can perform calculations, filtering, grouping, and statistical analysis."
)
# --- Initialize Multi-Agent ---
# --- Enhanced Multi-Agent with Context-Aware Reasoning ---
from langchain.memory import ConversationBufferMemory
multi_tools = [sql_query_tool, sql_gen_tool, document_qa_tool, data_analysis_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)
answer_text = extract_llm_content(answer)
st.markdown("**PDF Q&A Response:**")
st.write(answer_text)
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})
import os
import pandas as pd
import streamlit as st
import re
# โ
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, extract_csv_text, extract_excel_text, extract_json_text, extract_docx_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
# === Document Storage Functions ===
def chunk_text(text, chunk_size=800, overlap=100):
"""Split text into overlapping chunks"""
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
def store_document_chunks(filename, text, file_type, chroma_collection, embedding_model):
"""Store document chunks in vector database with metadata"""
try:
if not text or not text.strip():
st.warning(f"No text content found in {filename}")
return False
# Create chunks based on file type
if file_type in ['pdf', 'txt', 'docx']:
# For text documents, use standard chunking
chunks = chunk_text(text, chunk_size=800, overlap=100)
chunk_type = "text_chunk"
elif file_type in ['csv', 'excel']:
# For structured data, treat entire content as context
chunks = [text] # Store the summary as a single chunk
chunk_type = "data_summary"
else:
chunks = chunk_text(text, chunk_size=800, overlap=100)
chunk_type = "text_chunk"
# Generate embeddings for all chunks
chunk_embeddings = embedding_model.encode(chunks, convert_to_numpy=True)
# Get existing IDs to avoid conflicts
existing_data = chroma_collection.get()
existing_ids = existing_data.get('ids', [])
# Remove existing chunks for this file (if any)
file_ids_to_remove = [id for id in existing_ids if id.startswith(f"doc_{filename}_")]
if file_ids_to_remove:
chroma_collection.delete(ids=file_ids_to_remove)
st.info(f"Removed {len(file_ids_to_remove)} existing chunks for {filename}")
# Add new chunks
chunk_ids = []
chunk_documents = []
chunk_metadatas = []
embeddings_list = []
for i, (chunk, embedding) in enumerate(zip(chunks, chunk_embeddings)):
chunk_id = f"doc_{filename}_{i}"
chunk_ids.append(chunk_id)
chunk_documents.append(chunk)
chunk_metadatas.append({
"filename": filename,
"file_type": file_type,
"chunk_index": i,
"chunk_type": chunk_type,
"total_chunks": len(chunks),
"source": "uploaded_document"
})
embeddings_list.append(embedding.tolist())
# Add to ChromaDB
chroma_collection.add(
embeddings=embeddings_list,