NavyDevilDoc commited on
Commit
5b49ca2
ยท
verified ยท
1 Parent(s): 2d32578

Update app.py

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