Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
with gr.Blocks() as demo:
|
| 2 |
-
gr.Markdown("## 🏫
|
| 3 |
|
| 4 |
with gr.Row():
|
| 5 |
# --- Left column: tables (smaller) ---
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import pandas as pd
|
| 4 |
+
from sqlalchemy import create_engine, MetaData, Table, Column, String, Integer, Float, insert, text, inspect
|
| 5 |
+
from smolagents import tool, CodeAgent, InferenceClientModel
|
| 6 |
+
|
| 7 |
+
# --- Setup SQLite database ---
|
| 8 |
+
engine = create_engine("sqlite:///data.db")
|
| 9 |
+
metadata_obj = MetaData()
|
| 10 |
+
|
| 11 |
+
# --- Create students table ---
|
| 12 |
+
students = Table(
|
| 13 |
+
"students",
|
| 14 |
+
metadata_obj,
|
| 15 |
+
Column("student_id", Integer, primary_key=True),
|
| 16 |
+
Column("student_name", String(32), nullable=False),
|
| 17 |
+
)
|
| 18 |
+
metadata_obj.create_all(engine)
|
| 19 |
+
|
| 20 |
+
# Insert sample student data
|
| 21 |
+
student_rows = [
|
| 22 |
+
{"student_id": 1, "student_name": "Alice Johnson"},
|
| 23 |
+
{"student_id": 2, "student_name": "Bob Smith"},
|
| 24 |
+
{"student_id": 3, "student_name": "Charlie Brown"},
|
| 25 |
+
{"student_id": 4, "student_name": "Diana Prince"},
|
| 26 |
+
]
|
| 27 |
+
for row in student_rows:
|
| 28 |
+
stmt = insert(students).values(**row)
|
| 29 |
+
with engine.begin() as conn:
|
| 30 |
+
conn.execute(stmt)
|
| 31 |
+
|
| 32 |
+
# --- Create subjects table ---
|
| 33 |
+
subjects = Table(
|
| 34 |
+
"subjects",
|
| 35 |
+
metadata_obj,
|
| 36 |
+
Column("student_id", Integer, primary_key=True),
|
| 37 |
+
Column("subject_name", String(32), primary_key=True),
|
| 38 |
+
Column("marks", Float, nullable=False),
|
| 39 |
+
Column("teacher", String(32), nullable=False),
|
| 40 |
+
)
|
| 41 |
+
metadata_obj.create_all(engine)
|
| 42 |
+
|
| 43 |
+
# Insert sample subject/marks data
|
| 44 |
+
subject_rows = [
|
| 45 |
+
{"student_id": 1, "subject_name": "Math", "marks": 95.0, "teacher": "Mr. Adams"},
|
| 46 |
+
{"student_id": 1, "subject_name": "English", "marks": 88.5, "teacher": "Ms. Baker"},
|
| 47 |
+
{"student_id": 1, "subject_name": "Science", "marks": 92.0, "teacher": "Dr. Carter"},
|
| 48 |
+
{"student_id": 2, "subject_name": "Math", "marks": 72.0, "teacher": "Mr. Adams"},
|
| 49 |
+
{"student_id": 2, "subject_name": "Science", "marks": 81.0, "teacher": "Dr. Carter"},
|
| 50 |
+
{"student_id": 3, "subject_name": "Math", "marks": 85.0, "teacher": "Mr. Adams"},
|
| 51 |
+
{"student_id": 3, "subject_name": "History", "marks": 90.0, "teacher": "Mrs. Davis"},
|
| 52 |
+
{"student_id": 4, "subject_name": "English", "marks": 78.0, "teacher": "Ms. Baker"},
|
| 53 |
+
{"student_id": 4, "subject_name": "Science", "marks": 82.0, "teacher": "Dr. Carter"},
|
| 54 |
+
]
|
| 55 |
+
for row in subject_rows:
|
| 56 |
+
stmt = insert(subjects).values(**row)
|
| 57 |
+
with engine.begin() as conn:
|
| 58 |
+
conn.execute(stmt)
|
| 59 |
+
|
| 60 |
+
# --- Convert tables to DataFrames for front-end display ---
|
| 61 |
+
def fetch_table(table_name: str) -> pd.DataFrame:
|
| 62 |
+
with engine.connect() as con:
|
| 63 |
+
rows = con.execute(text(f"SELECT * FROM {table_name}"))
|
| 64 |
+
df = pd.DataFrame(rows.fetchall(), columns=rows.keys())
|
| 65 |
+
return df
|
| 66 |
+
|
| 67 |
+
students_df = fetch_table("students")
|
| 68 |
+
subjects_df = fetch_table("subjects")
|
| 69 |
+
|
| 70 |
+
# --- Define SQL tool for the agent ---
|
| 71 |
+
@tool
|
| 72 |
+
def sql_engine(query: str) -> list:
|
| 73 |
+
"""
|
| 74 |
+
Executes SQL queries on the available tables: students and subjects.
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
query (str): The SQL query string to execute.
|
| 78 |
+
|
| 79 |
+
Returns:
|
| 80 |
+
list: List of tuples containing the query results.
|
| 81 |
+
"""
|
| 82 |
+
try:
|
| 83 |
+
print(f"🧩 Executing query: {query}")
|
| 84 |
+
with engine.connect() as con:
|
| 85 |
+
rows = con.execute(text(query))
|
| 86 |
+
results = [tuple(row) for row in rows]
|
| 87 |
+
return results or []
|
| 88 |
+
except Exception as e:
|
| 89 |
+
return [f"⚠️ SQL Error: {str(e)}"]
|
| 90 |
+
|
| 91 |
+
# Dynamically describe tables for the agent
|
| 92 |
+
updated_description = "You can run SQL queries on these tables:\n"
|
| 93 |
+
inspector = inspect(engine)
|
| 94 |
+
for table in ["students", "subjects"]:
|
| 95 |
+
columns_info = [(col["name"], col["type"]) for col in inspector.get_columns(table)]
|
| 96 |
+
table_description = f"\n\nTable '{table}':\nColumns:\n" + "\n".join(
|
| 97 |
+
[f" - {name}: {col_type}" for name, col_type in columns_info]
|
| 98 |
+
)
|
| 99 |
+
updated_description += table_description
|
| 100 |
+
|
| 101 |
+
sql_engine.description = updated_description
|
| 102 |
+
|
| 103 |
+
# --- Create the agent ---
|
| 104 |
+
agent = CodeAgent(
|
| 105 |
+
tools=[sql_engine],
|
| 106 |
+
model=InferenceClientModel(
|
| 107 |
+
"meta-llama/Meta-Llama-3-8B-Instruct",
|
| 108 |
+
api_key=os.environ.get("HF_TOKEN")
|
| 109 |
+
),
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
# --- Sample prompts to display ---
|
| 113 |
+
sample_prompts = [
|
| 114 |
+
"Which student scored highest in Math?",
|
| 115 |
+
"List all subjects and marks for Alice Johnson.",
|
| 116 |
+
"Who is the teacher of Science for Diana Prince?",
|
| 117 |
+
"Show students who scored more than 80 in Science.",
|
| 118 |
+
"Average marks per subject."
|
| 119 |
+
]
|
| 120 |
+
|
| 121 |
+
# --- Define Gradio interface ---
|
| 122 |
+
def ask_agent(question: str) -> str:
|
| 123 |
+
"""Ask the AI agent a question and return its answer."""
|
| 124 |
+
try:
|
| 125 |
+
result = agent.run(question)
|
| 126 |
+
if isinstance(result, list):
|
| 127 |
+
result_str = "\n".join(str(r) for r in result)
|
| 128 |
+
return result_str or "No results."
|
| 129 |
+
return str(result)
|
| 130 |
+
except Exception as e:
|
| 131 |
+
return f"⚠️ Error: {str(e)}"
|
| 132 |
+
|
| 133 |
with gr.Blocks() as demo:
|
| 134 |
+
gr.Markdown("## 🏫 Text to SQL Agent")
|
| 135 |
|
| 136 |
with gr.Row():
|
| 137 |
# --- Left column: tables (smaller) ---
|