Gaurav-2273 commited on
Commit
6ea8ee7
·
verified ·
1 Parent(s): e0f0d5b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -27
app.py CHANGED
@@ -4,18 +4,18 @@ import sqlite3
4
  import pandas as pd
5
  import os
6
 
7
- # --- 1. CONFIG & API ---
8
- st.set_page_config(page_title="Agentic SQL", page_icon="🕵️‍♂️")
9
 
10
- # CRITICAL: This is where you use the key you just copied
11
- api_key = os.getenv("GEMINI_API_KEY")
12
 
13
  if api_key:
14
  genai.configure(api_key=api_key)
15
  else:
16
- st.error("⚠️ API Key missing! Add it to Hugging Face Settings > Secrets.")
17
 
18
- # --- 2. DB SETUP ---
19
  DB_NAME = "sales.db"
20
  def init_db():
21
  conn = sqlite3.connect(DB_NAME)
@@ -30,37 +30,47 @@ def init_db():
30
  if not os.path.exists(DB_NAME):
31
  init_db()
32
 
33
- # --- 3. AGENT LOGIC ---
34
  def sql_agent(user_prompt):
35
- # FALLBACK LOGIC: If 'flash' fails due to the 404 error, we try 'gemini-pro'
36
- try:
37
- model = genai.GenerativeModel('gemini-1.5-flash')
38
- except:
39
- model = genai.GenerativeModel('gemini-pro')
40
-
41
- conn = sqlite3.connect(DB_NAME)
42
- schema = "Table: customers (id, name, region); Table: products (id, name, category, price)"
43
 
44
- prompt = f"System: Output ONLY SQLite SQL. Schema: {schema}\nUser: {user_prompt}"
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
  try:
47
  response = model.generate_content(prompt)
48
  sql = response.text.strip().replace('```sql', '').replace('```', '')
 
 
49
  df = pd.read_sql_query(sql, conn)
 
50
  return df, None, sql
51
  except Exception as e:
52
  return None, str(e), "Error"
53
- finally:
54
- conn.close()
55
 
56
  # --- 4. UI ---
57
- st.title("🕵️‍♂️ Agentic SQL Fix")
58
- query = st.text_input("Ask your DB:", "List all North customers")
59
 
60
- if st.button("Run"):
61
- data, err, sql = sql_agent(query)
62
- if err:
63
- st.error(f"Error: {err}")
64
- else:
65
- st.code(sql)
66
- st.dataframe(data)
 
 
4
  import pandas as pd
5
  import os
6
 
7
+ # --- 1. SETTINGS ---
8
+ st.set_page_config(page_title="SQL AI Agent", layout="wide")
9
 
10
+ # Get Key from Secrets
11
+ api_key = os.getenv("GEMINI_API_KEY")
12
 
13
  if api_key:
14
  genai.configure(api_key=api_key)
15
  else:
16
+ st.error("⚠️ API Key missing! Go to Settings > Secrets and add 'GEMINI_API_KEY'")
17
 
18
+ # --- 2. DATABASE SETUP ---
19
  DB_NAME = "sales.db"
20
  def init_db():
21
  conn = sqlite3.connect(DB_NAME)
 
30
  if not os.path.exists(DB_NAME):
31
  init_db()
32
 
33
+ # --- 3. AGENTIC LOGIC ---
34
  def sql_agent(user_prompt):
35
+ # Forced stable model names
36
+ model_names = ['gemini-1.5-flash', 'gemini-1.5-pro', 'gemini-pro']
37
+ model = None
 
 
 
 
 
38
 
39
+ for name in model_names:
40
+ try:
41
+ model = genai.GenerativeModel(name)
42
+ # Test if this model works
43
+ model.generate_content("ping")
44
+ break
45
+ except:
46
+ continue
47
+
48
+ if not model:
49
+ return None, "Could not connect to any Gemini models.", ""
50
+
51
+ schema = "Tables: customers (id, name, region), products (id, name, category, price)"
52
+ prompt = f"System: Output ONLY clean SQLite SQL. No backticks. Schema: {schema}\nUser: {user_prompt}"
53
 
54
  try:
55
  response = model.generate_content(prompt)
56
  sql = response.text.strip().replace('```sql', '').replace('```', '')
57
+
58
+ conn = sqlite3.connect(DB_NAME)
59
  df = pd.read_sql_query(sql, conn)
60
+ conn.close()
61
  return df, None, sql
62
  except Exception as e:
63
  return None, str(e), "Error"
 
 
64
 
65
  # --- 4. UI ---
66
+ st.title("🕵️‍♂️ Agentic Text-to-SQL")
67
+ query = st.text_input("Ask a question:", "Show me all products")
68
 
69
+ if st.button("Run Analysis"):
70
+ with st.spinner("Agent is querying..."):
71
+ data, err, sql = sql_agent(query)
72
+ if err:
73
+ st.error(f"Error: {err}")
74
+ else:
75
+ st.code(sql, language="sql")
76
+ st.dataframe(data)