talk2data / app.py
prithvi55's picture
Update app.py
26eeefb verified
Raw History Blame
37.4 kB
import os
import pandas as pd
import streamlit as st
#from st_mic_recorder import mic_recorder
from streamlit_mic_recorder import mic_recorder
# โœ… 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
#Add voice icon
st.write("๐ŸŽค Click to record your question")
voice_input = mic_recorder(
start_prompt="Start Recording",
stop_prompt="Stop Recording",
just_once=True,
use_container_width=True
)
if voice_input:
st.write("โœ… Recorded audio!")
# If you want to convert speech to text, send this audio to an ASR model
#==========GPT5
from transformers import pipeline
import tempfile
asr = pipeline("automatic-speech-recognition", model="openai/whisper-small")
if voice_input:
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
tmp_file.write(voice_input["bytes"])
tmp_file_path = tmp_file.name
result = asr(tmp_file_path)
query_text = result["text"]
st.write(f"๐Ÿ—ฃ You said: {query_text}")
# 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})