Sayandip commited on
Commit
6593157
·
verified ·
1 Parent(s): adbefc2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -52
app.py CHANGED
@@ -3,56 +3,58 @@ 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 (in-memory) ---
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) -> str:
56
  """
57
  Executes SQL queries on the available tables: receipts and waiters.
58
 
@@ -60,16 +62,17 @@ def sql_engine(query: str) -> str:
60
  query: SQL query string.
61
  """
62
  try:
63
- output = ""
64
  with engine.connect() as con:
65
  rows = con.execute(text(query))
66
- for row in rows:
67
- output += "\n" + str(row)
68
- return output or "No results."
 
69
  except Exception as e:
70
  return f"⚠️ SQL Error: {str(e)}"
71
 
72
- # Dynamically describe tables
73
  updated_description = "Allows SQL queries on the following tables:\n"
74
  inspector = inspect(engine)
75
  for table in ["receipts", "waiters"]:
@@ -80,26 +83,25 @@ for table in ["receipts", "waiters"]:
80
  updated_description += table_description
81
  sql_engine.description = updated_description
82
 
83
- # --- Create the agent ---
84
- # Use the HF_TOKEN secret stored in the Space
85
  agent = CodeAgent(
86
  tools=[sql_engine],
87
  model=InferenceClientModel(
88
  "meta-llama/Meta-Llama-3-8B-Instruct",
89
- api_key=os.environ.get("HF_TOKEN") # 👈 Use secret key
90
  ),
91
  )
92
 
93
  # --- Define Gradio interface ---
94
  def ask_agent(question):
95
- """Ask the AI agent a question."""
96
  result = agent.run(question)
97
  return result
98
 
99
  demo = gr.Interface(
100
  fn=ask_agent,
101
- inputs=gr.Textbox(label="Ask a question (e.g., Who got the biggest tip?)"),
102
- outputs=gr.Textbox(label="Agent response"),
103
  title="🧠 Text-to-SQL Agent",
104
  description="Ask natural-language questions about a restaurant receipts database. Powered by smolagents + Meta-Llama-3.",
105
  )
 
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 file-based) ---
7
  engine = create_engine("sqlite:///data.db")
8
  metadata_obj = MetaData()
9
 
10
+ # --- Create receipts table (if not exists) ---
11
+ if not engine.dialect.has_table(engine.connect(), "receipts"):
12
+ receipts = Table(
13
+ "receipts",
14
+ metadata_obj,
15
+ Column("receipt_id", Integer, primary_key=True),
16
+ Column("customer_name", String(16)),
17
+ Column("price", Float),
18
+ Column("tip", Float),
19
+ )
20
+ metadata_obj.create_all(engine)
21
 
22
+ # Insert sample data
23
+ rows = [
24
+ {"receipt_id": 1, "customer_name": "Alan Payne", "price": 12.06, "tip": 1.20},
25
+ {"receipt_id": 2, "customer_name": "Alex Mason", "price": 23.86, "tip": 0.24},
26
+ {"receipt_id": 3, "customer_name": "Woodrow Wilson", "price": 53.43, "tip": 5.43},
27
+ {"receipt_id": 4, "customer_name": "Margaret James", "price": 21.11, "tip": 1.00},
28
+ ]
29
+ for row in rows:
30
+ stmt = insert(Table("receipts", metadata_obj, autoload_with=engine)).values(**row)
31
+ with engine.begin() as conn:
32
+ conn.execute(stmt)
33
 
34
+ # --- Create waiters table (if not exists) ---
35
+ if not engine.dialect.has_table(engine.connect(), "waiters"):
36
+ waiters = Table(
37
+ "waiters",
38
+ metadata_obj,
39
+ Column("receipt_id", Integer, primary_key=True),
40
+ Column("waiter_name", String(16)),
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
+ for row in rows:
51
+ stmt = insert(Table("waiters", metadata_obj, autoload_with=engine)).values(**row)
52
+ with engine.begin() as conn:
53
+ conn.execute(stmt)
54
 
55
  # --- Define SQL tool for the agent ---
56
  @tool
57
+ def sql_engine(query: str):
58
  """
59
  Executes SQL queries on the available tables: receipts and waiters.
60
 
 
62
  query: SQL query string.
63
  """
64
  try:
65
+ print(f"🧩 Executing query: {query}") # Debug log in Space console
66
  with engine.connect() as con:
67
  rows = con.execute(text(query))
68
+ results = [tuple(row) for row in rows]
69
+ if not results:
70
+ return "No results."
71
+ return results
72
  except Exception as e:
73
  return f"⚠️ SQL Error: {str(e)}"
74
 
75
+ # --- Describe tables for the model ---
76
  updated_description = "Allows SQL queries on the following tables:\n"
77
  inspector = inspect(engine)
78
  for table in ["receipts", "waiters"]:
 
83
  updated_description += table_description
84
  sql_engine.description = updated_description
85
 
86
+ # --- Create the AI agent ---
 
87
  agent = CodeAgent(
88
  tools=[sql_engine],
89
  model=InferenceClientModel(
90
  "meta-llama/Meta-Llama-3-8B-Instruct",
91
+ api_key=os.environ.get("HF_TOKEN"), # Uses HF secret
92
  ),
93
  )
94
 
95
  # --- Define Gradio interface ---
96
  def ask_agent(question):
97
+ """Ask the AI agent a question and return the result."""
98
  result = agent.run(question)
99
  return result
100
 
101
  demo = gr.Interface(
102
  fn=ask_agent,
103
+ inputs=gr.Textbox(label="💬 Ask a question (e.g., Who got the biggest tip?)"),
104
+ outputs=gr.Textbox(label="🤖 Agent response"),
105
  title="🧠 Text-to-SQL Agent",
106
  description="Ask natural-language questions about a restaurant receipts database. Powered by smolagents + Meta-Llama-3.",
107
  )