MasterOfHugs commited on
Commit
b4888ab
·
verified ·
1 Parent(s): 51155aa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -18
app.py CHANGED
@@ -10,9 +10,8 @@ import re
10
  import requests
11
  import pandas as pd
12
  import gradio as gr
13
- import yaml
14
 
15
- from smolagents import CodeAgent, HfApiModel, tool
16
 
17
  # -------------------------
18
  # Minimal tools
@@ -40,16 +39,35 @@ def safe_calc(expr: str):
40
 
41
  @tool
42
  def calculator(expr: str) -> str:
43
- """Safely evaluate a math expression."""
 
 
 
 
 
 
 
 
 
44
  try:
45
  val = safe_calc(expr)
46
  return json.dumps({"expression": expr, "result": float(val)})
47
  except Exception as e:
48
  return json.dumps({"error": f"Calc error: {e}"})
49
 
 
50
  @tool
51
  def get_current_time_in_timezone(timezone: str) -> str:
52
- """Get the current local time in a timezone."""
 
 
 
 
 
 
 
 
 
53
  try:
54
  tz = pytz.timezone(timezone)
55
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
@@ -57,24 +75,22 @@ def get_current_time_in_timezone(timezone: str) -> str:
57
  except Exception as e:
58
  return json.dumps({"error": f"Timezone error: {e}"})
59
 
 
60
  # -------------------------
61
  # Load prompts.yaml if exists
62
  # -------------------------
63
  prompt_templates = None
64
  try:
 
65
  with open("prompts.yaml", "r") as fh:
66
  prompt_templates = yaml.safe_load(fh)
67
  except Exception:
68
  prompt_templates = None
69
 
70
  # -------------------------
71
- # HfApiModel + CodeAgent
72
  # -------------------------
73
- model = HfApiModel(
74
- model_id="HuggingFaceTB/SmolLM-135M-Instruct",
75
- max_tokens=1024,
76
- temperature=0.5
77
- )
78
 
79
  code_agent = CodeAgent(
80
  model=model,
@@ -110,7 +126,10 @@ class GaiaAgentMinimal:
110
 
111
  # Time queries
112
  if self._is_time(q):
113
- tz = "Europe/Paris" if "paris" in q.lower() or "france" in q.lower() else "UTC"
 
 
 
114
  return get_current_time_in_timezone(tz)
115
 
116
  # fallback LLM
@@ -124,6 +143,7 @@ class GaiaAgentMinimal:
124
  except Exception as e:
125
  return json.dumps({"error": f"Agent internal error: {e}"})
126
 
 
127
  gaia_agent = GaiaAgentMinimal(code_agent)
128
 
129
  # -------------------------
@@ -133,13 +153,16 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
133
 
134
  def run_and_submit_all(profile: gr.OAuthProfile | None):
135
  space_id = os.getenv("SPACE_ID")
 
136
  if profile:
137
- username = profile.username
138
  else:
139
  return "Please Login to Hugging Face with the button.", None
140
 
141
- questions_url = f"{DEFAULT_API_URL}/questions"
142
- submit_url = f"{DEFAULT_API_URL}/submit"
 
 
143
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "unknown"
144
 
145
  # Fetch questions
@@ -153,7 +176,8 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
153
  return f"Error fetching questions: {e}", None
154
 
155
  # Run agent
156
- results_log, answers_payload = [], []
 
157
  for item in questions_data:
158
  task_id = item.get("task_id")
159
  question_text = item.get("question")
@@ -171,6 +195,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
171
 
172
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
173
 
 
174
  try:
175
  response = requests.post(submit_url, json=submission_data, timeout=60)
176
  response.raise_for_status()
@@ -182,20 +207,25 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
182
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
183
  f"Message: {result_data.get('message', 'No message received.')}"
184
  )
185
- return final_status, pd.DataFrame(results_log)
 
186
  except Exception as e:
187
- return f"Submission failed: {e}", pd.DataFrame(results_log)
 
188
 
189
  # -------------------------
190
  # Gradio UI
191
  # -------------------------
192
  with gr.Blocks() as demo:
193
  gr.Markdown("# Minimal GAIA Agent Runner")
194
- gr.Markdown("Log in to Hugging Face, click 'Run Evaluation & Submit All Answers' to fetch questions, run the agent, and submit answers.")
 
 
195
  gr.LoginButton()
196
  run_button = gr.Button("Run Evaluation & Submit All Answers")
197
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
198
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
 
199
  run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
200
 
201
  if __name__ == "__main__":
 
10
  import requests
11
  import pandas as pd
12
  import gradio as gr
 
13
 
14
+ from smolagents import CodeAgent, TransformersModel, tool
15
 
16
  # -------------------------
17
  # Minimal tools
 
39
 
40
  @tool
41
  def calculator(expr: str) -> str:
42
+ """
43
+ Safely evaluate a mathematical expression.
44
+
45
+ Args:
46
+ expr (str): Mathematical expression to evaluate, e.g., "2 + 2 * 3".
47
+
48
+ Returns:
49
+ str: JSON string with {"expression": expr, "result": value}
50
+ or {"error": "..."} on failure.
51
+ """
52
  try:
53
  val = safe_calc(expr)
54
  return json.dumps({"expression": expr, "result": float(val)})
55
  except Exception as e:
56
  return json.dumps({"error": f"Calc error: {e}"})
57
 
58
+
59
  @tool
60
  def get_current_time_in_timezone(timezone: str) -> str:
61
+ """
62
+ Get the current local time in a specified timezone.
63
+
64
+ Args:
65
+ timezone (str): A valid timezone string (e.g., "Europe/Paris").
66
+
67
+ Returns:
68
+ str: JSON string with {"timezone": timezone, "local_time": "..."}
69
+ or {"error": "..."} on failure.
70
+ """
71
  try:
72
  tz = pytz.timezone(timezone)
73
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
 
75
  except Exception as e:
76
  return json.dumps({"error": f"Timezone error: {e}"})
77
 
78
+
79
  # -------------------------
80
  # Load prompts.yaml if exists
81
  # -------------------------
82
  prompt_templates = None
83
  try:
84
+ import yaml
85
  with open("prompts.yaml", "r") as fh:
86
  prompt_templates = yaml.safe_load(fh)
87
  except Exception:
88
  prompt_templates = None
89
 
90
  # -------------------------
91
+ # TransformersModel + CodeAgent minimal
92
  # -------------------------
93
+ model = TransformersModel(model_id="HuggingFaceTB/SmolLM-135M-Instruct")
 
 
 
 
94
 
95
  code_agent = CodeAgent(
96
  model=model,
 
126
 
127
  # Time queries
128
  if self._is_time(q):
129
+ if "paris" in q.lower() or "france" in q.lower():
130
+ tz = "Europe/Paris"
131
+ else:
132
+ tz = "UTC"
133
  return get_current_time_in_timezone(tz)
134
 
135
  # fallback LLM
 
143
  except Exception as e:
144
  return json.dumps({"error": f"Agent internal error: {e}"})
145
 
146
+ # instantiate GAIA agent
147
  gaia_agent = GaiaAgentMinimal(code_agent)
148
 
149
  # -------------------------
 
153
 
154
  def run_and_submit_all(profile: gr.OAuthProfile | None):
155
  space_id = os.getenv("SPACE_ID")
156
+
157
  if profile:
158
+ username = f"{profile.username}"
159
  else:
160
  return "Please Login to Hugging Face with the button.", None
161
 
162
+ api_url = DEFAULT_API_URL
163
+ questions_url = f"{api_url}/questions"
164
+ submit_url = f"{api_url}/submit"
165
+
166
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "unknown"
167
 
168
  # Fetch questions
 
176
  return f"Error fetching questions: {e}", None
177
 
178
  # Run agent
179
+ results_log = []
180
+ answers_payload = []
181
  for item in questions_data:
182
  task_id = item.get("task_id")
183
  question_text = item.get("question")
 
195
 
196
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
197
 
198
+ # Submit
199
  try:
200
  response = requests.post(submit_url, json=submission_data, timeout=60)
201
  response.raise_for_status()
 
207
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
208
  f"Message: {result_data.get('message', 'No message received.')}"
209
  )
210
+ results_df = pd.DataFrame(results_log)
211
+ return final_status, results_df
212
  except Exception as e:
213
+ results_df = pd.DataFrame(results_log)
214
+ return f"Submission failed: {e}", results_df
215
 
216
  # -------------------------
217
  # Gradio UI
218
  # -------------------------
219
  with gr.Blocks() as demo:
220
  gr.Markdown("# Minimal GAIA Agent Runner")
221
+ gr.Markdown(
222
+ "Log in to Hugging Face, click 'Run Evaluation & Submit All Answers' to fetch questions, run the agent, and submit answers."
223
+ )
224
  gr.LoginButton()
225
  run_button = gr.Button("Run Evaluation & Submit All Answers")
226
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
227
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
228
+
229
  run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
230
 
231
  if __name__ == "__main__":