Sayandip commited on
Commit
9851cfe
·
verified ·
1 Parent(s): 4aede25

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -108
app.py CHANGED
@@ -1,83 +1,79 @@
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
- import pandas as pd
6
 
7
- # --- Setup SQLite database ---
8
- engine = create_engine("sqlite:///students.db")
9
  metadata_obj = MetaData()
10
 
11
- # --- Create tables ---
12
- students = Table(
13
- "students", metadata_obj,
14
- Column("student_id", Integer, primary_key=True),
15
- Column("name", String(30)),
16
- Column("age", Integer)
17
- )
18
-
19
- marks = Table(
20
- "marks", metadata_obj,
21
- Column("student_id", Integer, primary_key=True),
22
- Column("subject", String(20), primary_key=True),
23
- Column("marks", Float),
24
- Column("grade", String(2))
25
  )
26
-
27
  metadata_obj.create_all(engine)
28
 
29
- # --- Insert sample data safely ---
30
- students_data = [
31
- {"student_id": 1, "name": "Alice Johnson", "age": 16},
32
- {"student_id": 2, "name": "Bob Smith", "age": 17},
33
- {"student_id": 3, "name": "Charlie Lee", "age": 16},
34
- {"student_id": 4, "name": "Diana King", "age": 17},
35
- ]
36
-
37
- marks_data = [
38
- {"student_id": 1, "subject": "Math", "marks": 88, "grade": "A"},
39
- {"student_id": 1, "subject": "English", "marks": 75, "grade": "B"},
40
- {"student_id": 2, "subject": "Math", "marks": 92, "grade": "A"},
41
- {"student_id": 2, "subject": "English", "marks": 81, "grade": "A"},
42
- {"student_id": 3, "subject": "Math", "marks": 64, "grade": "C"},
43
- {"student_id": 3, "subject": "English", "marks": 70, "grade": "B"},
44
- {"student_id": 4, "subject": "Math", "marks": 79, "grade": "B"},
45
- {"student_id": 4, "subject": "English", "marks": 85, "grade": "A"},
46
  ]
47
-
48
- for row in students_data:
49
- stmt = insert(students).values(**row).prefix_with("OR IGNORE")
50
- with engine.begin() as conn:
51
  conn.execute(stmt)
52
 
53
- for row in marks_data:
54
- stmt = insert(marks).values(**row).prefix_with("OR IGNORE")
55
- with engine.begin() as conn:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  conn.execute(stmt)
57
 
58
- # --- Define SQL tool ---
59
  @tool
60
- def sql_engine(query: str) -> dict:
 
61
  try:
 
62
  with engine.connect() as con:
63
  rows = con.execute(text(query))
64
- columns = rows.keys()
65
- data = [tuple(row) for row in rows]
66
- return {"columns": columns, "data": data} if data else {"columns": [], "data": []}
67
  except Exception as e:
68
- return {"columns": ["Error"], "data": [[str(e)]]}
69
-
70
 
71
- # --- Table descriptions ---
 
72
  inspector = inspect(engine)
73
- updated_description = "Ask natural language questions about the student marks database.\n"
74
- for table in ["students", "marks"]:
75
  columns_info = [(col["name"], col["type"]) for col in inspector.get_columns(table)]
76
- table_description = f"\n\nTable '{table}':\n" + "\n".join(
77
- [f" - {name}: {col_type}" for name, col_type in columns_info]
78
  )
79
  updated_description += table_description
80
-
81
  sql_engine.description = updated_description
82
 
83
  # --- Create the agent ---
@@ -85,60 +81,28 @@ agent = CodeAgent(
85
  tools=[sql_engine],
86
  model=InferenceClientModel(
87
  "meta-llama/Meta-Llama-3-8B-Instruct",
88
- api_key=os.environ.get("HF_TOKEN")
89
  ),
90
  )
91
 
92
- # --- Gradio functions ---
93
- def ask_agent(question: str):
94
- result = agent.run(question)
95
- if isinstance(result, dict) and "columns" in result and "data" in result:
96
- if not result["data"]:
97
- return pd.DataFrame(columns=result["columns"])
98
- return pd.DataFrame(result["data"], columns=result["columns"])
99
- return pd.DataFrame([[str(result)]], columns=["Result"])
100
-
101
- # --- Sample prompts ---
102
- sample_prompts = [
103
- "Which student has the highest marks in Math?",
104
- "List all students with their subjects and grades.",
105
- "What is the average marks of each student?",
106
- "Show students who scored above 80 in English."
107
- ]
108
-
109
- def set_prompt(prompt):
110
- return prompt
111
-
112
- # --- Display database tables ---
113
- def get_tables():
114
- with engine.connect() as con:
115
- students_df = pd.read_sql_table("students", con)
116
- marks_df = pd.read_sql_table("marks", con)
117
- return students_df, marks_df
118
-
119
- students_df, marks_df = get_tables()
120
-
121
- # --- Gradio App ---
122
- with gr.Blocks() as demo:
123
- gr.Markdown("## 🎓 Student Marks Database Explorer")
124
-
125
- with gr.Row():
126
- with gr.Column():
127
- gr.Markdown("### Students Table")
128
- gr.Dataframe(students_df, interactive=False)
129
- with gr.Column():
130
- gr.Markdown("### Marks Table")
131
- gr.Dataframe(marks_df, interactive=False)
132
-
133
- gr.Markdown("### Ask the AI Agent")
134
- question = gr.Textbox(label="Ask a question")
135
- output = gr.Dataframe(headers=None) # Result displayed as DataFrame
136
- ask_btn = gr.Button("Ask")
137
- ask_btn.click(ask_agent, inputs=question, outputs=output)
138
-
139
- gr.Markdown("### Sample Prompts")
140
- for sp in sample_prompts:
141
- btn = gr.Button(sp)
142
- btn.click(set_prompt, inputs=gr.State(sp), outputs=question)
143
 
144
  demo.launch()
 
1
  import os
2
  import gradio as gr
3
+ from sqlalchemy import (
4
+ create_engine, MetaData, Table, Column, String, Integer, Float, insert, text, inspect
5
+ )
6
  from smolagents import tool, CodeAgent, InferenceClientModel
 
7
 
8
+ # --- Setup SQLite database (persistent in Space) ---
9
+ engine = create_engine("sqlite:///data.db")
10
  metadata_obj = MetaData()
11
 
12
+ # --- Create receipts table ---
13
+ receipts = Table(
14
+ "receipts",
15
+ metadata_obj,
16
+ Column("receipt_id", Integer, primary_key=True),
17
+ Column("customer_name", String(16), primary_key=True),
18
+ Column("price", Float),
19
+ Column("tip", Float),
 
 
 
 
 
 
20
  )
 
21
  metadata_obj.create_all(engine)
22
 
23
+ # Insert sample data
24
+ rows = [
25
+ {"receipt_id": 1, "customer_name": "Alan Payne", "price": 12.06, "tip": 1.20},
26
+ {"receipt_id": 2, "customer_name": "Alex Mason", "price": 23.86, "tip": 0.24},
27
+ {"receipt_id": 3, "customer_name": "Woodrow Wilson", "price": 53.43, "tip": 5.43},
28
+ {"receipt_id": 4, "customer_name": "Margaret James", "price": 21.11, "tip": 1.00},
 
 
 
 
 
 
 
 
 
 
 
29
  ]
30
+ with engine.begin() as conn:
31
+ for row in rows:
32
+ stmt = insert(receipts).values(**row)
 
33
  conn.execute(stmt)
34
 
35
+ # --- Create waiters table ---
36
+ waiters = Table(
37
+ "waiters",
38
+ metadata_obj,
39
+ Column("receipt_id", Integer, primary_key=True),
40
+ Column("waiter_name", String(16), primary_key=True),
41
+ )
42
+ metadata_obj.create_all(engine)
43
+
44
+ rows = [
45
+ {"receipt_id": 1, "waiter_name": "Corey Johnson"},
46
+ {"receipt_id": 2, "waiter_name": "Michael Watts"},
47
+ {"receipt_id": 3, "waiter_name": "Michael Watts"},
48
+ {"receipt_id": 4, "waiter_name": "Margaret James"},
49
+ ]
50
+ with engine.begin() as conn:
51
+ for row in rows:
52
+ stmt = insert(waiters).values(**row)
53
  conn.execute(stmt)
54
 
55
+ # --- Define SQL tool for the agent ---
56
  @tool
57
+ def sql_engine(query: str) -> list:
58
+ """Executes SQL queries on the available tables: receipts and waiters."""
59
  try:
60
+ print(f"🧩 Executing query: {query}") # Debug log
61
  with engine.connect() as con:
62
  rows = con.execute(text(query))
63
+ results = [tuple(row) for row in rows]
64
+ return results or []
 
65
  except Exception as e:
66
+ return [f"⚠️ SQL Error: {str(e)}"]
 
67
 
68
+ # Dynamically describe tables
69
+ updated_description = "Allows SQL queries on the following tables:\n"
70
  inspector = inspect(engine)
71
+ for table in ["receipts", "waiters"]:
 
72
  columns_info = [(col["name"], col["type"]) for col in inspector.get_columns(table)]
73
+ table_description = f"\n\nTable '{table}':\nColumns:\n" + "\n".join(
74
+ [f" - {name}: {col_type}" for name, col_type in columns_info]
75
  )
76
  updated_description += table_description
 
77
  sql_engine.description = updated_description
78
 
79
  # --- Create the agent ---
 
81
  tools=[sql_engine],
82
  model=InferenceClientModel(
83
  "meta-llama/Meta-Llama-3-8B-Instruct",
84
+ api_key=os.environ.get("HF_TOKEN") # Use secret from Space
85
  ),
86
  )
87
 
88
+ # --- Define Gradio interface ---
89
+ def ask_agent(question: str) -> str:
90
+ """Ask the AI agent a question and return its answer."""
91
+ try:
92
+ result = agent.run(question)
93
+ if isinstance(result, list):
94
+ result_str = "\n".join(str(r) for r in result)
95
+ return result_str or "No results."
96
+ return str(result)
97
+ except Exception as e:
98
+ return f"⚠️ Error: {str(e)}"
99
+
100
+ demo = gr.Interface(
101
+ fn=ask_agent,
102
+ inputs=gr.Textbox(label="Ask a question (e.g., Who got the biggest tip?)"),
103
+ outputs=gr.Textbox(label="Agent response"),
104
+ title="🧠 Text-to-SQL Agent",
105
+ description="Ask natural-language questions about a restaurant receipts database. Powered by smolagents + Meta-Llama-3.",
106
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
 
108
  demo.launch()