Sayandip commited on
Commit
48d5e02
·
verified ·
1 Parent(s): bff2a36

Update app.py

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