ArielShadrac commited on
Commit
218d7ac
·
1 Parent(s): 0be4662

Add smolagents GAIA agent

Browse files
Files changed (1) hide show
  1. app.py +114 -207
app.py CHANGED
@@ -1,289 +1,196 @@
1
  import os
2
  import gradio as gr
3
  import requests
 
4
  import pandas as pd
5
 
6
- from smolagents import (
7
- CodeAgent,
8
- DuckDuckGoSearchTool,
9
- InferenceClientModel,
10
- tool,
11
- )
12
-
13
-
14
  # --- Constants ---
15
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
16
 
17
- # --- Custom Tools ---
18
-
19
- @tool
20
- def download_file_from_task(task_id: str) -> str:
 
 
 
 
 
 
 
 
21
  """
22
- Downloads a file associated with a GAIA task and returns its content as text.
23
- Use this when a question references an attached file.
24
-
25
- Args:
26
- task_id: The task ID string of the GAIA question.
27
- """
28
- url = f"{DEFAULT_API_URL}/files/{task_id}"
29
- try:
30
- response = requests.get(url, timeout=30)
31
- response.raise_for_status()
32
- content_type = response.headers.get("content-type", "")
33
-
34
- # Try to decode as text
35
- try:
36
- text = response.content.decode("utf-8")
37
- # Truncate if too long
38
- if len(text) > 8000:
39
- text = text[:8000] + "\n[... truncated ...]"
40
- return text
41
- except UnicodeDecodeError:
42
- return f"File downloaded but contains binary content (content-type: {content_type}). Size: {len(response.content)} bytes."
43
-
44
- except requests.exceptions.RequestException as e:
45
- return f"Error downloading file for task {task_id}: {e}"
46
-
47
-
48
- @tool
49
- def python_calculator(code: str) -> str:
50
  """
51
- Executes a Python expression or small snippet and returns the result.
52
- Use for arithmetic, unit conversions, date calculations, or any numerical reasoning.
53
- Only use safe, simple expressions. No imports needed for basic math.
54
 
55
- Args:
56
- code: A Python expression or short snippet to evaluate (e.g. '2 ** 10', 'round(3.14159 * 2, 4)')
57
- """
58
- import math
59
- import datetime
60
- allowed_globals = {
61
- "__builtins__": {},
62
- "math": math,
63
- "datetime": datetime,
64
- "abs": abs,
65
- "round": round,
66
- "int": int,
67
- "float": float,
68
- "str": str,
69
- "len": len,
70
- "sum": sum,
71
- "min": min,
72
- "max": max,
73
- "sorted": sorted,
74
- "range": range,
75
- "list": list,
76
- "dict": dict,
77
- "set": set,
78
- "zip": zip,
79
- "enumerate": enumerate,
80
- "print": print,
81
- }
82
- try:
83
- result = eval(code, allowed_globals)
84
- return str(result)
85
- except Exception:
86
- try:
87
- exec_globals = allowed_globals.copy()
88
- exec(code, exec_globals)
89
- output = exec_globals.get("result", exec_globals.get("output", "Code executed but no 'result' variable found."))
90
- return str(output)
91
- except Exception as e:
92
- return f"Error executing code: {e}"
93
-
94
-
95
- # --- System Prompt ---
96
- SYSTEM_PROMPT = """You are an expert research assistant tasked with answering questions from the GAIA benchmark.
97
-
98
- CRITICAL RULES:
99
- 1. Your final answer must be EXACT and CONCISE. No explanations, no sentences, no punctuation unless part of the answer.
100
- 2. If the answer is a number, return ONLY the number (e.g. "42" not "The answer is 42").
101
- 3. If the answer is a name, return ONLY the name (e.g. "Marie Curie" not "The answer is Marie Curie").
102
- 4. If the answer is a list, return items separated by commas (e.g. "cat, dog, fish").
103
- 5. If a question references a file or attachment, use the download_file_from_task tool with the task_id.
104
- 6. Always search the web for factual questions before answering.
105
- 7. Double-check calculations using the python_calculator tool.
106
- 8. Never include "FINAL ANSWER:" in your response.
107
- 9. Match the exact format requested in the question (abbreviation, full name, number, etc.).
108
- """
109
-
110
-
111
- # --- Agent Factory ---
112
- def build_agent():
113
- model = InferenceClientModel(
114
- model_id="Qwen/Qwen2.5-72B-Instruct",
115
- max_tokens=2048,
116
- temperature=0.1,
117
- )
118
-
119
- agent = CodeAgent(
120
- model=model,
121
- tools=[
122
- DuckDuckGoSearchTool(),
123
- download_file_from_task,
124
- python_calculator,
125
- ],
126
- max_steps=8,
127
- verbosity_level=1,
128
- additional_authorized_imports=["math", "datetime", "re", "json", "csv", "io"],
129
- )
130
-
131
- # Inject system prompt into agent
132
- agent.system_prompt = SYSTEM_PROMPT + "\n\n" + agent.system_prompt
133
-
134
- return agent
135
-
136
-
137
- # --- Main Runner ---
138
- def run_and_submit_all(profile: gr.OAuthProfile | None):
139
- """
140
- Fetches all questions, runs the agent on them, submits answers, and displays results.
141
- """
142
- space_id = os.getenv("SPACE_ID")
143
-
144
- if not profile:
145
- return "Please login to Hugging Face first.", None
146
-
147
- username = profile.username
148
- print(f"User logged in: {username}")
149
 
150
  api_url = DEFAULT_API_URL
151
  questions_url = f"{api_url}/questions"
152
  submit_url = f"{api_url}/submit"
153
 
154
- # 1. Build agent
155
  try:
156
- agent = build_agent()
157
  except Exception as e:
 
158
  return f"Error initializing agent: {e}", None
159
-
160
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
161
- print(f"Agent code link: {agent_code}")
162
 
163
- # 2. Fetch questions
164
  print(f"Fetching questions from: {questions_url}")
165
  try:
166
  response = requests.get(questions_url, timeout=15)
167
  response.raise_for_status()
168
  questions_data = response.json()
169
  if not questions_data:
170
- return "Fetched questions list is empty.", None
 
171
  print(f"Fetched {len(questions_data)} questions.")
172
- except Exception as e:
 
173
  return f"Error fetching questions: {e}", None
 
 
 
 
 
 
 
174
 
175
- # 3. Run agent on each question
176
  results_log = []
177
  answers_payload = []
178
  print(f"Running agent on {len(questions_data)} questions...")
179
-
180
  for item in questions_data:
181
  task_id = item.get("task_id")
182
  question_text = item.get("question")
183
-
184
  if not task_id or question_text is None:
185
  print(f"Skipping item with missing task_id or question: {item}")
186
  continue
187
-
188
- # Inject task_id into question so agent can use download_file_from_task
189
- augmented_question = f"[task_id: {task_id}]\n\n{question_text}"
190
-
191
  try:
192
- submitted_answer = agent.run(augmented_question)
193
- submitted_answer = str(submitted_answer).strip()
194
- print(f"Task {task_id}: {submitted_answer[:80]}")
195
  except Exception as e:
196
- submitted_answer = f"AGENT ERROR: {e}"
197
- print(f"Error on task {task_id}: {e}")
198
-
199
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
200
- results_log.append({
201
- "Task ID": task_id,
202
- "Question": question_text[:120],
203
- "Submitted Answer": submitted_answer,
204
- })
205
 
206
  if not answers_payload:
207
- return "Agent produced no answers.", pd.DataFrame(results_log)
 
208
 
209
- # 4. Submit
210
- submission_data = {
211
- "username": username.strip(),
212
- "agent_code": agent_code,
213
- "answers": answers_payload,
214
- }
215
 
216
- print(f"Submitting {len(answers_payload)} answers...")
 
217
  try:
218
- response = requests.post(submit_url, json=submission_data, timeout=120)
219
  response.raise_for_status()
220
  result_data = response.json()
221
  final_status = (
222
  f"Submission Successful!\n"
223
  f"User: {result_data.get('username')}\n"
224
- f"Score: {result_data.get('score', 'N/A')}% "
225
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
226
  f"Message: {result_data.get('message', 'No message received.')}"
227
  )
228
  print("Submission successful.")
229
- return final_status, pd.DataFrame(results_log)
 
230
  except requests.exceptions.HTTPError as e:
 
231
  try:
232
- detail = e.response.json().get("detail", e.response.text)
233
- except Exception:
234
- detail = e.response.text[:500]
235
- return f"Submission Failed: {detail}", pd.DataFrame(results_log)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
  except Exception as e:
237
- return f"Submission Failed: {e}", pd.DataFrame(results_log)
 
 
 
238
 
239
 
240
- # --- Gradio Interface ---
241
  with gr.Blocks() as demo:
242
- gr.Markdown("# GAIA Agent - Unit 4 Final Assignment")
243
  gr.Markdown(
244
  """
245
  **Instructions:**
246
- 1. Log in with your Hugging Face account below.
247
- 2. Click **Run Evaluation & Submit** to start the agent on all 20 GAIA questions.
248
- 3. Results and score will appear below.
249
 
250
- The agent uses web search, file downloading, and Python calculations to answer questions.
251
- Target: >= 30% to earn the course certificate.
 
 
 
 
 
 
252
  """
253
  )
254
 
255
  gr.LoginButton()
256
 
257
- run_button = gr.Button("Run Evaluation & Submit All Answers", variant="primary")
258
 
259
- status_output = gr.Textbox(
260
- label="Submission Result",
261
- lines=6,
262
- interactive=False,
263
- )
264
- results_table = gr.DataFrame(
265
- label="Questions and Agent Answers",
266
- wrap=True,
267
- )
268
 
269
  run_button.click(
270
  fn=run_and_submit_all,
271
- outputs=[status_output, results_table],
272
  )
273
 
274
  if __name__ == "__main__":
275
- print("\n" + "-" * 30 + " App Starting " + "-" * 30)
276
-
277
  space_host_startup = os.getenv("SPACE_HOST")
278
- space_id_startup = os.getenv("SPACE_ID")
279
 
280
  if space_host_startup:
281
- print(f"SPACE_HOST: {space_host_startup}")
282
- if space_id_startup:
283
- print(f"SPACE_ID: {space_id_startup}")
284
- print(f"Repo URL: https://huggingface.co/spaces/{space_id_startup}")
285
- print(f"Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
 
 
 
 
 
 
 
 
286
 
287
- print("-" * 74 + "\n")
288
- print("Launching Gradio Interface...")
289
  demo.launch(debug=True, share=False)
 
1
  import os
2
  import gradio as gr
3
  import requests
4
+ import inspect
5
  import pandas as pd
6
 
7
+ # (Keep Constants as is)
 
 
 
 
 
 
 
8
  # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
+ # --- Basic Agent Definition ---
12
+ # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
13
+ class BasicAgent:
14
+ def __init__(self):
15
+ print("BasicAgent initialized.")
16
+ def __call__(self, question: str) -> str:
17
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
18
+ fixed_answer = "This is a default answer."
19
+ print(f"Agent returning fixed answer: {fixed_answer}")
20
+ return fixed_answer
21
+
22
+ def run_and_submit_all( profile: gr.OAuthProfile | None):
23
  """
24
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
25
+ and displays the results.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  """
27
+ # --- Determine HF Space Runtime URL and Repo URL ---
28
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
 
29
 
30
+ if profile:
31
+ username= f"{profile.username}"
32
+ print(f"User logged in: {username}")
33
+ else:
34
+ print("User not logged in.")
35
+ return "Please Login to Hugging Face with the button.", None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
  api_url = DEFAULT_API_URL
38
  questions_url = f"{api_url}/questions"
39
  submit_url = f"{api_url}/submit"
40
 
41
+ # 1. Instantiate Agent ( modify this part to create your agent)
42
  try:
43
+ agent = BasicAgent()
44
  except Exception as e:
45
+ print(f"Error instantiating agent: {e}")
46
  return f"Error initializing agent: {e}", None
47
+ # In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
48
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
49
+ print(agent_code)
50
 
51
+ # 2. Fetch Questions
52
  print(f"Fetching questions from: {questions_url}")
53
  try:
54
  response = requests.get(questions_url, timeout=15)
55
  response.raise_for_status()
56
  questions_data = response.json()
57
  if not questions_data:
58
+ print("Fetched questions list is empty.")
59
+ return "Fetched questions list is empty or invalid format.", None
60
  print(f"Fetched {len(questions_data)} questions.")
61
+ except requests.exceptions.RequestException as e:
62
+ print(f"Error fetching questions: {e}")
63
  return f"Error fetching questions: {e}", None
64
+ except requests.exceptions.JSONDecodeError as e:
65
+ print(f"Error decoding JSON response from questions endpoint: {e}")
66
+ print(f"Response text: {response.text[:500]}")
67
+ return f"Error decoding server response for questions: {e}", None
68
+ except Exception as e:
69
+ print(f"An unexpected error occurred fetching questions: {e}")
70
+ return f"An unexpected error occurred fetching questions: {e}", None
71
 
72
+ # 3. Run your Agent
73
  results_log = []
74
  answers_payload = []
75
  print(f"Running agent on {len(questions_data)} questions...")
 
76
  for item in questions_data:
77
  task_id = item.get("task_id")
78
  question_text = item.get("question")
 
79
  if not task_id or question_text is None:
80
  print(f"Skipping item with missing task_id or question: {item}")
81
  continue
 
 
 
 
82
  try:
83
+ submitted_answer = agent(question_text)
84
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
85
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
86
  except Exception as e:
87
+ print(f"Error running agent on task {task_id}: {e}")
88
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
 
 
 
 
 
 
89
 
90
  if not answers_payload:
91
+ print("Agent did not produce any answers to submit.")
92
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
93
 
94
+ # 4. Prepare Submission
95
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
96
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
97
+ print(status_update)
 
 
98
 
99
+ # 5. Submit
100
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
101
  try:
102
+ response = requests.post(submit_url, json=submission_data, timeout=60)
103
  response.raise_for_status()
104
  result_data = response.json()
105
  final_status = (
106
  f"Submission Successful!\n"
107
  f"User: {result_data.get('username')}\n"
108
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
109
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
110
  f"Message: {result_data.get('message', 'No message received.')}"
111
  )
112
  print("Submission successful.")
113
+ results_df = pd.DataFrame(results_log)
114
+ return final_status, results_df
115
  except requests.exceptions.HTTPError as e:
116
+ error_detail = f"Server responded with status {e.response.status_code}."
117
  try:
118
+ error_json = e.response.json()
119
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
120
+ except requests.exceptions.JSONDecodeError:
121
+ error_detail += f" Response: {e.response.text[:500]}"
122
+ status_message = f"Submission Failed: {error_detail}"
123
+ print(status_message)
124
+ results_df = pd.DataFrame(results_log)
125
+ return status_message, results_df
126
+ except requests.exceptions.Timeout:
127
+ status_message = "Submission Failed: The request timed out."
128
+ print(status_message)
129
+ results_df = pd.DataFrame(results_log)
130
+ return status_message, results_df
131
+ except requests.exceptions.RequestException as e:
132
+ status_message = f"Submission Failed: Network error - {e}"
133
+ print(status_message)
134
+ results_df = pd.DataFrame(results_log)
135
+ return status_message, results_df
136
  except Exception as e:
137
+ status_message = f"An unexpected error occurred during submission: {e}"
138
+ print(status_message)
139
+ results_df = pd.DataFrame(results_log)
140
+ return status_message, results_df
141
 
142
 
143
+ # --- Build Gradio Interface using Blocks ---
144
  with gr.Blocks() as demo:
145
+ gr.Markdown("# Basic Agent Evaluation Runner")
146
  gr.Markdown(
147
  """
148
  **Instructions:**
 
 
 
149
 
150
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
151
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
152
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
153
+
154
+ ---
155
+ **Disclaimers:**
156
+ Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
157
+ This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
158
  """
159
  )
160
 
161
  gr.LoginButton()
162
 
163
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
164
 
165
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
166
+ # Removed max_rows=10 from DataFrame constructor
167
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
 
 
 
 
 
 
168
 
169
  run_button.click(
170
  fn=run_and_submit_all,
171
+ outputs=[status_output, results_table]
172
  )
173
 
174
  if __name__ == "__main__":
175
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
176
+ # Check for SPACE_HOST and SPACE_ID at startup for information
177
  space_host_startup = os.getenv("SPACE_HOST")
178
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
179
 
180
  if space_host_startup:
181
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
182
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
183
+ else:
184
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
185
+
186
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
187
+ print(f"✅ SPACE_ID found: {space_id_startup}")
188
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
189
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
190
+ else:
191
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
192
+
193
+ print("-"*(60 + len(" App Starting ")) + "\n")
194
 
195
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
 
196
  demo.launch(debug=True, share=False)