rohitkhaire commited on
Commit
3c6bd71
·
verified ·
1 Parent(s): 793fd12

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +455 -250
app.py CHANGED
@@ -1,352 +1,557 @@
1
  import os
 
 
 
2
  import tempfile
 
 
 
3
  import requests
4
  import pandas as pd
5
  import gradio as gr
6
  import spaces
7
 
8
- from smolagents import (
9
- CodeAgent,
10
- LiteLLMModel,
11
- DuckDuckGoSearchTool,
12
- )
13
 
14
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
 
 
 
16
 
17
- # ----------------------------------------------------
18
- # Model
19
- # ----------------------------------------------------
20
 
21
- MODEL = LiteLLMModel(
22
- model_id="groq/llama-3.3-70b-versatile",
23
- api_key=os.getenv("GROQ_API_KEY"),
24
- temperature=0,
25
- max_tokens=512,
26
- )
27
 
 
 
28
 
29
- # ----------------------------------------------------
30
- # Agent
31
- # ----------------------------------------------------
 
 
 
 
 
 
 
32
 
33
- SYSTEM_PROMPT = """
34
- You are solving GAIA benchmark questions.
 
 
 
 
 
 
 
 
 
 
 
35
 
36
- VERY IMPORTANT RULES
37
 
38
- 1. Return ONLY the final answer.
39
- 2. Never explain.
40
- 3. Never output markdown.
41
- 4. Never output JSON.
42
- 5. Never output "Final Answer".
43
- 6. Follow the requested format EXACTLY.
44
- 7. If asked for multiple values, return exactly those values.
45
- 8. Think carefully before answering.
46
- """
47
 
 
 
48
 
49
- class GAIAAgent:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  def __init__(self):
 
 
 
 
 
 
 
 
 
52
 
53
  self.agent = CodeAgent(
54
- model=MODEL,
55
- tools=[
56
- DuckDuckGoSearchTool(),
57
- ],
58
- add_base_tools=True,
59
  additional_authorized_imports=[
60
- "requests",
 
61
  "json",
62
- "csv",
63
  "math",
64
  "statistics",
65
  "datetime",
 
 
66
  ],
67
- max_steps=8,
68
  )
69
 
70
- print("✅ GAIA Agent initialized.")
 
 
 
 
 
71
 
72
- def download_task_file(self, task_id):
 
 
 
 
 
 
73
 
74
- url = f"{DEFAULT_API_URL}/files/{task_id}"
75
 
76
- try:
77
 
78
- r = requests.get(url, timeout=60)
 
 
79
 
80
- if r.status_code != 200:
81
- return None
82
 
83
- temp_dir = tempfile.gettempdir()
 
 
84
 
85
- filename = os.path.join(temp_dir, task_id)
86
 
87
- with open(filename, "wb") as f:
88
- f.write(r.content)
 
 
 
 
 
 
 
 
 
 
 
89
 
90
- return filename
 
 
91
 
92
- except Exception:
 
 
93
 
94
- return None
 
 
 
95
 
96
- def solve(self, task_id, question):
 
 
97
 
98
- file_path = self.download_task_file(task_id)
99
 
100
- if file_path:
101
 
102
- prompt = f"""
103
- {SYSTEM_PROMPT}
104
 
105
- Question:
 
 
106
 
107
- {question}
108
 
109
- A file is attached.
 
 
 
 
 
 
 
 
 
 
110
 
111
- Its local path is:
112
 
113
- {file_path}
 
 
 
 
 
 
 
 
 
 
114
 
115
- If useful, read the file.
116
 
117
- Return ONLY the final answer.
118
- """
 
 
 
 
 
 
 
119
 
 
 
 
 
120
  else:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
 
122
- prompt = f"""
123
- {SYSTEM_PROMPT}
124
 
125
- Question:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
 
127
- {question}
128
- """
129
 
130
- try:
 
 
131
 
132
- answer = self.agent.run(prompt)
133
 
134
- if answer is None:
135
- return ""
 
 
 
136
 
137
- return str(answer).strip()
 
138
 
139
- except Exception as e:
 
 
 
 
 
 
 
 
 
140
 
141
- print(e)
 
 
 
 
 
 
 
 
 
142
 
143
- return ""
144
-
145
 
146
 
147
- @spaces.GPU
148
- def run_and_submit_all( profile: gr.OAuthProfile | None):
149
- """
150
- Fetches all questions, runs the BasicAgent on them, submits all answers,
151
- and displays the results.
152
- """
153
- # --- Determine HF Space Runtime URL and Repo URL ---
154
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
155
 
156
- if profile:
157
- username= f"{profile.username}"
158
- print(f"User logged in: {username}")
159
- else:
160
- print("User not logged in.")
161
- return "Please Login to Hugging Face with the button.", None
162
 
163
- api_url = DEFAULT_API_URL
164
- questions_url = f"{api_url}/questions"
165
- submit_url = f"{api_url}/submit"
 
 
166
 
167
- # 1. Instantiate Agent ( modify this part to create your agent)
168
  try:
169
  agent = GAIAAgent()
170
  except Exception as e:
171
- print(f"Error instantiating agent: {e}")
172
- return f"Error initializing agent: {e}", None
173
- # 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)
174
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
175
- print(agent_code)
176
-
177
- # 2. Fetch Questions
178
- print(f"Fetching questions from: {questions_url}")
179
  try:
180
- response = requests.get(questions_url, timeout=15)
181
- response.raise_for_status()
182
- questions_data = response.json()
183
- if not questions_data:
184
- print("Fetched questions list is empty.")
185
- return "Fetched questions list is empty or invalid format.", None
186
- print(f"Fetched {len(questions_data)} questions.")
187
- except requests.exceptions.RequestException as e:
188
- print(f"Error fetching questions: {e}")
189
  return f"Error fetching questions: {e}", None
190
- except requests.exceptions.JSONDecodeError as e:
191
- print(f"Error decoding JSON response from questions endpoint: {e}")
192
- print(f"Response text: {response.text[:500]}")
193
- return f"Error decoding server response for questions: {e}", None
194
- except Exception as e:
195
- print(f"An unexpected error occurred fetching questions: {e}")
196
- return f"An unexpected error occurred fetching questions: {e}", None
197
 
198
- # 3. Run your Agent
199
- results_log = []
 
 
 
200
  answers_payload = []
201
- print(f"Running agent on {len(questions_data)} questions...")
202
- for item in questions_data:
203
- task_id = item.get("task_id")
204
- question_text = item.get("question")
205
- if not task_id or question_text is None:
206
- print(f"Skipping item with missing task_id or question: {item}")
207
- continue
208
- try:
209
- submitted_answer = agent.solve(
210
- task_id,
211
- question_text,
212
- )
213
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
214
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
215
- except Exception as e:
216
- print(f"Error running agent on task {task_id}: {e}")
217
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
218
 
219
- if not answers_payload:
220
- print("Agent did not produce any answers to submit.")
221
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
222
 
223
- # 4. Prepare Submission
224
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
225
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
226
- print(status_update)
227
 
228
- # 5. Submit
229
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
230
- try:
231
- response = requests.post(submit_url, json=submission_data, timeout=60)
232
- response.raise_for_status()
233
- result_data = response.json()
234
- final_status = (
235
- f"Submission Successful!\n"
236
- f"User: {result_data.get('username')}\n"
237
- f"Overall Score: {result_data.get('score', 'N/A')}% "
238
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
239
- f"Message: {result_data.get('message', 'No message received.')}"
240
- )
241
- print("Submission successful.")
242
- results_df = pd.DataFrame(results_log)
243
- return final_status, results_df
244
- except requests.exceptions.HTTPError as e:
245
- error_detail = f"Server responded with status {e.response.status_code}."
246
  try:
247
- error_json = e.response.json()
248
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
249
- except requests.exceptions.JSONDecodeError:
250
- error_detail += f" Response: {e.response.text[:500]}"
251
- status_message = f"Submission Failed: {error_detail}"
252
- print(status_message)
253
- results_df = pd.DataFrame(results_log)
254
- return status_message, results_df
255
- except requests.exceptions.Timeout:
256
- status_message = "Submission Failed: The request timed out."
257
- print(status_message)
258
- results_df = pd.DataFrame(results_log)
259
- return status_message, results_df
260
- except requests.exceptions.RequestException as e:
261
- status_message = f"Submission Failed: Network error - {e}"
262
- print(status_message)
263
- results_df = pd.DataFrame(results_log)
264
- return status_message, results_df
265
- except Exception as e:
266
- status_message = f"An unexpected error occurred during submission: {e}"
267
- print(status_message)
268
- results_df = pd.DataFrame(results_log)
269
- return status_message, results_df
270
-
271
 
272
- def test_random_question():
273
- response = requests.get(f"{DEFAULT_API_URL}/random-question")
274
- response.raise_for_status()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
275
 
276
- question = response.json()
 
277
 
278
- agent = GAIAAgent()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
279
 
280
- answer = agent(question["question"])
281
 
282
- return (
283
- f"Task ID: {question['task_id']}\n\n"
284
- f"Question:\n{question['question']}\n\n"
285
- f"Agent Answer:\n{answer}"
286
- )
287
 
288
-
 
 
289
 
290
- # --- Build Gradio Interface using Blocks ---
291
- with gr.Blocks() as demo:
292
- gr.Markdown("# Basic Agent Evaluation Runner")
293
  gr.Markdown(
294
- """
295
- **Instructions:**
296
-
297
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
298
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
299
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
300
-
301
- ---
302
- **Disclaimers:**
303
- 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).
304
- 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.
305
- """
306
  )
307
 
308
  gr.LoginButton()
309
 
310
- run_button = gr.Button("Run Evaluation & Submit All Answers")
 
 
311
 
312
- test_button = gr.Button("Test Random Question")
313
 
314
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
315
- # Removed max_rows=10 from DataFrame constructor
316
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
317
-
318
- run_button.click(
319
- fn=run_and_submit_all,
320
- outputs=[status_output, results_table]
321
- )
322
 
323
- test_output = gr.Textbox(lines=15)
324
 
325
  test_button.click(
326
  fn=test_random_question,
327
- outputs=test_output
 
328
  )
329
 
330
- if __name__ == "__main__":
331
- print("\n" + "-"*30 + " App Starting " + "-"*30)
332
- # Check for SPACE_HOST and SPACE_ID at startup for information
333
- space_host_startup = os.getenv("SPACE_HOST")
334
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
335
-
336
- if space_host_startup:
337
- print(f"✅ SPACE_HOST found: {space_host_startup}")
338
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
339
- else:
340
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
341
-
342
- if space_id_startup: # Print repo URLs if SPACE_ID is found
343
- print(f"✅ SPACE_ID found: {space_id_startup}")
344
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
345
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
346
- else:
347
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
348
-
349
- print("-"*(60 + len(" App Starting ")) + "\n")
350
 
351
- print("Launching Gradio Interface for Basic Agent Evaluation...")
352
- demo.launch(debug=True, share=False)
 
1
  import os
2
+ import re
3
+ import json
4
+ import time
5
  import tempfile
6
+ import traceback
7
+ from typing import List, Dict, Any, Optional
8
+
9
  import requests
10
  import pandas as pd
11
  import gradio as gr
12
  import spaces
13
 
14
+ from smolagents import CodeAgent, LiteLLMModel, Tool, tool
15
+
16
+ # ------------------------------------------------------------------------------------
17
+ # CONSTANTS
18
+ # ------------------------------------------------------------------------------------
19
 
20
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
21
+ QUESTIONS_ENDPOINT = f"{DEFAULT_API_URL}/questions"
22
+ RANDOM_QUESTION_ENDPOINT = f"{DEFAULT_API_URL}/random-question"
23
+ FILES_ENDPOINT = f"{DEFAULT_API_URL}/files"
24
+ SUBMIT_ENDPOINT = f"{DEFAULT_API_URL}/submit"
25
+
26
+ REQUEST_TIMEOUT = 30
27
+ GROQ_MODEL_ID = "groq/llama-3.3-70b-versatile"
28
+
29
+ SYSTEM_PROMPT = """You are a general AI assistant solving questions from the GAIA benchmark.
30
+
31
+ STRICT OUTPUT RULES (violating these rules is a failure):
32
+ - Respond with ONLY the final answer. Nothing else.
33
+ - Do NOT use markdown formatting (no asterisks, no backticks, no headers, no bullet points).
34
+ - Do NOT include any explanation, reasoning, or commentary in your output.
35
+ - Do NOT output JSON.
36
+ - Do NOT prefix your answer with "Final Answer", "Answer:", "The answer is", or anything similar.
37
+ - Do NOT wrap the answer in quotes unless the quotes are part of the actual answer.
38
+ - If the question asks for a number, output only the number (no units unless explicitly requested, no commas unless part of the expected format).
39
+ - If the question asks for a string, output only the string, using the exact capitalization and phrasing requested.
40
+ - If the question asks for a comma separated list, output exactly that list, comma separated, with no extra text.
41
+ - If multiple values are requested, output exactly those values in the requested format, nothing more.
42
+ - Think step by step internally, use tools as needed, but NEVER reveal your reasoning, steps, or tool calls in the final output.
43
+ - Your final answer must be as concise as possible while being a fully correct, exact match to what is expected.
44
+
45
+ You have access to a Python code execution environment and a web search tool. Use them to research,
46
+ calculate, and verify facts before producing your final answer. When a local file path is given in the
47
+ task, open and read that file using Python (pandas for csv, standard file IO for txt, PyPDF2/pdfplumber-style
48
+ parsing or simple text extraction for pdf if available, and PIL for images) to extract the information you need.
49
+
50
+ Remember: the very last thing you output must be ONLY the final answer, with nothing else around it.
51
+ """
52
 
53
+ # ------------------------------------------------------------------------------------
54
+ # TOOLS
55
+ # ------------------------------------------------------------------------------------
56
 
 
 
 
57
 
58
+ @tool
59
+ def web_search(query: str) -> str:
60
+ """Performs a web search using DuckDuckGo (via DDGS) and returns the top results.
 
 
 
61
 
62
+ Args:
63
+ query: The search query string.
64
 
65
+ Returns:
66
+ A formatted string containing the top search results (title, snippet, url).
67
+ """
68
+ try:
69
+ from ddgs import DDGS
70
+ except ImportError:
71
+ try:
72
+ from duckduckgo_search import DDGS # fallback if ddgs unavailable
73
+ except ImportError:
74
+ return "Search tool unavailable: neither 'ddgs' nor 'duckduckgo_search' is installed."
75
 
76
+ try:
77
+ results = []
78
+ with DDGS() as ddgs:
79
+ for r in ddgs.text(query, max_results=5):
80
+ title = r.get("title", "")
81
+ body = r.get("body", "")
82
+ href = r.get("href", "")
83
+ results.append(f"Title: {title}\nSnippet: {body}\nURL: {href}")
84
+ if not results:
85
+ return f"No results found for query: {query}"
86
+ return "\n\n".join(results)
87
+ except Exception as e:
88
+ return f"Search failed for query '{query}': {str(e)}"
89
 
 
90
 
91
+ @tool
92
+ def read_text_file(file_path: str) -> str:
93
+ """Reads and returns the content of a plain text file.
 
 
 
 
 
 
94
 
95
+ Args:
96
+ file_path: Local path to the text file.
97
 
98
+ Returns:
99
+ The text content of the file, truncated if extremely large.
100
+ """
101
+ try:
102
+ with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
103
+ content = f.read()
104
+ if len(content) > 20000:
105
+ content = content[:20000] + "\n...[truncated]..."
106
+ return content
107
+ except Exception as e:
108
+ return f"Failed to read text file {file_path}: {str(e)}"
109
+
110
+
111
+ @tool
112
+ def read_csv_file(file_path: str) -> str:
113
+ """Reads a CSV file and returns a textual summary along with the first rows.
114
+
115
+ Args:
116
+ file_path: Local path to the CSV file.
117
+
118
+ Returns:
119
+ A string describing the CSV columns, shape, and a preview of the data.
120
+ """
121
+ try:
122
+ df = pd.read_csv(file_path)
123
+ summary = f"Columns: {list(df.columns)}\nShape: {df.shape}\n\nPreview:\n{df.head(20).to_string()}"
124
+ return summary
125
+ except Exception as e:
126
+ return f"Failed to read csv file {file_path}: {str(e)}"
127
+
128
+
129
+ @tool
130
+ def read_pdf_file(file_path: str) -> str:
131
+ """Extracts text content from a PDF file.
132
+
133
+ Args:
134
+ file_path: Local path to the PDF file.
135
+
136
+ Returns:
137
+ The extracted text content of the PDF, truncated if very large.
138
+ """
139
+ text_content = ""
140
+ try:
141
+ try:
142
+ import pypdf
143
+ reader = pypdf.PdfReader(file_path)
144
+ for page in reader.pages:
145
+ text_content += page.extract_text() or ""
146
+ except ImportError:
147
+ try:
148
+ from PyPDF2 import PdfReader
149
+ reader = PdfReader(file_path)
150
+ for page in reader.pages:
151
+ text_content += page.extract_text() or ""
152
+ except ImportError:
153
+ return "No PDF parsing library available (pypdf/PyPDF2 not installed)."
154
+ if not text_content.strip():
155
+ return "PDF appears to contain no extractable text (may be scanned/image-based)."
156
+ if len(text_content) > 20000:
157
+ text_content = text_content[:20000] + "\n...[truncated]..."
158
+ return text_content
159
+ except Exception as e:
160
+ return f"Failed to read pdf file {file_path}: {str(e)}"
161
+
162
+
163
+ @tool
164
+ def describe_image_file(file_path: str) -> str:
165
+ """Loads an image file and returns basic metadata about it (size, mode, format).
166
 
167
+ Args:
168
+ file_path: Local path to the image file.
169
+
170
+ Returns:
171
+ A string describing basic image metadata. Note: this does not perform
172
+ visual understanding; use it only to confirm the image loaded correctly.
173
+ """
174
+ try:
175
+ from PIL import Image
176
+ img = Image.open(file_path)
177
+ return f"Image loaded. Format: {img.format}, Size: {img.size}, Mode: {img.mode}"
178
+ except Exception as e:
179
+ return f"Failed to load image file {file_path}: {str(e)}"
180
+
181
+
182
+ # ------------------------------------------------------------------------------------
183
+ # AGENT
184
+ # ------------------------------------------------------------------------------------
185
+
186
+
187
+ class GAIAAgent:
188
  def __init__(self):
189
+ api_key = os.getenv("GROQ_API_KEY")
190
+ if not api_key:
191
+ print("WARNING: GROQ_API_KEY environment variable is not set.")
192
+
193
+ self.model = LiteLLMModel(
194
+ model_id=GROQ_MODEL_ID,
195
+ api_key=api_key,
196
+ temperature=0.0,
197
+ )
198
 
199
  self.agent = CodeAgent(
200
+ tools=[web_search, read_text_file, read_csv_file, read_pdf_file, describe_image_file],
201
+ model=self.model,
202
+ add_base_tools=False,
 
 
203
  additional_authorized_imports=[
204
+ "pandas",
205
+ "numpy",
206
  "json",
207
+ "re",
208
  "math",
209
  "statistics",
210
  "datetime",
211
+ "itertools",
212
+ "collections",
213
  ],
 
214
  )
215
 
216
+ @spaces.GPU
217
+ def __call__(self, question: str, file_path: Optional[str] = None) -> str:
218
+ prompt = SYSTEM_PROMPT + "\n\nQuestion:\n" + question
219
+ if file_path:
220
+ prompt += f"\n\nA file relevant to this question has been downloaded locally at: {file_path}\n"
221
+ prompt += "Use the appropriate tool (read_text_file, read_csv_file, read_pdf_file, describe_image_file) or Python code to open and inspect it."
222
 
223
+ try:
224
+ result = self.agent.run(prompt)
225
+ answer = str(result) if result is not None else ""
226
+ except Exception as e:
227
+ print(f"LLM/agent failure while answering question: {e}")
228
+ traceback.print_exc()
229
+ answer = ""
230
 
231
+ return clean_answer(answer)
232
 
 
233
 
234
+ # ------------------------------------------------------------------------------------
235
+ # OUTPUT CLEANING
236
+ # ------------------------------------------------------------------------------------
237
 
 
 
238
 
239
+ def clean_answer(raw_answer: str) -> str:
240
+ if raw_answer is None:
241
+ return ""
242
 
243
+ answer = str(raw_answer).strip()
244
 
245
+ prefixes_to_strip = [
246
+ "final answer:",
247
+ "final answer",
248
+ "answer:",
249
+ "the answer is:",
250
+ "the answer is",
251
+ "output:",
252
+ ]
253
+ lowered = answer.lower()
254
+ for prefix in prefixes_to_strip:
255
+ if lowered.startswith(prefix):
256
+ answer = answer[len(prefix):].strip()
257
+ lowered = answer.lower()
258
 
259
+ answer = re.sub(r"^```[a-zA-Z]*\n?", "", answer)
260
+ answer = re.sub(r"\n?```$", "", answer)
261
+ answer = answer.strip()
262
 
263
+ answer = re.sub(r"^\*\*(.*)\*\*$", r"\1", answer).strip()
264
+ answer = re.sub(r"^\*(.*)\*$", r"\1", answer).strip()
265
+ answer = re.sub(r"^`(.*)`$", r"\1", answer).strip()
266
 
267
+ if len(answer) >= 2 and answer[0] == '"' and answer[-1] == '"':
268
+ answer = answer[1:-1].strip()
269
+ if len(answer) >= 2 and answer[0] == "'" and answer[-1] == "'":
270
+ answer = answer[1:-1].strip()
271
 
272
+ if answer.endswith(".") and not re.match(r"^\d+\.\d*\.?$", answer):
273
+ if not (len(answer) >= 2 and answer[-2].isdigit()):
274
+ answer = answer[:-1].strip()
275
 
276
+ answer = " ".join(answer.split())
277
 
278
+ return answer
279
 
 
 
280
 
281
+ # ------------------------------------------------------------------------------------
282
+ # NETWORK HELPERS
283
+ # ------------------------------------------------------------------------------------
284
 
 
285
 
286
+ def fetch_questions() -> List[Dict[str, Any]]:
287
+ try:
288
+ resp = requests.get(QUESTIONS_ENDPOINT, timeout=REQUEST_TIMEOUT)
289
+ resp.raise_for_status()
290
+ return resp.json()
291
+ except requests.exceptions.Timeout:
292
+ raise RuntimeError("Timed out while fetching questions from the scoring API.")
293
+ except requests.exceptions.RequestException as e:
294
+ raise RuntimeError(f"Network error while fetching questions: {e}")
295
+ except json.JSONDecodeError as e:
296
+ raise RuntimeError(f"Failed to decode questions JSON: {e}")
297
 
 
298
 
299
+ def fetch_random_question() -> Dict[str, Any]:
300
+ try:
301
+ resp = requests.get(RANDOM_QUESTION_ENDPOINT, timeout=REQUEST_TIMEOUT)
302
+ resp.raise_for_status()
303
+ return resp.json()
304
+ except requests.exceptions.Timeout:
305
+ raise RuntimeError("Timed out while fetching a random question.")
306
+ except requests.exceptions.RequestException as e:
307
+ raise RuntimeError(f"Network error while fetching random question: {e}")
308
+ except json.JSONDecodeError as e:
309
+ raise RuntimeError(f"Failed to decode random question JSON: {e}")
310
 
 
311
 
312
+ def download_task_file(task_id: str) -> Optional[str]:
313
+ if not task_id:
314
+ return None
315
+ try:
316
+ url = f"{FILES_ENDPOINT}/{task_id}"
317
+ resp = requests.get(url, timeout=REQUEST_TIMEOUT)
318
+ if resp.status_code == 404:
319
+ return None
320
+ resp.raise_for_status()
321
 
322
+ content_disposition = resp.headers.get("content-disposition", "")
323
+ filename_match = re.search(r'filename="?([^";]+)"?', content_disposition)
324
+ if filename_match:
325
+ filename = filename_match.group(1)
326
  else:
327
+ content_type = resp.headers.get("content-type", "")
328
+ ext = ""
329
+ if "pdf" in content_type:
330
+ ext = ".pdf"
331
+ elif "csv" in content_type:
332
+ ext = ".csv"
333
+ elif "text" in content_type:
334
+ ext = ".txt"
335
+ elif "png" in content_type:
336
+ ext = ".png"
337
+ elif "jpeg" in content_type or "jpg" in content_type:
338
+ ext = ".jpg"
339
+ filename = f"{task_id}{ext}"
340
+
341
+ tmp_dir = tempfile.mkdtemp(prefix="gaia_task_")
342
+ local_path = os.path.join(tmp_dir, filename)
343
+ with open(local_path, "wb") as f:
344
+ f.write(resp.content)
345
+
346
+ print(f"Downloaded file for task {task_id} -> {local_path}")
347
+ return local_path
348
+ except requests.exceptions.Timeout:
349
+ print(f"Timed out while downloading file for task {task_id}.")
350
+ return None
351
+ except requests.exceptions.RequestException as e:
352
+ print(f"Network error while downloading file for task {task_id}: {e}")
353
+ return None
354
+ except Exception as e:
355
+ print(f"Unexpected error while downloading file for task {task_id}: {e}")
356
+ return None
357
 
 
 
358
 
359
+ def submit_answers(username: str, agent_code: str, answers: List[Dict[str, str]]) -> Dict[str, Any]:
360
+ payload = {
361
+ "username": username,
362
+ "agent_code": agent_code,
363
+ "answers": answers,
364
+ }
365
+ try:
366
+ resp = requests.post(SUBMIT_ENDPOINT, json=payload, timeout=120)
367
+ resp.raise_for_status()
368
+ return resp.json()
369
+ except requests.exceptions.Timeout:
370
+ raise RuntimeError("Timed out while submitting answers.")
371
+ except requests.exceptions.HTTPError as e:
372
+ detail = ""
373
+ try:
374
+ detail = resp.text
375
+ except Exception:
376
+ pass
377
+ raise RuntimeError(f"Submission failed with HTTP error: {e}. Details: {detail}")
378
+ except requests.exceptions.RequestException as e:
379
+ raise RuntimeError(f"Network error during submission: {e}")
380
+ except json.JSONDecodeError as e:
381
+ raise RuntimeError(f"Failed to decode submission response JSON: {e}")
382
 
 
 
383
 
384
+ # ------------------------------------------------------------------------------------
385
+ # GRADIO CALLBACKS
386
+ # ------------------------------------------------------------------------------------
387
 
 
388
 
389
+ def test_random_question():
390
+ try:
391
+ question_data = fetch_random_question()
392
+ except RuntimeError as e:
393
+ return f"Error: {e}", "", "", ""
394
 
395
+ task_id = question_data.get("task_id", "N/A")
396
+ question_text = question_data.get("question", "")
397
 
398
+ print(f"[TEST] Task ID: {task_id}")
399
+ print(f"[TEST] Question: {question_text}")
400
+
401
+ file_path = None
402
+ try:
403
+ file_path = download_task_file(task_id)
404
+ if file_path:
405
+ print(f"[TEST] Downloaded file: {file_path}")
406
+ except Exception as e:
407
+ print(f"[TEST] File download skipped/failed: {e}")
408
 
409
+ try:
410
+ agent = GAIAAgent()
411
+ answer = agent(question_text, file_path)
412
+ print(f"[TEST] LLM answer: {answer}")
413
+ status = "Success"
414
+ except Exception as e:
415
+ answer = ""
416
+ status = f"Agent error: {e}"
417
+ print(f"[TEST] {status}")
418
+ traceback.print_exc()
419
 
420
+ return status, str(task_id), question_text, answer
 
421
 
422
 
423
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
424
+ if profile is None:
425
+ return "Please log in to Hugging Face using the button above before running the evaluation.", None
 
 
 
 
 
426
 
427
+ username = profile.username
428
+ print(f"User logged in: {username}")
 
 
 
 
429
 
430
+ space_id = os.getenv("SPACE_ID", "")
431
+ if space_id:
432
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
433
+ else:
434
+ agent_code = "local-run/unknown-space"
435
 
 
436
  try:
437
  agent = GAIAAgent()
438
  except Exception as e:
439
+ error_msg = f"Failed to initialize agent: {e}"
440
+ print(error_msg)
441
+ traceback.print_exc()
442
+ return error_msg, None
443
+
 
 
 
444
  try:
445
+ questions = fetch_questions()
446
+ except RuntimeError as e:
 
 
 
 
 
 
 
447
  return f"Error fetching questions: {e}", None
 
 
 
 
 
 
 
448
 
449
+ if not questions:
450
+ return "No questions were returned by the scoring API.", None
451
+
452
+ print(f"Fetched {len(questions)} questions.")
453
+
454
  answers_payload = []
455
+ results_log = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
456
 
457
+ for idx, item in enumerate(questions):
458
+ task_id = item.get("task_id", f"unknown-{idx}")
459
+ question_text = item.get("question", "")
460
 
461
+ print(f"\n--- Processing task {idx + 1}/{len(questions)}: {task_id} ---")
462
+ print(f"Question: {question_text}")
 
 
463
 
464
+ file_path = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
465
  try:
466
+ file_path = download_task_file(task_id)
467
+ if file_path:
468
+ print(f"Downloaded file: {file_path}")
469
+ except Exception as e:
470
+ print(f"File download failed for task {task_id}: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
471
 
472
+ try:
473
+ answer = agent(question_text, file_path)
474
+ print(f"LLM answer for {task_id}: {answer}")
475
+ except Exception as e:
476
+ print(f"Agent failed on task {task_id}: {e}")
477
+ traceback.print_exc()
478
+ answer = ""
479
+
480
+ answers_payload.append({
481
+ "task_id": task_id,
482
+ "submitted_answer": answer,
483
+ })
484
+ results_log.append({
485
+ "Task ID": task_id,
486
+ "Question": question_text,
487
+ "Submitted Answer": answer,
488
+ })
489
 
490
+ if not answers_payload:
491
+ return "No answers were generated; nothing to submit.", pd.DataFrame(results_log)
492
 
493
+ print(f"\nSubmitting {len(answers_payload)} answers for user '{username}'...")
494
+ try:
495
+ submission_result = submit_answers(username, agent_code, answers_payload)
496
+ score = submission_result.get("score", "N/A")
497
+ correct = submission_result.get("correct_count", submission_result.get("correct", "N/A"))
498
+ total = submission_result.get("total_attempted", submission_result.get("total", len(answers_payload)))
499
+ message = submission_result.get("message", "")
500
+
501
+ status_msg = (
502
+ f"Submission successful!\n"
503
+ f"User: {username}\n"
504
+ f"Score: {score}\n"
505
+ f"Correct: {correct} / {total}\n"
506
+ f"{message}"
507
+ )
508
+ print(status_msg)
509
+ except RuntimeError as e:
510
+ status_msg = f"Submission failed: {e}"
511
+ print(status_msg)
512
 
513
+ return status_msg, pd.DataFrame(results_log)
514
 
 
 
 
 
 
515
 
516
+ # ------------------------------------------------------------------------------------
517
+ # GRADIO UI
518
+ # ------------------------------------------------------------------------------------
519
 
520
+ with gr.Blocks(title="GAIA Agent - Unit 4 Final Assignment") as demo:
521
+ gr.Markdown("# GAIA Agent Evaluation Runner")
 
522
  gr.Markdown(
523
+ "This Space runs a smolagents CodeAgent (Groq `llama-3.3-70b-versatile` via LiteLLM) "
524
+ "against the GAIA benchmark questions from the Hugging Face Agents Course Unit 4 scoring API. "
525
+ "Log in with Hugging Face, then either test a single random question or run the full evaluation "
526
+ "and submit all answers for scoring."
 
 
 
 
 
 
 
 
527
  )
528
 
529
  gr.LoginButton()
530
 
531
+ with gr.Row():
532
+ test_button = gr.Button("Test Random Question")
533
+ run_button = gr.Button("Run Evaluation & Submit All Answers", variant="primary")
534
 
535
+ status_box = gr.Textbox(label="Status", lines=6, interactive=False)
536
 
537
+ with gr.Row():
538
+ test_task_id = gr.Textbox(label="Task ID", interactive=False)
539
+ test_question = gr.Textbox(label="Question", lines=4, interactive=False)
540
+ test_answer = gr.Textbox(label="Answer", lines=2, interactive=False)
 
 
 
 
541
 
542
+ results_df = gr.Dataframe(label="Results", wrap=True)
543
 
544
  test_button.click(
545
  fn=test_random_question,
546
+ inputs=[],
547
+ outputs=[status_box, test_task_id, test_question, test_answer],
548
  )
549
 
550
+ run_button.click(
551
+ fn=run_and_submit_all,
552
+ inputs=[],
553
+ outputs=[status_box, results_df],
554
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
555
 
556
+ if __name__ == "__main__":
557
+ demo.launch(debug=True)