SQL-ChatBot / app.py
AliInamdar's picture
Update app.py
f173eae verified
raw
history blame
2.68 kB
import gradio as gr
import pandas as pd
import duckdb
import requests
import re
import os
# βœ… Load Together API key securely
def get_together_api_key():
key = os.environ.get("TOGETHER_API_KEY")
if key:
print("βœ… TOGETHER_API_KEY loaded successfully.")
return key
raise RuntimeError("❌ TOGETHER_API_KEY not found. Set it in Hugging Face > Settings > Secrets.")
TOGETHER_API_KEY = get_together_api_key()
# 🧠 Generate SQL from prompt using Together API
def generate_sql_from_prompt(prompt, df):
schema = ", ".join([f"{col} ({str(dtype)})" for col, dtype in df.dtypes.items()])
full_prompt = f"""You are a SQL expert. Here is a table called 'df' with the following schema:
{schema}
User question: "{prompt}"
Write a valid SQL query using the 'df' table. Return only the SQL code."""
url = "https://api.together.xyz/inference"
headers = {
"Authorization": f"Bearer {TOGETHER_API_KEY}",
"Content-Type": "application/json"
}
payload = {
"model": "meta-llama/Llama-3-8B-Instruct",
"prompt": full_prompt,
"max_tokens": 300,
"temperature": 0.5,
}
response = requests.post(url, headers=headers, json=payload)
response.raise_for_status()
result = response.json()
return result['output'].strip("```sql").strip("```").strip()
# 🧽 Clean SQL for DuckDB compatibility
def clean_sql_for_duckdb(sql, df_columns):
sql = sql.replace("`", '"')
for col in df_columns:
if " " in col and f'"{col}"' not in sql:
pattern = r'\b' + re.escape(col) + r'\b'
sql = re.sub(pattern, f'"{col}"', sql)
return sql
# πŸ’¬ Main Gradio function
def chatbot_interface(file, question):
try:
df = pd.read_excel(file)
sql = generate_sql_from_prompt(question, df)
cleaned_sql = clean_sql_for_duckdb(sql, df.columns)
result = duckdb.query(cleaned_sql).to_df()
return f"πŸ“œ SQL Query:\n```sql\n{sql}\n```", result
except Exception as e:
return f"❌ Error: {str(e)}", pd.DataFrame()
# πŸŽ›οΈ Gradio UI
with gr.Blocks() as demo:
gr.Markdown("## πŸ“Š Excel SQL Chatbot with Together API")
with gr.Row():
file_input = gr.File(label="πŸ“‚ Upload Excel File (.xlsx)")
question = gr.Textbox(label="🧠 Ask a question", placeholder="e.g., Show average salary by department")
submit = gr.Button("πŸš€ Generate & Query")
sql_output = gr.Markdown()
result_table = gr.Dataframe()
submit.click(fn=chatbot_interface, inputs=[file_input, question], outputs=[sql_output, result_table])
# πŸš€ Launch the app
if __name__ == "__main__":
demo.launch()