Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -211,17 +211,20 @@ def query_sql(user_query: str) -> str:
|
|
211 |
"DO NOT explain your reasoning, and DO NOT return anything other than the SQL query itself."
|
212 |
)
|
213 |
|
|
|
214 |
generated_sql = agent.run(f"{schema_info} Convert this request into SQL: {user_query}")
|
215 |
|
|
|
216 |
if not isinstance(generated_sql, str):
|
217 |
-
return f"
|
218 |
|
219 |
-
#
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
|
|
225 |
|
226 |
# Fix table names
|
227 |
for wrong_name in ['table_name', 'customers', 'main']:
|
@@ -234,14 +237,18 @@ def query_sql(user_query: str) -> str:
|
|
234 |
if col in generated_sql and f'"{col}"' not in generated_sql and f'`{col}`' not in generated_sql:
|
235 |
generated_sql = generated_sql.replace(col, f'"{col}"')
|
236 |
|
237 |
-
# Execute the query
|
238 |
-
result = sql_engine(generated_sql)
|
239 |
-
|
240 |
try:
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
245 |
|
246 |
# Create the Gradio interface
|
247 |
with gr.Blocks() as demo:
|
|
|
211 |
"DO NOT explain your reasoning, and DO NOT return anything other than the SQL query itself."
|
212 |
)
|
213 |
|
214 |
+
# Get the SQL query from the agent
|
215 |
generated_sql = agent.run(f"{schema_info} Convert this request into SQL: {user_query}")
|
216 |
|
217 |
+
# Clean up and validate the SQL
|
218 |
if not isinstance(generated_sql, str):
|
219 |
+
return f"Error: Invalid query generated"
|
220 |
|
221 |
+
# Extract just the SQL query if there's additional text
|
222 |
+
sql_lines = [line for line in generated_sql.split('\n') if 'select' in line.lower()]
|
223 |
+
if sql_lines:
|
224 |
+
generated_sql = sql_lines[0]
|
225 |
+
|
226 |
+
# Remove any trailing semicolons
|
227 |
+
generated_sql = generated_sql.strip().rstrip(';')
|
228 |
|
229 |
# Fix table names
|
230 |
for wrong_name in ['table_name', 'customers', 'main']:
|
|
|
237 |
if col in generated_sql and f'"{col}"' not in generated_sql and f'`{col}`' not in generated_sql:
|
238 |
generated_sql = generated_sql.replace(col, f'"{col}"')
|
239 |
|
|
|
|
|
|
|
240 |
try:
|
241 |
+
# Execute the query
|
242 |
+
result = sql_engine(generated_sql)
|
243 |
+
|
244 |
+
# Try to format as number if possible
|
245 |
+
try:
|
246 |
+
float_result = float(result)
|
247 |
+
return f"{float_result:,.0f}" # Format with commas, no decimals
|
248 |
+
except ValueError:
|
249 |
+
return result
|
250 |
+
except Exception as e:
|
251 |
+
return f"Error executing query: {str(e)}"
|
252 |
|
253 |
# Create the Gradio interface
|
254 |
with gr.Blocks() as demo:
|