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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -51
app.py CHANGED
@@ -3,63 +3,64 @@ 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 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
 
61
  Args:
62
  query: SQL query string.
 
 
 
63
  """
64
  try:
65
  print(f"🧩 Executing query: {query}") # Debug log in Space console
@@ -68,11 +69,11 @@ def sql_engine(query: str):
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,25 +84,26 @@ 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
  )
 
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) ---
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
 
59
  Args:
60
  query: SQL query string.
61
+
62
+ Returns:
63
+ A string representing the query results, or an error message.
64
  """
65
  try:
66
  print(f"🧩 Executing query: {query}") # Debug log in Space console
 
69
  results = [tuple(row) for row in rows]
70
  if not results:
71
  return "No results."
72
+ return "\n".join(str(r) for r in results)
73
  except Exception as e:
74
  return f"⚠️ SQL Error: {str(e)}"
75
 
76
+ # Dynamically describe tables
77
  updated_description = "Allows SQL queries on the following tables:\n"
78
  inspector = inspect(engine)
79
  for table in ["receipts", "waiters"]:
 
84
  updated_description += table_description
85
  sql_engine.description = updated_description
86
 
87
+ # --- Create the agent ---
88
+ # Use the HF_TOKEN secret stored in the Space
89
  agent = CodeAgent(
90
  tools=[sql_engine],
91
  model=InferenceClientModel(
92
  "meta-llama/Meta-Llama-3-8B-Instruct",
93
+ api_key=os.environ.get("HF_TOKEN") # 👈 Hugging Face secret
94
  ),
95
  )
96
 
97
  # --- Define Gradio interface ---
98
+ def ask_agent(question: str) -> str:
99
+ """Ask the AI agent a question."""
100
  result = agent.run(question)
101
  return result
102
 
103
  demo = gr.Interface(
104
  fn=ask_agent,
105
+ inputs=gr.Textbox(label="Ask a question (e.g., Who got the biggest tip?)"),
106
+ outputs=gr.Textbox(label="Agent response"),
107
  title="🧠 Text-to-SQL Agent",
108
  description="Ask natural-language questions about a restaurant receipts database. Powered by smolagents + Meta-Llama-3.",
109
  )