sql-agent-backend / agent.py
Huzaifa1435's picture
Deploy AI SQL Agent Backend
345a446
Raw History Blame Contribute Delete
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)