avi080704 commited on
Commit
d68fc9e
·
verified ·
1 Parent(s): 3105460

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +124 -333
app.py CHANGED
@@ -2,384 +2,195 @@ import os
2
  import gradio as gr
3
  import requests
4
  import pandas as pd
5
- import re
6
- import traceback
7
 
8
- # --- Constants ---
9
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
-
11
- from smolagents import CodeAgent, tool, VisitWebpageTool, DuckDuckGoSearchTool, LiteLLMModel
12
-
13
-
14
- @tool
15
- def download_task_file(task_id: str) -> str:
16
- """
17
- Downloads the file attached to a GAIA task and returns its text content.
18
- ALWAYS call this first if the question mentions any file, attachment,
19
- spreadsheet, audio, PDF, image, or code file.
20
-
21
- Args:
22
- task_id: The task_id string from [task_id: ...] at the top of the question.
23
-
24
- Returns:
25
- The text content of the file, or a descriptive note if unreadable.
26
- """
27
- try:
28
- url = f"{DEFAULT_API_URL}/files/{task_id}"
29
- resp = requests.get(url, timeout=30)
30
- if resp.status_code == 404:
31
- return "No file is associated with this task."
32
- resp.raise_for_status()
33
- content_type = resp.headers.get("Content-Type", "")
34
- disposition = resp.headers.get("Content-Disposition", "")
35
- filename = ""
36
- if "filename=" in disposition:
37
- filename = disposition.split("filename=")[-1].strip().strip('"')
38
- ext = filename.rsplit(".", 1)[-1].lower() if "." in filename else ""
39
-
40
- if "text" in content_type or ext in ("txt", "csv", "tsv", "md", "py", "js", "json", "xml", "yaml", "yml", "html"):
41
- return f"[File: {filename}]\n" + resp.text[:8000]
42
-
43
- if ext in ("xlsx", "xls"):
44
- try:
45
- import io, openpyxl
46
- wb = openpyxl.load_workbook(io.BytesIO(resp.content), data_only=True)
47
- lines = []
48
- for sheet in wb.sheetnames:
49
- ws = wb[sheet]
50
- lines.append(f"=== Sheet: {sheet} ===")
51
- for row in ws.iter_rows(values_only=True):
52
- lines.append("\t".join(str(c) if c is not None else "" for c in row))
53
- return f"[File: {filename}]\n" + "\n".join(lines)[:8000]
54
- except Exception as e:
55
- return f"Could not parse Excel file {filename}: {e}"
56
-
57
- if "pdf" in content_type or ext == "pdf":
58
- try:
59
- import io, pdfminer.high_level
60
- text = pdfminer.high_level.extract_text(io.BytesIO(resp.content))
61
- return f"[File: {filename}]\n" + (text or "No extractable text in PDF.")[:8000]
62
- except Exception as e:
63
- return f"Could not parse PDF {filename}: {e}"
64
-
65
- if ext in ("mp3", "wav", "m4a", "flac", "ogg") or "audio" in content_type:
66
- return (
67
- f"[Audio file: {filename}]\n"
68
- "This is an audio file — transcription not available. "
69
- "Search the web for the answer based on the question context."
70
- )
71
-
72
- if ext in ("png", "jpg", "jpeg", "gif", "bmp", "webp") or "image" in content_type:
73
- return (
74
- f"[Image file: {filename}]\n"
75
- "This is an image file — visual reading not available. "
76
- "Search the web for the answer based on the question context."
77
- )
78
-
79
- try:
80
- return f"[File: {filename}]\n" + resp.content.decode("utf-8")[:8000]
81
- except Exception:
82
- return f"Binary file ({filename}, type={content_type}) — cannot extract text."
83
- except Exception as e:
84
- return f"Error downloading file for task {task_id}: {e}"
85
-
86
-
87
- @tool
88
- def calculate(expression: str) -> str:
89
- """
90
- Safely evaluates a mathematical expression and returns the result.
91
- Use this for ANY arithmetic, counting, percentages, or numeric calculation.
92
 
93
- Args:
94
- expression: A valid Python math expression.
95
- Examples: "2 ** 10", "round(100 * 1.07 ** 3, 2)", "sum([1,2,3])"
96
-
97
- Returns:
98
- The numeric result as a string, or an error message.
99
- """
100
- try:
101
- import math as _math
102
- allowed = {k: v for k, v in _math.__dict__.items() if not k.startswith("_")}
103
- allowed.update({"round": round, "abs": abs, "sum": sum, "min": min,
104
- "max": max, "len": len, "sorted": sorted,
105
- "list": list, "range": range})
106
- result = eval(expression, {"__builtins__": {}}, allowed)
107
- return str(result)
108
- except Exception as e:
109
- return f"Calculation error: {e}"
110
 
 
 
 
 
 
111
 
112
- @tool
113
- def search_wikipedia(query: str) -> str:
114
- """
115
- Searches Wikipedia and returns the full page text.
116
- Best for: people, places, history, science, albums, films, sports stats.
117
 
118
- Args:
119
- query: The Wikipedia article title or search phrase.
 
 
 
 
 
 
120
 
121
- Returns:
122
- Wikipedia page text (up to 6000 chars).
123
- """
124
- try:
125
- search_url = "https://en.wikipedia.org/w/api.php"
126
- params = {"action": "query", "list": "search", "srsearch": query,
127
- "format": "json", "srlimit": 1}
128
- resp = requests.get(search_url, params=params, timeout=10)
129
- results = resp.json().get("query", {}).get("search", [])
130
- if not results:
131
- return f"No Wikipedia results for: {query}"
132
- title = results[0]["title"]
133
- page_params = {"action": "query", "titles": title, "prop": "extracts",
134
- "exintro": False, "explaintext": True, "format": "json"}
135
- page_resp = requests.get(search_url, params=page_params, timeout=10)
136
- pages = page_resp.json().get("query", {}).get("pages", {})
137
- page = next(iter(pages.values()))
138
- text = page.get("extract", "")
139
- return f"=== Wikipedia: {title} ===\n{text[:6000]}"
140
- except Exception as e:
141
- return f"Wikipedia search error: {e}"
142
 
 
143
 
144
- def _make_agent(gemini_api_key: str) -> CodeAgent:
145
- model = LiteLLMModel(
146
- model_id="gemini/gemini-2.5-flash",
147
- api_key=gemini_api_key,
148
- )
149
- return CodeAgent(
150
- tools=[
151
- DuckDuckGoSearchTool(),
152
- VisitWebpageTool(),
153
- download_task_file,
154
- calculate,
155
- search_wikipedia,
156
- ],
157
- model=model,
158
- max_steps=15,
159
- )
160
 
 
 
 
 
 
 
161
 
162
- class BasicAgent:
163
- def __init__(self):
164
- gemini_api_key = os.environ.get("GEMINI_API_KEY")
165
- if not gemini_api_key:
166
- raise RuntimeError(
167
- "GEMINI_API_KEY environment variable is not set. "
168
- "Go to Space Settings → Variables and secrets → add GEMINI_API_KEY."
169
- )
170
- print("GEMINI_API_KEY present: True")
171
 
172
  try:
173
- print("Initializing agent with gemini-2.5-flash...")
174
- self.agent = _make_agent(gemini_api_key)
175
- # Quick smoke test
176
- test = self.agent.run("Reply with just the number 42.")
177
- print(f"✅ Gemini agent OK → {str(test)[:30]}")
178
- except Exception as e:
179
- raise RuntimeError(f"Failed to initialize Gemini agent: {e}")
180
-
181
- print("BasicAgent initialized with model: gemini/gemini-2.5-flash")
182
 
183
- def __call__(self, question: str) -> str:
184
- print(f"Agent received question (first 50 chars): {question[:50]}...")
185
-
186
- task_id = ""
187
- task_id_match = re.match(r"\[task_id:\s*([^\]]+)\]", question)
188
- if task_id_match:
189
- task_id = task_id_match.group(1).strip()
190
-
191
- prompt = f"""You are an expert GAIA benchmark solving agent.
192
-
193
- task_id: {task_id}
194
-
195
- STRICT OUTPUT RULES:
196
- - Output ONLY the bare final answer. Nothing else.
197
- - No explanation. No "The answer is". No "FINAL ANSWER". No markdown.
198
- - Just the raw answer: a number, a name, a date, a word, or comma-separated values.
199
- - Never output an empty string — always give your best answer.
200
-
201
- STRATEGY:
202
- 1. Read the question carefully.
203
- 2. If it mentions a file, spreadsheet, audio, image → call download_task_file("{task_id}") FIRST.
204
- 3. For encyclopedia/factual questions → call search_wikipedia first.
205
- 4. For web research → DuckDuckGo search, then visit URLs with VisitWebpageTool.
206
- 5. For math/counting → use calculate tool.
207
- 6. For YouTube videos → search web for the video title + transcript/description.
208
- 7. For reversed text → decode it yourself before answering.
209
- 8. Think carefully, then output ONLY the final answer.
210
-
211
- ANSWER FORMAT EXAMPLES:
212
- - Count → "3"
213
- - Name → "Marie Curie"
214
- - Yes/No → "Yes"
215
- - List → "apple, banana, cherry"
216
- - Currency → "$12345.67"
217
- - Chess move → "Qd5"
218
-
219
- Question:
220
- {question}
221
 
222
- Output ONLY the final answer:"""
223
 
224
- try:
225
- response = self.agent.run(prompt)
226
- final_answer = str(response).strip()
227
- for prefix in ["FINAL ANSWER:", "FINAL ANSWER", "Answer:", "The answer is:", "Result:"]:
228
- if final_answer.upper().startswith(prefix.upper()):
229
- final_answer = final_answer[len(prefix):].strip()
230
- print(f"Agent returning answer: {final_answer}")
231
- return final_answer
232
  except Exception as e:
233
- err_msg = f"ERROR: {type(e).__name__}: {str(e)[:200]}"
234
- print(f"Agent error: {traceback.format_exc()}")
235
- return err_msg
236
-
237
 
 
 
 
238
  def run_and_submit_all(profile: gr.OAuthProfile | None):
239
- """
240
- Fetches all questions, runs the BasicAgent on them, submits all answers,
241
- and displays the results.
242
- """
243
  space_id = os.getenv("SPACE_ID")
244
 
245
  if profile:
246
  username = f"{profile.username}"
247
  print(f"User logged in: {username}")
248
  else:
249
- print("User not logged in.")
250
- return "Please Login to Hugging Face with the button.", None
251
 
252
  api_url = DEFAULT_API_URL
253
  questions_url = f"{api_url}/questions"
254
  submit_url = f"{api_url}/submit"
255
 
256
- # 1. Instantiate Agent
257
  try:
258
  agent = BasicAgent()
259
  except Exception as e:
260
- print(f"Error instantiating agent: {e}")
261
  return f"Error initializing agent: {e}", None
262
 
263
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
264
- print(agent_code)
265
 
266
- # 2. Fetch Questions
267
- print(f"Fetching questions from: {questions_url}")
268
  try:
269
- response = requests.get(questions_url, timeout=15)
270
  response.raise_for_status()
271
  questions_data = response.json()
272
- if not questions_data:
273
- print("Fetched questions list is empty.")
274
- return "Fetched questions list is empty or invalid format.", None
275
- print(f"Fetched {len(questions_data)} questions.")
276
- except requests.exceptions.RequestException as e:
277
- print(f"Error fetching questions: {e}")
278
- return f"Error fetching questions: {e}", None
279
- except requests.exceptions.JSONDecodeError as e:
280
- print(f"Error decoding JSON response from questions endpoint: {e}")
281
- print(f"Response text: {response.text[:500]}")
282
- return f"Error decoding server response for questions: {e}", None
283
  except Exception as e:
284
- print(f"An unexpected error occurred fetching questions: {e}")
285
- return f"An unexpected error occurred fetching questions: {e}", None
286
 
287
- # 3. Run your Agent
288
  results_log = []
289
  answers_payload = []
290
- print(f"Running agent on {len(questions_data)} questions...")
291
  for item in questions_data:
 
292
  task_id = item.get("task_id")
293
  question_text = item.get("question")
294
- if not task_id or question_text is None:
295
- print(f"Skipping item with missing task_id or question: {item}")
296
- continue
297
  try:
298
- augmented_question = f"[task_id: {task_id}]\n{question_text}"
299
- submitted_answer = agent(augmented_question)
300
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
301
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
 
 
 
 
 
 
 
 
 
 
302
  except Exception as e:
303
- print(f"Error running agent on task {task_id}: {e}")
304
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
305
 
306
- if not answers_payload:
307
- print("Agent did not produce any answers to submit.")
308
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
 
 
309
 
310
- # 4. Prepare Submission
311
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
312
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
313
- print(status_update)
 
 
314
 
315
- # 5. Submit
316
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
317
  try:
318
- response = requests.post(submit_url, json=submission_data, timeout=60)
 
 
 
 
 
 
319
  response.raise_for_status()
 
320
  result_data = response.json()
 
321
  final_status = (
322
  f"Submission Successful!\n"
323
  f"User: {result_data.get('username')}\n"
324
- f"Overall Score: {result_data.get('score', 'N/A')}% "
325
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
326
- f"Message: {result_data.get('message', 'No message received.')}"
 
327
  )
328
- print("Submission successful.")
329
- results_df = pd.DataFrame(results_log)
330
- return final_status, results_df
331
- except requests.exceptions.HTTPError as e:
332
- error_detail = f"Server responded with status {e.response.status_code}."
333
- try:
334
- error_json = e.response.json()
335
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
336
- except requests.exceptions.JSONDecodeError:
337
- error_detail += f" Response: {e.response.text[:500]}"
338
- status_message = f"Submission Failed: {error_detail}"
339
- print(status_message)
340
- results_df = pd.DataFrame(results_log)
341
- return status_message, results_df
342
- except requests.exceptions.Timeout:
343
- status_message = "Submission Failed: The request timed out."
344
- print(status_message)
345
- results_df = pd.DataFrame(results_log)
346
- return status_message, results_df
347
- except requests.exceptions.RequestException as e:
348
- status_message = f"Submission Failed: Network error - {e}"
349
- print(status_message)
350
- results_df = pd.DataFrame(results_log)
351
- return status_message, results_df
352
  except Exception as e:
353
- status_message = f"An unexpected error occurred during submission: {e}"
354
- print(status_message)
355
- results_df = pd.DataFrame(results_log)
356
- return status_message, results_df
357
 
 
 
 
 
358
 
359
- # --- Build Gradio Interface using Blocks ---
 
 
360
  with gr.Blocks() as demo:
361
- gr.Markdown("# Basic Agent Evaluation Runner")
362
- gr.Markdown(
363
- """
364
- **Instructions:**
365
-
366
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
367
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
368
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
369
-
370
- ---
371
- **Disclaimers:**
372
- 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).
373
- 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.
374
- """
375
- )
376
 
377
  gr.LoginButton()
378
 
379
- run_button = gr.Button("Run Evaluation & Submit All Answers")
380
 
381
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
382
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
 
 
 
 
 
 
 
383
 
384
  run_button.click(
385
  fn=run_and_submit_all,
@@ -387,24 +198,4 @@ with gr.Blocks() as demo:
387
  )
388
 
389
  if __name__ == "__main__":
390
- print("\n" + "-"*30 + " App Starting " + "-"*30)
391
- space_host_startup = os.getenv("SPACE_HOST")
392
- space_id_startup = os.getenv("SPACE_ID")
393
-
394
- if space_host_startup:
395
- print(f"✅ SPACE_HOST found: {space_host_startup}")
396
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
397
- else:
398
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
399
-
400
- if space_id_startup:
401
- print(f"✅ SPACE_ID found: {space_id_startup}")
402
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
403
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
404
- else:
405
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
406
-
407
- print("-"*(60 + len(" App Starting ")) + "\n")
408
-
409
- print("Launching Gradio Interface for Basic Agent Evaluation...")
410
- demo.launch(debug=True, share=False)
 
2
  import gradio as gr
3
  import requests
4
  import pandas as pd
 
 
5
 
6
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
+ # -----------------------------
9
+ # Constants
10
+ # -----------------------------
11
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
+ # -----------------------------
14
+ # Build Agent
15
+ # -----------------------------
16
+ class BasicAgent:
17
+ def __init__(self):
18
 
19
+ # Uses your HF token automatically from Space secrets
20
+ model = HfApiModel(
21
+ model_id="Qwen/Qwen2.5-72B-Instruct"
22
+ )
 
23
 
24
+ self.agent = CodeAgent(
25
+ tools=[
26
+ DuckDuckGoSearchTool()
27
+ ],
28
+ model=model,
29
+ max_steps=6,
30
+ verbosity_level=1
31
+ )
32
 
33
+ print("HF Agent initialized.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
+ def __call__(self, question: str) -> str:
36
 
37
+ prompt = f"""
38
+ You are a highly accurate GAIA benchmark solving agent.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
+ Rules:
41
+ - Think carefully step by step.
42
+ - Use web search when needed.
43
+ - Return ONLY the final answer.
44
+ - Keep the answer concise.
45
+ - Do not explain reasoning unless asked.
46
 
47
+ Question:
48
+ {question}
49
+ """
 
 
 
 
 
 
50
 
51
  try:
52
+ answer = self.agent.run(prompt)
 
 
 
 
 
 
 
 
53
 
54
+ if answer is None:
55
+ return "I could not determine the answer."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
+ return str(answer).strip()
58
 
 
 
 
 
 
 
 
 
59
  except Exception as e:
60
+ print(f"Agent error: {e}")
61
+ return f"Error: {e}"
 
 
62
 
63
+ # -----------------------------
64
+ # Main Evaluation Function
65
+ # -----------------------------
66
  def run_and_submit_all(profile: gr.OAuthProfile | None):
67
+
 
 
 
68
  space_id = os.getenv("SPACE_ID")
69
 
70
  if profile:
71
  username = f"{profile.username}"
72
  print(f"User logged in: {username}")
73
  else:
74
+ return "Please login to Hugging Face.", None
 
75
 
76
  api_url = DEFAULT_API_URL
77
  questions_url = f"{api_url}/questions"
78
  submit_url = f"{api_url}/submit"
79
 
80
+ # Initialize Agent
81
  try:
82
  agent = BasicAgent()
83
  except Exception as e:
 
84
  return f"Error initializing agent: {e}", None
85
 
86
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
 
87
 
88
+ # Fetch Questions
 
89
  try:
90
+ response = requests.get(questions_url, timeout=30)
91
  response.raise_for_status()
92
  questions_data = response.json()
93
+
 
 
 
 
 
 
 
 
 
 
94
  except Exception as e:
95
+ return f"Error fetching questions: {e}", None
 
96
 
97
+ # Run Agent
98
  results_log = []
99
  answers_payload = []
100
+
101
  for item in questions_data:
102
+
103
  task_id = item.get("task_id")
104
  question_text = item.get("question")
105
+
 
 
106
  try:
107
+
108
+ submitted_answer = agent(question_text)
109
+
110
+ answers_payload.append({
111
+ "task_id": task_id,
112
+ "submitted_answer": submitted_answer
113
+ })
114
+
115
+ results_log.append({
116
+ "Task ID": task_id,
117
+ "Question": question_text,
118
+ "Submitted Answer": submitted_answer
119
+ })
120
+
121
  except Exception as e:
 
 
122
 
123
+ results_log.append({
124
+ "Task ID": task_id,
125
+ "Question": question_text,
126
+ "Submitted Answer": f"ERROR: {e}"
127
+ })
128
 
129
+ # Submit
130
+ submission_data = {
131
+ "username": username.strip(),
132
+ "agent_code": agent_code,
133
+ "answers": answers_payload
134
+ }
135
 
 
 
136
  try:
137
+
138
+ response = requests.post(
139
+ submit_url,
140
+ json=submission_data,
141
+ timeout=120
142
+ )
143
+
144
  response.raise_for_status()
145
+
146
  result_data = response.json()
147
+
148
  final_status = (
149
  f"Submission Successful!\n"
150
  f"User: {result_data.get('username')}\n"
151
+ f"Overall Score: {result_data.get('score', 'N/A')}%\n"
152
+ f"Correct: {result_data.get('correct_count', '?')}/"
153
+ f"{result_data.get('total_attempted', '?')}\n"
154
+ f"Message: {result_data.get('message', '')}"
155
  )
156
+
157
+ return final_status, pd.DataFrame(results_log)
158
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159
  except Exception as e:
 
 
 
 
160
 
161
+ return (
162
+ f"Submission failed: {e}",
163
+ pd.DataFrame(results_log)
164
+ )
165
 
166
+ # -----------------------------
167
+ # Gradio UI
168
+ # -----------------------------
169
  with gr.Blocks() as demo:
170
+
171
+ gr.Markdown("# Hugging Face Agents Course - Final Assignment")
172
+
173
+ gr.Markdown("""
174
+ This agent uses:
175
+ - Hugging Face Inference API
176
+ - smolagents
177
+ - DuckDuckGo web search
178
+ - Qwen2.5-72B-Instruct
179
+ """)
 
 
 
 
 
180
 
181
  gr.LoginButton()
182
 
183
+ run_button = gr.Button("Run Evaluation & Submit")
184
 
185
+ status_output = gr.Textbox(
186
+ label="Submission Result",
187
+ lines=6
188
+ )
189
+
190
+ results_table = gr.DataFrame(
191
+ label="Agent Answers",
192
+ wrap=True
193
+ )
194
 
195
  run_button.click(
196
  fn=run_and_submit_all,
 
198
  )
199
 
200
  if __name__ == "__main__":
201
+ demo.launch(debug=True)