NavyDevilDoc commited on
Commit
66bae08
ยท
verified ยท
1 Parent(s): 971daac

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -25
app.py CHANGED
@@ -1,49 +1,111 @@
1
  import streamlit as st
2
  from google import genai
3
  from io import StringIO
4
- from prompts import SYSTEM_INSTRUCTION, USER_PROMPT_TEMPLATE
5
 
6
  st.set_page_config(page_title="SQL AI Assistant", layout="wide")
7
 
8
- # 1. Setup Sidebar for Context
9
  st.sidebar.title("๐Ÿ› ๏ธ Database Context")
 
 
10
  dialect = st.sidebar.selectbox("SQL Dialect", ["PostgreSQL", "MySQL", "SQLite", "BigQuery", "Snowflake"])
11
  db_name = st.sidebar.text_input("Database Name", placeholder="e.g. production_db")
12
- schema = st.sidebar.text_area("Table Schemas (DDL)", placeholder="CREATE TABLE users (id INT, name TEXT...)", height=300)
13
 
14
- st.title("๐Ÿค– Gemini SQL Generator")
15
- st.caption(f"Powered by Gemini 2.5 Flash")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
- # 2. Initialize Gemini Client
18
- # In HF Spaces, go to Settings -> Secrets and add 'GEMINI_API_KEY'
19
- api_key = st.secrets["GEMINI_API_KEY"]
20
- client = genai.Client(api_key=api_key)
 
 
 
 
 
 
 
 
21
 
22
- # 3. Chat Interface
 
 
 
 
23
  if "messages" not in st.session_state:
24
  st.session_state.messages = []
 
 
25
 
 
26
  for msg in st.session_state.messages:
27
- st.chat_message(msg["role"]).write(msg["content"])
 
 
 
 
28
 
29
- if prompt := st.chat_input("Show me the top 10 users by signup date..."):
 
 
30
  st.session_state.messages.append({"role": "user", "content": prompt})
31
- st.chat_message("user").write(prompt)
 
32
 
33
- # Build the full system instructions with current sidebar context
34
- full_system_msg = SYSTEM_INSTRUCTION.format(
 
 
 
35
  dialect=dialect,
36
- db_name=db_name,
37
- schema=schema if schema else "No specific schema provided."
 
38
  )
39
 
40
  with st.spinner("Generating SQL..."):
41
- response = client.models.generate_content(
42
- model="gemini-2.5-flash",
43
- config={'system_instruction': full_system_msg},
44
- contents=USER_PROMPT_TEMPLATE.format(user_input=prompt)
45
- )
 
 
 
 
 
 
 
 
 
46
 
47
- sql_output = response.text
48
- st.session_state.messages.append({"role": "assistant", "content": sql_output})
49
- st.chat_message("assistant").code(sql_output, language="sql")
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  from google import genai
3
  from io import StringIO
4
+ import prompts # Assuming prompts.py is in the same directory
5
 
6
  st.set_page_config(page_title="SQL AI Assistant", layout="wide")
7
 
8
+ # --- 1. Sidebar: Configuration & Context ---
9
  st.sidebar.title("๐Ÿ› ๏ธ Database Context")
10
+
11
+ # Dialect and DB Name
12
  dialect = st.sidebar.selectbox("SQL Dialect", ["PostgreSQL", "MySQL", "SQLite", "BigQuery", "Snowflake"])
13
  db_name = st.sidebar.text_input("Database Name", placeholder="e.g. production_db")
 
14
 
15
+ # File Uploader for Schema
16
+ st.sidebar.subheader("๐Ÿ“„ Upload Schema")
17
+ uploaded_file = st.sidebar.file_uploader("Upload .sql or .txt file", type=["sql", "txt"])
18
+
19
+ # Logic to handle schema input (Manual or Uploaded)
20
+ initial_schema = ""
21
+ if uploaded_file is not None:
22
+ initial_schema = uploaded_file.getvalue().decode("utf-8")
23
+
24
+ schema = st.sidebar.text_area(
25
+ "Table Schemas (DDL)",
26
+ value=initial_schema,
27
+ placeholder="CREATE TABLE users (id INT, name TEXT...)",
28
+ height=300
29
+ )
30
+
31
+ # Option to toggle explanations
32
+ show_explanation = st.sidebar.checkbox("Show Logic Explanation", value=False)
33
 
34
+ if st.sidebar.button("๐Ÿ—‘๏ธ Clear Chat History"):
35
+ st.session_state.messages = []
36
+ st.rerun()
37
+
38
+ # --- 2. Initialize Gemini Client ---
39
+ # Correcting the secret key name based on your error report
40
+ try:
41
+ api_key = st.secrets["GOOGLE_API_KEY"]
42
+ client = genai.Client(api_key=api_key)
43
+ except Exception as e:
44
+ st.error("API Key not found. Please ensure GOOGLE_API_KEY is set in Hugging Face Secrets.")
45
+ st.stop()
46
 
47
+ # --- 3. Main UI ---
48
+ st.title("๐Ÿค– Gemini SQL Generator")
49
+ st.caption("Generate, inspect, and download optimized SQL queries.")
50
+
51
+ # Initialize session state for messages and the last generated query
52
  if "messages" not in st.session_state:
53
  st.session_state.messages = []
54
+ if "last_query" not in st.session_state:
55
+ st.session_state.last_query = ""
56
 
57
+ # Display chat history
58
  for msg in st.session_state.messages:
59
+ with st.chat_message(msg["role"]):
60
+ if msg["role"] == "assistant":
61
+ st.code(msg["content"], language="sql")
62
+ else:
63
+ st.write(msg["content"])
64
 
65
+ # --- 4. Chat Input & Generation ---
66
+ if prompt := st.chat_input("Show me all orders from the last 30 days..."):
67
+ # Add user message to state
68
  st.session_state.messages.append({"role": "user", "content": prompt})
69
+ with st.chat_message("user"):
70
+ st.write(prompt)
71
 
72
+ # Format instructions from prompts.py
73
+ # Note: Ensure your SYSTEM_INSTRUCTION in prompts.py has {dialect}, {db_name}, {schema}, and {explain}
74
+ explain_text = "Provide a brief explanation after the code." if show_explanation else "Provide ONLY the code."
75
+
76
+ full_system_msg = prompts.SYSTEM_INSTRUCTION.format(
77
  dialect=dialect,
78
+ db_name=db_name if db_name else "unspecified",
79
+ schema=schema if schema else "No specific schema provided.",
80
+ explain=explain_text
81
  )
82
 
83
  with st.spinner("Generating SQL..."):
84
+ try:
85
+ response = client.models.generate_content(
86
+ model="gemini-2.0-flash", # Using the latest flash model
87
+ config={'system_instruction': full_system_msg},
88
+ contents=prompts.USER_PROMPT_TEMPLATE.format(user_input=prompt)
89
+ )
90
+
91
+ sql_output = response.text
92
+ st.session_state.last_query = sql_output
93
+
94
+ # Add assistant response to state
95
+ st.session_state.messages.append({"role": "assistant", "content": sql_output})
96
+ with st.chat_message("assistant"):
97
+ st.code(sql_output, language="sql")
98
 
99
+ except Exception as e:
100
+ st.error(f"Generation failed: {e}")
101
+
102
+ # --- 5. Download Action ---
103
+ if st.session_state.last_query:
104
+ st.divider()
105
+ st.download_button(
106
+ label="๐Ÿ’พ Download Latest Query",
107
+ data=st.session_state.last_query,
108
+ file_name="generated_query.sql",
109
+ mime="text/x-sql",
110
+ use_container_width=True
111
+ )