hassenhamdi commited on
Commit
ceee7cf
·
verified ·
1 Parent(s): 81917a3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +193 -122
app.py CHANGED
@@ -3,32 +3,161 @@ 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.")
@@ -38,123 +167,70 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
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
 
@@ -163,7 +239,6 @@ with gr.Blocks() as demo:
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(
@@ -173,9 +248,8 @@ with gr.Blocks() as demo:
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}")
@@ -183,14 +257,11 @@ if __name__ == "__main__":
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)
 
3
  import requests
4
  import inspect
5
  import pandas as pd
6
+ from smolagents import OpenAIServerModel
7
+ from smolagents import CodeAgent, Tool, tool
8
+ from smolagents import DuckDuckGoSearchTool, VisitWebpageTool
9
+ from smolagents import PythonInterpreterTool # Import the built-in Python Interpreter Tool
10
 
 
11
  # --- Constants ---
12
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
13
 
14
+ # --- Tool Definitions ---
15
+
16
+ class GaiaFileTool(Tool):
17
+ """
18
+ A smolagents.Tool subclass for downloading files from the GAIA API.
19
+ """
20
+ name = "download_gaia_file"
21
+ description = "Downloads a file associated with a given GAIA task ID and returns its content. It takes 'task_id' as input and returns the file content as a string. Use this when a question refers to an external file."
22
+ inputs = {"task_id": {"type": "str", "description": "The task ID for which to download the file (e.g., '2345')."}}
23
+ output_type = str
24
+
25
+ def __init__(self, api_base_url=DEFAULT_API_URL):
26
+ super().__init__()
27
+ self.api_base_url = api_base_url
28
+ print(f"GaiaFileTool initialized with API base URL: {self.api_base_url}")
29
+
30
+ def forward(self, task_id: str) -> str:
31
+ """
32
+ The core logic for the tool: downloads a file from the GAIA API.
33
+ This method is called by the agent when it uses this tool.
34
+ """
35
+ file_url = f"{self.api_base_url}/files/{task_id}"
36
+ print(f"Attempting to download file from: {file_url}")
37
+ try:
38
+ response = requests.get(file_url)
39
+ response.raise_for_status()
40
+ print(f"Successfully downloaded file for task_id {task_id}")
41
+ return response.text
42
+ except requests.exceptions.RequestException as e:
43
+ print(f"Error downloading file for task_id {task_id}: {e}")
44
+ return f"Error downloading file: {e}"
45
+
46
+ # Removed the custom python_repl function as we are using the built-in tool
47
+
48
+ # --- Custom GAIA Agent Definition ---
49
+ class GaiaAgent(CodeAgent):
50
+ """
51
+ A smolagents-based agent designed to tackle GAIA Level 1 benchmark questions.
52
+ It uses Gemini Flash for reasoning and integrates a Python Interpreter, a
53
+ GAIA file download tool, and web browsing/searching tools.
54
+ """
55
  def __init__(self):
56
+ print("GaiaAgent initializing...")
57
+ gemini_api_key = os.getenv("GEMINI_API_KEY")
58
+ if not gemini_api_key:
59
+ print("WARNING: GEMINI_API_KEY environment variable not set.")
60
+ print("Please set GEMINI_API_KEY for Gemini Flash to work.")
61
+
62
+ self.llm_model = OpenAIServerModel(
63
+ model_id="gemini-2.0-flash",
64
+ api_base="https://generativelanguage.googleapis.com/v1beta/openai/",
65
+ api_key=gemini_api_key,
66
+ temperature=0.1,
67
+ )
68
+
69
+ # Initialize GAIA file tool
70
+ gaia_file_tool_instance = GaiaFileTool()
71
+
72
+ # Initialize web searching and browsing tools
73
+ duckduckgo_search_tool = DuckDuckGoSearchTool()
74
+ visit_webpage_tool = VisitWebpageTool()
75
+
76
+ # Initialize the built-in Python Interpreter Tool
77
+ # By default, PythonInterpreterTool uses a local executor, which is generally safe
78
+ # for controlled environments like Hugging Face Spaces.
79
+ python_interpreter_tool = PythonInterpreterTool()
80
+
81
+ # Define the tools available to the agent
82
+ agent_tools = [
83
+ python_interpreter_tool, # Use the built-in Python interpreter tool
84
+ gaia_file_tool_instance,
85
+ duckduckgo_search_tool,
86
+ visit_webpage_tool
87
+ ]
88
+ super().__init__(model=self.llm_model, tools=agent_tools)
89
+ print("GaiaAgent initialized successfully with Gemini Flash and built-in tools.")
90
+
91
  def __call__(self, question: str) -> str:
92
+ """
93
+ The main method for the agent to process a question and return an answer.
94
+ This will involve the agent's internal reasoning, tool use, and planning.
95
+ """
96
+ print(f"\n--- Agent received question (first 100 chars): {question[:100]}...")
97
 
98
+ try:
99
+ prompt = (
100
+ f"You are an AI agent designed to solve GAIA benchmark questions. "
101
+ f"Your goal is to provide the exact answer as a string, without any additional text, "
102
+ f"explanation, or the phrase 'FINAL ANSWER:'. "
103
+ f"Break down the problem, use the available tools (python_interpreter, download_gaia_file, "
104
+ f"duckduckgo_search_tool, visit_webpage_tool) as needed, and think step-by-step. "
105
+ f"Use 'python_interpreter' for any calculations or code execution. "
106
+ f"Use 'duckduckgo_search_tool' to find information on the web. "
107
+ f"Use 'visit_webpage_tool' to read the content of a specific URL. "
108
+ f"When you have the final answer, output ONLY the answer string.\n\n"
109
+ f"Question: {question}"
110
+ )
111
+
112
+ result = self.run(query=prompt)
113
+
114
+ final_answer = self._extract_exact_answer(result)
115
+ print(f"--- Agent returning final answer (first 100 chars): {final_answer[:100]}...")
116
+ return final_answer
117
+ except Exception as e:
118
+ print(f"--- Error during agent execution: {e}")
119
+ return "Agent encountered an error and could not provide an answer."
120
+
121
+ def _extract_exact_answer(self, raw_output: str) -> str:
122
+ """
123
+ Extracts and formats the exact answer from the agent's raw output.
124
+ Ensures no "FINAL ANSWER" text is included and handles any
125
+ extraneous formatting. This function is crucial for GAIA's exact match scoring.
126
+ """
127
+ cleaned_output = raw_output.replace("FINAL ANSWER:", "").strip()
128
+ cleaned_output = cleaned_output.replace("Answer:", "").strip()
129
+ cleaned_output = cleaned_output.replace("The answer is:", "").strip()
130
+ cleaned_output = cleaned_output.replace("```python", "").replace("```", "").strip()
131
+
132
+ lines = cleaned_output.split('\n')
133
+ if lines:
134
+ potential_answer = lines[-1].strip()
135
+ if len(potential_answer) < 5 or "tool_code" in potential_answer.lower():
136
+ for line in reversed(lines[:-1]):
137
+ if line.strip() and "tool_code" not in line.lower():
138
+ potential_answer = line.strip()
139
+ break
140
+ cleaned_output = potential_answer
141
+
142
+ if cleaned_output.startswith('"') and cleaned_output.endswith('"'):
143
+ cleaned_output = cleaned_output[1:-1]
144
+ if cleaned_output.startswith("'") and cleaned_output.endswith("'"):
145
+ cleaned_output = cleaned_output[1:-1]
146
+
147
+ return cleaned_output.strip()
148
+
149
+
150
+ # --- Gradio Application Logic (mostly unchanged from template) ---
151
+
152
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
153
  """
154
+ Fetches all questions, runs the GaiaAgent on them, submits all answers,
155
  and displays the results.
156
  """
157
+ space_id = os.getenv("SPACE_ID")
 
158
 
159
  if profile:
160
+ username = f"{profile.username}"
161
  print(f"User logged in: {username}")
162
  else:
163
  print("User not logged in.")
 
167
  questions_url = f"{api_url}/questions"
168
  submit_url = f"{api_url}/submit"
169
 
 
170
  try:
171
+ agent = GaiaAgent()
172
  except Exception as e:
 
173
  return f"Error initializing agent: {e}", None
 
 
 
174
 
 
 
175
  try:
176
+ print(f"Fetching questions from: {questions_url}")
177
+ questions_response = requests.get(questions_url)
178
+ questions_response.raise_for_status()
179
+ questions = questions_response.json()
180
+ print(f"Fetched {len(questions)} questions.")
 
 
181
  except requests.exceptions.RequestException as e:
 
182
  return f"Error fetching questions: {e}", None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
183
 
184
+ all_answers = []
185
+ results_data = []
186
+
187
+ for i, q_data in enumerate(questions):
188
+ task_id = q_data.get("task_id", f"unknown_{i}")
189
+ question_text = q_data.get("question", "No question text found.")
190
+ print(f"\n--- Processing Task ID: {task_id} ---")
191
+ print(f"Question: {question_text[:100]}...")
192
 
193
+ agent_answer = agent(question_text)
194
+ all_answers.append({"task_id": task_id, "answer": agent_answer})
195
+ results_data.append({
196
+ "Task ID": task_id,
197
+ "Question": question_text,
198
+ "Agent Answer": agent_answer
199
+ })
200
+ print(f"--- Finished processing Task ID: {task_id} ---")
201
 
 
 
202
  try:
203
+ print(f"\nSubmitting {len(all_answers)} answers to: {submit_url}")
204
+ submission_payload = {
205
+ "username": username,
206
+ "code_link": f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "local_execution",
207
+ "answers": all_answers
208
+ }
209
+ submit_response = requests.post(submit_url, json=submission_payload)
210
+ submit_response.raise_for_status()
211
+ submission_result = submit_response.json()
212
+ print(f"Submission successful: {submission_result}")
213
+ status_message = f"Submission successful!\nScore: {submission_result.get('score', 'N/A')}\nDetails: {submission_result.get('message', 'No message')}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
  except requests.exceptions.RequestException as e:
215
+ print(f"Error submitting answers: {e}")
216
+ status_message = f"Error submitting answers: {e}"
 
 
 
 
 
 
 
217
 
218
+ results_df = pd.DataFrame(results_data)
219
+ return status_message, results_df
220
 
221
+ # --- Gradio UI ---
222
  with gr.Blocks() as demo:
 
223
  gr.Markdown(
224
  """
225
+ # GAIA Level 1 Agent Evaluation
226
+ This application allows you to run your `smolagents`-based agent on the GAIA Level 1 benchmark
227
+ and submit your answers to the leaderboard.
228
 
229
+ **Important:**
230
+ 1. **Login to Hugging Face** using the button below to submit your score.
231
+ 2. **Set `GEMINI_API_KEY`**: Ensure your `GEMINI_API_KEY` is set as a Space Secret
232
+ in Hugging Face Spaces (or as an environment variable if running locally)
233
+ for the Gemini Flash model to function.
 
 
 
234
  """
235
  )
236
 
 
239
  run_button = gr.Button("Run Evaluation & Submit All Answers")
240
 
241
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
242
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
243
 
244
  run_button.click(
 
248
 
249
  if __name__ == "__main__":
250
  print("\n" + "-"*30 + " App Starting " + "-"*30)
 
251
  space_host_startup = os.getenv("SPACE_HOST")
252
+ space_id_startup = os.getenv("SPACE_ID")
253
 
254
  if space_host_startup:
255
  print(f"✅ SPACE_HOST found: {space_host_startup}")
 
257
  else:
258
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
259
 
260
+ if space_id_startup:
261
  print(f"✅ SPACE_ID found: {space_id_startup}")
262
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
263
  print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
264
  else:
265
+ print("ℹ️ SPACE_ID environment variable not found. Code link might be incorrect for submission.")
 
 
266
 
267
+ demo.launch()