AliInamdar commited on
Commit
c18bc78
Β·
verified Β·
1 Parent(s): fd33596

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -0
app.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import duckdb
4
+ import requests
5
+ import re
6
+ import io
7
+
8
+ # πŸ” Set your Together API key securely
9
+ TOGETHER_API_KEY = st.secrets["TOGETHER_API_KEY"] if "TOGETHER_API_KEY" in st.secrets else st.text_input("Enter Together API Key", type="password")
10
+
11
+ # 🧠 Generate SQL using Together API
12
+ def generate_sql_from_prompt(prompt, df):
13
+ schema = ", ".join([f"{col} ({str(dtype)})" for col, dtype in df.dtypes.items()])
14
+ full_prompt = f"""
15
+ You are a SQL expert. Here is a table called 'df' with the following schema:
16
+ {schema}
17
+
18
+ User question: "{prompt}"
19
+
20
+ Write a valid SQL query using the 'df' table. Return only the SQL code.
21
+ """
22
+ url = "https://api.together.xyz/v1/chat/completions"
23
+ headers = {
24
+ "Authorization": f"Bearer {TOGETHER_API_KEY}",
25
+ "Content-Type": "application/json"
26
+ }
27
+ payload = {
28
+ "model": "mistralai/Mixtral-8x7B-Instruct-v0.1",
29
+ "messages": [{"role": "user", "content": full_prompt}],
30
+ "temperature": 0.2,
31
+ "max_tokens": 200
32
+ }
33
+
34
+ response = requests.post(url, headers=headers, json=payload)
35
+ response.raise_for_status()
36
+ result = response.json()
37
+ return result['choices'][0]['message']['content'].strip("```sql").strip("```").strip()
38
+
39
+ # 🧽 Clean SQL for DuckDB
40
+ def clean_sql_for_duckdb(sql, df_columns):
41
+ sql = sql.replace("`", '"')
42
+ for col in df_columns:
43
+ if " " in col and f'"{col}"' not in sql:
44
+ pattern = r'\b' + re.escape(col) + r'\b'
45
+ sql = re.sub(pattern, f'"{col}"', sql)
46
+ return sql
47
+
48
+ # === Streamlit UI ===
49
+ st.set_page_config(page_title="🧠 Excel SQL Chatbot", layout="centered")
50
+ st.title("πŸ“Š Excel SQL Chatbot with LLM")
51
+ st.markdown("Upload your **Excel file**, ask a question in natural language, and get results from SQL queries generated by an LLM.")
52
+
53
+ uploaded_file = st.file_uploader("πŸ“‚ Upload Excel file", type=["xlsx"])
54
+
55
+ if uploaded_file and TOGETHER_API_KEY:
56
+ df = pd.read_excel(uploaded_file)
57
+ st.success(f"βœ… Loaded: {uploaded_file.name} with shape {df.shape}")
58
+ st.dataframe(df.head(), use_container_width=True)
59
+
60
+ user_prompt = st.text_input("πŸ’¬ Ask a question about your data")
61
+
62
+ if st.button("πŸš€ Generate SQL & Run") and user_prompt:
63
+ try:
64
+ sql_query = generate_sql_from_prompt(user_prompt, df)
65
+ cleaned_sql = clean_sql_for_duckdb(sql_query, df.columns)
66
+
67
+ st.code(sql_query, language="sql")
68
+
69
+ con = duckdb.connect()
70
+ con.register("df", df)
71
+ result_df = con.execute(cleaned_sql).fetchdf()
72
+
73
+ st.success("βœ… Query executed successfully")
74
+ st.dataframe(result_df, use_container_width=True)
75
+
76
+ except Exception as e:
77
+ st.error(f"❌ Error: {e}")
78
+ else:
79
+ st.info("πŸ”‘ Please upload a file and provide the API key to continue.")