-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
242 lines (196 loc) · 7.36 KB
/
Copy pathapp.py
File metadata and controls
242 lines (196 loc) · 7.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
"""
app.py
Final Streamlit interface for the SQL co-pilot.
Full chat history, sidebar, schema explorer, example questions,
retry log, query counter, and clear conversation.
"""
import os
import streamlit as st
from dotenv import load_dotenv
from agent import SQLAgent
from db import get_connection, get_row_counts, get_table_names, get_table_schema
load_dotenv()
st.set_page_config(
page_title="SQL Co-pilot",
page_icon="🗄",
layout="wide",
)
EXAMPLE_QUESTIONS = [
"How many orders are in the dataset?",
"What are the different order statuses and how many orders are in each?",
"Which cities have the most customers?",
"What are the top 10 sellers by number of orders fulfilled?",
"What are the top 10 product categories by total revenue?",
"Which product categories have the highest average review score?",
"What is the monthly order volume trend across 2017 and 2018?",
"What percentage of orders were delivered late?",
"Which sellers have the highest average review score with at least 50 orders?",
"What payment methods are most commonly used?",
]
def get_hf_token() -> str:
# On HF Spaces the token is injected as an environment variable
# skip st.secrets entirely to avoid the missing secrets file warning
token = os.getenv("HF_TOKEN", "")
if token:
return token
# Local fallback — try st.secrets only if env var not found
try:
if "HF_TOKEN" in st.secrets:
return st.secrets["HF_TOKEN"]
except (FileNotFoundError, KeyError):
pass
st.error(
"HF_TOKEN not found. "
"Add it to your .env file for local development "
"or to Space secrets for deployment."
)
st.stop()
return ""
def render_sidebar(con) -> None:
with st.sidebar:
st.markdown("### How it works")
st.markdown(
"Type any business question in plain English. "
"The agent writes the SQL, validates it, runs it against "
"the loaded dataset, and explains the result. "
"If the query fails, it automatically retries up to 3 times."
)
st.divider()
query_count = len([
m for m in st.session_state.get("messages", [])
if m["role"] == "user"
])
st.metric("Queries this session", query_count)
if st.button("Clear conversation", use_container_width=True):
st.session_state.messages = []
st.rerun()
st.divider()
st.markdown("### Example questions")
st.caption("Click any question to run it directly.")
for q in EXAMPLE_QUESTIONS:
if st.button(q, use_container_width=True, key=f"ex_{q[:30]}"):
st.session_state.pending_question = q
st.divider()
st.markdown("### Schema explorer")
st.caption("Tables currently loaded from the data/ folder.")
tables = get_table_names(con)
counts = get_row_counts(con)
selected = st.selectbox("Select a table to inspect", tables)
if selected:
st.caption(f"{counts.get(selected, 0):,} rows")
schema_df = get_table_schema(con, selected)
st.dataframe(
schema_df[["column_name", "column_type"]],
use_container_width=True,
hide_index=True,
)
st.divider()
st.markdown("### Using your own data")
st.caption(
"Drop any CSV files into the data/ folder and restart the app. "
"Each CSV becomes a queryable table automatically. "
"Add a relationships.txt file to define join keys, "
"or drop an ERD image and the app extracts them for you."
)
def render_home_context(con) -> None:
tables = get_table_names(con)
counts = get_row_counts(con)
total_rows = sum(counts.values())
st.markdown("### What you can query")
st.markdown(
"This tool lets you ask questions about the loaded dataset in plain English. "
"It translates your question into SQL, runs it instantly, and explains the result. "
"No SQL knowledge needed."
)
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Tables loaded", len(tables))
with col2:
st.metric("Total rows", f"{total_rows:,}")
with col3:
st.metric("Max retries", "3")
st.markdown("### Loaded tables")
cols = st.columns(3)
for i, table in enumerate(tables):
with cols[i % 3]:
st.markdown(
f"**{table}** \n"
f"<span style='color: grey; font-size: 12px'>"
f"{counts.get(table, 0):,} rows</span>",
unsafe_allow_html=True,
)
st.divider()
def render_result(result) -> None:
if not result.success:
st.error(
f"Could not generate a valid query after "
f"{result.attempts} attempt(s)."
)
if result.error_history:
with st.expander("Error details"):
for i, err in enumerate(result.error_history, 1):
st.text(f"Attempt {i}: {err}")
return
attempt_label = (
f"Done in {result.attempts} attempt(s)."
if result.attempts == 1
else f"Done in {result.attempts} attempts (self-corrected)."
)
st.success(attempt_label)
if result.explanation:
st.info(result.explanation)
with st.expander("Generated SQL", expanded=True):
st.code(result.sql, language="sql")
if result.error_history:
with st.expander(
f"Self-correction log — {len(result.error_history)} retry(s)"
):
for i, err in enumerate(result.error_history, 1):
st.text(f"Attempt {i} error: {err}")
st.dataframe(
result.result,
use_container_width=True,
hide_index=True,
)
st.caption(f"{len(result.result):,} rows returned.")
def main() -> None:
st.title("Agentic SQL Co-pilot")
st.caption(
"Powered by Qwen2.5-Coder-7B and DuckDB. "
"Ask anything about the loaded dataset."
)
hf_token = get_hf_token()
con = get_connection()
render_sidebar(con)
if "messages" not in st.session_state:
st.session_state.messages = []
if "pending_question" not in st.session_state:
st.session_state.pending_question = None
if not st.session_state.messages:
render_home_context(con)
agent = SQLAgent(con=con, hf_token=hf_token)
for message in st.session_state.messages:
with st.chat_message(message["role"]):
if message["role"] == "user":
st.markdown(message["content"])
else:
render_result(message["result"])
question = st.chat_input("Ask a question about the dataset...")
if st.session_state.pending_question:
question = st.session_state.pending_question
st.session_state.pending_question = None
if question:
st.session_state.messages.append(
{"role": "user", "content": question}
)
with st.chat_message("user"):
st.markdown(question)
with st.chat_message("assistant"):
with st.spinner("Generating SQL and running query..."):
result = agent.run(question)
render_result(result)
st.session_state.messages.append(
{"role": "assistant", "result": result}
)
if __name__ == "__main__":
main()