Spaces:
Configuration error
Configuration error
Download agent.py from Huzaifa1313/sql-agent-backend: direct link, hf CLI and curl.
- Browser
- Download file 1.22 kB
-
https://huggingface.co/spaces/Huzaifa1313/sql-agent-backend/resolve/main/agent.py
- Command line
-
hf download hf://spaces/Huzaifa1313/sql-agent-backend/agent.py
-
curl -L -o agent.py https://huggingface.co/spaces/Huzaifa1313/sql-agent-backend/resolve/main/agent.py
1.22 kB
| from llm import generate_sql | |
| from database import fetch_query, execute_query, get_schema_info, get_db_path | |
| import pandas as pd | |
| ALLOWED = ("SELECT", "INSERT", "UPDATE", "DELETE") | |
| def ask_ai(question: str): | |
| """ | |
| Takes English question, returns (answer, sql, dataframe_or_none) | |
| """ | |
| # Build schema from currently active DB | |
| schema = get_schema_info(get_db_path()) | |
| sql = generate_sql(question, schema_info=schema) | |
| sql_upper = sql.upper().strip() | |
| # Block unsafe or invalid queries | |
| if sql_upper == "INVALID_QUERY": | |
| return ("❌ This question cannot be answered with the current database.", sql, None) | |
| if not sql_upper.startswith(ALLOWED): | |
| return ("❌ Unsafe or unsupported query blocked.", sql, None) | |
| try: | |
| if sql_upper.startswith("SELECT"): | |
| rows = fetch_query(sql) | |
| if not rows: | |
| return ("No records found.", sql, pd.DataFrame()) | |
| df = pd.DataFrame(rows) | |
| return (f"Found {len(df)} record(s).", sql, df) | |
| else: | |
| execute_query(sql) | |
| return ("✅ Database updated successfully!", sql, None) | |
| except Exception as e: | |
| return (f"❌ Error: {e}", sql, None) | |