Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,9 +1,10 @@
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
|
|
|
| 3 |
from sqlalchemy import create_engine, MetaData, Table, Column, String, Integer, Float, insert, text, inspect
|
| 4 |
from smolagents import tool, CodeAgent, InferenceClientModel
|
| 5 |
|
| 6 |
-
# --- Setup SQLite database
|
| 7 |
engine = create_engine("sqlite:///data.db")
|
| 8 |
metadata_obj = MetaData()
|
| 9 |
|
|
@@ -12,7 +13,7 @@ students = Table(
|
|
| 12 |
"students",
|
| 13 |
metadata_obj,
|
| 14 |
Column("student_id", Integer, primary_key=True),
|
| 15 |
-
Column("student_name", String(32),
|
| 16 |
)
|
| 17 |
metadata_obj.create_all(engine)
|
| 18 |
|
|
@@ -34,49 +35,53 @@ subjects = Table(
|
|
| 34 |
metadata_obj,
|
| 35 |
Column("student_id", Integer, primary_key=True),
|
| 36 |
Column("subject_name", String(32), primary_key=True),
|
| 37 |
-
Column("marks", Float),
|
|
|
|
| 38 |
)
|
| 39 |
metadata_obj.create_all(engine)
|
| 40 |
|
| 41 |
# Insert sample subject/marks data
|
| 42 |
subject_rows = [
|
| 43 |
-
{"student_id": 1, "subject_name": "Math", "marks": 95.0},
|
| 44 |
-
{"student_id": 1, "subject_name": "English", "marks": 88.5},
|
| 45 |
-
{"student_id":
|
| 46 |
-
{"student_id": 2, "subject_name": "
|
| 47 |
-
{"student_id":
|
| 48 |
-
{"student_id": 3, "subject_name": "
|
| 49 |
-
{"student_id":
|
| 50 |
-
{"student_id": 4, "subject_name": "
|
|
|
|
| 51 |
]
|
| 52 |
for row in subject_rows:
|
| 53 |
stmt = insert(subjects).values(**row)
|
| 54 |
with engine.begin() as conn:
|
| 55 |
conn.execute(stmt)
|
| 56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
# --- Define SQL tool for the agent ---
|
| 58 |
@tool
|
| 59 |
def sql_engine(query: str) -> list:
|
| 60 |
-
"""
|
| 61 |
-
Executes SQL queries on the available tables: students and subjects.
|
| 62 |
-
|
| 63 |
-
Args:
|
| 64 |
-
query: SQL query string.
|
| 65 |
-
|
| 66 |
-
Returns:
|
| 67 |
-
List of tuples with query results.
|
| 68 |
-
"""
|
| 69 |
try:
|
| 70 |
-
print(f"🧩 Executing query: {query}")
|
| 71 |
with engine.connect() as con:
|
| 72 |
rows = con.execute(text(query))
|
| 73 |
-
results = [tuple(row) for row in rows]
|
| 74 |
return results or []
|
| 75 |
except Exception as e:
|
| 76 |
return [f"⚠️ SQL Error: {str(e)}"]
|
| 77 |
|
| 78 |
-
# Dynamically describe tables
|
| 79 |
-
updated_description = "
|
| 80 |
inspector = inspect(engine)
|
| 81 |
for table in ["students", "subjects"]:
|
| 82 |
columns_info = [(col["name"], col["type"]) for col in inspector.get_columns(table)]
|
|
@@ -92,16 +97,24 @@ agent = CodeAgent(
|
|
| 92 |
tools=[sql_engine],
|
| 93 |
model=InferenceClientModel(
|
| 94 |
"meta-llama/Meta-Llama-3-8B-Instruct",
|
| 95 |
-
api_key=os.environ.get("HF_TOKEN")
|
| 96 |
),
|
| 97 |
)
|
| 98 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
# --- Define Gradio interface ---
|
| 100 |
def ask_agent(question: str) -> str:
|
| 101 |
"""Ask the AI agent a question and return its answer."""
|
| 102 |
try:
|
| 103 |
result = agent.run(question)
|
| 104 |
-
# Convert tuples to readable string if result is a list of tuples
|
| 105 |
if isinstance(result, list):
|
| 106 |
result_str = "\n".join(str(r) for r in result)
|
| 107 |
return result_str or "No results."
|
|
@@ -109,12 +122,18 @@ def ask_agent(question: str) -> str:
|
|
| 109 |
except Exception as e:
|
| 110 |
return f"⚠️ Error: {str(e)}"
|
| 111 |
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
|
| 120 |
demo.launch()
|
|
|
|
| 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 |
|
|
|
|
| 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 |
|
|
|
|
| 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 |
+
"""Executes SQL queries on students and subjects and returns list of tuples."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
try:
|
| 75 |
+
print(f"🧩 Executing query: {query}")
|
| 76 |
with engine.connect() as con:
|
| 77 |
rows = con.execute(text(query))
|
| 78 |
+
results = [tuple(row) for row in rows]
|
| 79 |
return results or []
|
| 80 |
except Exception as e:
|
| 81 |
return [f"⚠️ SQL Error: {str(e)}"]
|
| 82 |
|
| 83 |
+
# Dynamically describe tables for the agent
|
| 84 |
+
updated_description = "You can run SQL queries on these tables:\n"
|
| 85 |
inspector = inspect(engine)
|
| 86 |
for table in ["students", "subjects"]:
|
| 87 |
columns_info = [(col["name"], col["type"]) for col in inspector.get_columns(table)]
|
|
|
|
| 97 |
tools=[sql_engine],
|
| 98 |
model=InferenceClientModel(
|
| 99 |
"meta-llama/Meta-Llama-3-8B-Instruct",
|
| 100 |
+
api_key=os.environ.get("HF_TOKEN")
|
| 101 |
),
|
| 102 |
)
|
| 103 |
|
| 104 |
+
# --- Sample prompts to display ---
|
| 105 |
+
sample_prompts = [
|
| 106 |
+
"Which student scored highest in Math?",
|
| 107 |
+
"List all subjects and marks for Alice Johnson.",
|
| 108 |
+
"Who is the teacher of Science for Diana Prince?",
|
| 109 |
+
"Show students who scored more than 80 in Science.",
|
| 110 |
+
"Average marks per subject."
|
| 111 |
+
]
|
| 112 |
+
|
| 113 |
# --- Define Gradio interface ---
|
| 114 |
def ask_agent(question: str) -> str:
|
| 115 |
"""Ask the AI agent a question and return its answer."""
|
| 116 |
try:
|
| 117 |
result = agent.run(question)
|
|
|
|
| 118 |
if isinstance(result, list):
|
| 119 |
result_str = "\n".join(str(r) for r in result)
|
| 120 |
return result_str or "No results."
|
|
|
|
| 122 |
except Exception as e:
|
| 123 |
return f"⚠️ Error: {str(e)}"
|
| 124 |
|
| 125 |
+
with gr.Blocks() as demo:
|
| 126 |
+
gr.Markdown("## 🏫 Student Marks SQL Agent")
|
| 127 |
+
gr.Markdown("### Students Table")
|
| 128 |
+
gr.DataFrame(value=students_df, interactive=False)
|
| 129 |
+
gr.Markdown("### Subjects Table")
|
| 130 |
+
gr.DataFrame(value=subjects_df, interactive=False)
|
| 131 |
+
gr.Markdown("### Ask questions about students, subjects, marks, and teachers")
|
| 132 |
+
question_input = gr.Textbox(label="Your question", placeholder="e.g., Which student scored highest in Math?")
|
| 133 |
+
answer_output = gr.Textbox(label="Agent response")
|
| 134 |
+
gr.Markdown("### Sample Prompts")
|
| 135 |
+
for prompt in sample_prompts:
|
| 136 |
+
gr.Markdown(f"- {prompt}")
|
| 137 |
+
question_input.submit(fn=ask_agent, inputs=question_input, outputs=answer_output)
|
| 138 |
|
| 139 |
demo.launch()
|