Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,48 +1,37 @@
|
|
| 1 |
import os
|
| 2 |
-
import
|
| 3 |
import requests
|
|
|
|
| 4 |
import pandas as pd
|
| 5 |
-
import gradio as gr
|
| 6 |
-
|
| 7 |
-
from smolagents import CodeAgent, ApiModel, tool
|
| 8 |
-
from smolagents.tools import DuckDuckGoSearchTool
|
| 9 |
|
| 10 |
-
#
|
| 11 |
-
# Constants
|
| 12 |
-
# ─────────────────────────────────────────────────────────────
|
| 13 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
# ─────────────────────────────────────────────────────────────
|
| 17 |
-
# Custom Tools
|
| 18 |
-
# ─────────────────────────────────────────────────────────────
|
| 19 |
|
| 20 |
@tool
|
| 21 |
def visit_webpage(url: str) -> str:
|
| 22 |
"""
|
| 23 |
Fetches and returns the visible text content of any webpage.
|
| 24 |
-
Use this to read
|
| 25 |
-
Always use this after a web search to get full details from a URL.
|
| 26 |
|
| 27 |
Args:
|
| 28 |
url: The full URL to fetch (must start with http:// or https://)
|
| 29 |
|
| 30 |
Returns:
|
| 31 |
-
The visible text of the page, truncated to
|
| 32 |
"""
|
| 33 |
try:
|
| 34 |
-
headers = {
|
| 35 |
-
"User-Agent": (
|
| 36 |
-
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
| 37 |
-
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
| 38 |
-
"Chrome/120.0.0.0 Safari/537.36"
|
| 39 |
-
)
|
| 40 |
-
}
|
| 41 |
resp = requests.get(url, headers=headers, timeout=15)
|
| 42 |
resp.raise_for_status()
|
| 43 |
-
|
| 44 |
-
# Strip HTML tags
|
| 45 |
-
clean = re.sub(r"<style[^>]*>.*?</style>", " ", content, flags=re.DOTALL)
|
| 46 |
clean = re.sub(r"<script[^>]*>.*?</script>", " ", clean, flags=re.DOTALL)
|
| 47 |
clean = re.sub(r"<[^>]+>", " ", clean)
|
| 48 |
clean = re.sub(r"\s+", " ", clean).strip()
|
|
@@ -55,14 +44,13 @@ def visit_webpage(url: str) -> str:
|
|
| 55 |
def download_task_file(task_id: str) -> str:
|
| 56 |
"""
|
| 57 |
Downloads the file attached to a GAIA task and returns its text content.
|
| 58 |
-
Use this whenever the question mentions or implies an attached file
|
| 59 |
-
(e.g. a spreadsheet, PDF, image, audio, CSV, etc.)
|
| 60 |
|
| 61 |
Args:
|
| 62 |
-
task_id: The task_id string from the [task_id: ...]
|
| 63 |
|
| 64 |
Returns:
|
| 65 |
-
The text content
|
| 66 |
"""
|
| 67 |
try:
|
| 68 |
url = f"{DEFAULT_API_URL}/files/{task_id}"
|
|
@@ -70,34 +58,18 @@ def download_task_file(task_id: str) -> str:
|
|
| 70 |
if resp.status_code == 404:
|
| 71 |
return "No file is associated with this task."
|
| 72 |
resp.raise_for_status()
|
| 73 |
-
|
| 74 |
content_type = resp.headers.get("Content-Type", "")
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
# Detect filename from headers
|
| 78 |
filename = ""
|
| 79 |
-
if "filename=" in
|
| 80 |
-
filename =
|
| 81 |
-
|
| 82 |
ext = filename.rsplit(".", 1)[-1].lower() if "." in filename else ""
|
| 83 |
|
| 84 |
-
|
| 85 |
-
if "text" in content_type or ext in ("txt", "csv", "tsv", "md"):
|
| 86 |
-
return resp.text[:6000]
|
| 87 |
-
|
| 88 |
-
# JSON
|
| 89 |
-
if "json" in content_type or ext == "json":
|
| 90 |
-
return resp.text[:6000]
|
| 91 |
-
|
| 92 |
-
# Code files
|
| 93 |
-
if ext in ("py", "js", "html", "xml", "yaml", "yml"):
|
| 94 |
return resp.text[:6000]
|
| 95 |
-
|
| 96 |
-
# Excel / spreadsheet
|
| 97 |
if ext in ("xlsx", "xls"):
|
| 98 |
try:
|
| 99 |
-
import io
|
| 100 |
-
import openpyxl
|
| 101 |
wb = openpyxl.load_workbook(io.BytesIO(resp.content), data_only=True)
|
| 102 |
lines = []
|
| 103 |
for sheet in wb.sheetnames:
|
|
@@ -107,40 +79,22 @@ def download_task_file(task_id: str) -> str:
|
|
| 107 |
lines.append("\t".join(str(c) if c is not None else "" for c in row))
|
| 108 |
return "\n".join(lines)[:6000]
|
| 109 |
except Exception as e:
|
| 110 |
-
return f"Could not parse Excel
|
| 111 |
-
|
| 112 |
-
# PDF
|
| 113 |
if "pdf" in content_type or ext == "pdf":
|
| 114 |
try:
|
| 115 |
-
import io
|
| 116 |
-
import pdfminer.high_level
|
| 117 |
text = pdfminer.high_level.extract_text(io.BytesIO(resp.content))
|
| 118 |
-
return (text or "
|
| 119 |
except Exception as e:
|
| 120 |
return f"Could not parse PDF: {e}"
|
| 121 |
-
|
| 122 |
-
# Audio
|
| 123 |
if ext in ("mp3", "wav", "m4a", "flac", "ogg") or "audio" in content_type:
|
| 124 |
-
return (
|
| 125 |
-
f"Audio file detected ({filename or content_type}). "
|
| 126 |
-
"Audio transcription is not available in this environment. "
|
| 127 |
-
"Try to answer based on the question context alone."
|
| 128 |
-
)
|
| 129 |
-
|
| 130 |
-
# Image
|
| 131 |
if ext in ("png", "jpg", "jpeg", "gif", "bmp", "webp") or "image" in content_type:
|
| 132 |
-
return (
|
| 133 |
-
f"Image file detected ({filename or content_type}). "
|
| 134 |
-
"Image content cannot be read as text here. "
|
| 135 |
-
"Try to answer based on the question context alone."
|
| 136 |
-
)
|
| 137 |
-
|
| 138 |
-
# Fallback: try UTF-8 decode
|
| 139 |
try:
|
| 140 |
return resp.content.decode("utf-8")[:6000]
|
| 141 |
except Exception:
|
| 142 |
-
return f"Binary file ({filename
|
| 143 |
-
|
| 144 |
except Exception as e:
|
| 145 |
return f"Error downloading file for task {task_id}: {e}"
|
| 146 |
|
|
@@ -149,69 +103,28 @@ def download_task_file(task_id: str) -> str:
|
|
| 149 |
def calculate(expression: str) -> str:
|
| 150 |
"""
|
| 151 |
Safely evaluates a mathematical expression and returns the result.
|
| 152 |
-
Use this for arithmetic, percentages,
|
| 153 |
|
| 154 |
Args:
|
| 155 |
-
expression: A valid Python math expression.
|
| 156 |
-
Examples: "2 ** 10", "round(
|
| 157 |
|
| 158 |
Returns:
|
| 159 |
The numeric result as a string, or an error message.
|
| 160 |
"""
|
| 161 |
try:
|
| 162 |
import math as _math
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
result = eval(expression, {"__builtins__": {}}, allowed_names) # noqa: S307
|
| 168 |
return str(result)
|
| 169 |
except Exception as e:
|
| 170 |
-
return f"Calculation error
|
| 171 |
-
|
| 172 |
|
| 173 |
-
# ─────────────────────────────────────────────────────────────
|
| 174 |
-
# System Prompt
|
| 175 |
-
# ─────────────────────────────────────────────────────────────
|
| 176 |
-
|
| 177 |
-
SYSTEM_PROMPT = """You are an expert AI assistant specialised in solving GAIA benchmark questions.
|
| 178 |
-
|
| 179 |
-
GAIA questions require multi-step reasoning, web search, reading webpages, file analysis, and precise calculation.
|
| 180 |
-
|
| 181 |
-
STRICT OUTPUT RULES — never break these:
|
| 182 |
-
1. Your FINAL output must be ONLY the bare answer itself.
|
| 183 |
-
2. No explanations. No reasoning. No preamble. No "The answer is...".
|
| 184 |
-
3. No markdown. No bullet points. No code blocks.
|
| 185 |
-
4. NEVER include the words "FINAL ANSWER" anywhere.
|
| 186 |
-
5. Match the exact expected format:
|
| 187 |
-
- If the answer is a number → output just the number (e.g. "42" or "3.14")
|
| 188 |
-
- If the answer is a name → output just the name (e.g. "Marie Curie")
|
| 189 |
-
- If the answer is a list → output comma-separated values (e.g. "apple, banana, cherry")
|
| 190 |
-
- If the answer is a date → output just the date in the format implied by the question
|
| 191 |
-
6. Never output an empty string — always give your best answer.
|
| 192 |
-
|
| 193 |
-
STRATEGY (follow these steps in order):
|
| 194 |
-
1. Read the question carefully. Note the [task_id: ...] at the top.
|
| 195 |
-
2. If the question references a file, immediately call download_task_file(task_id).
|
| 196 |
-
3. Search the web using DuckDuckGoSearchTool for key facts.
|
| 197 |
-
4. Call visit_webpage on the most relevant URLs to get full page content.
|
| 198 |
-
5. Use calculate for any arithmetic needed.
|
| 199 |
-
6. Synthesise all gathered information.
|
| 200 |
-
7. Output ONLY the final answer — nothing else.
|
| 201 |
-
"""
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
# ─────────────────────────────────────────────────────────────
|
| 205 |
-
# Agent Definition
|
| 206 |
-
# ─────────────────────────────────────────────────────────────
|
| 207 |
|
| 208 |
class BasicAgent:
|
| 209 |
-
|
| 210 |
def __init__(self):
|
| 211 |
-
model = ApiModel(
|
| 212 |
-
model_id="Qwen/Qwen2.5-72B-Instruct",
|
| 213 |
-
)
|
| 214 |
-
|
| 215 |
self.agent = CodeAgent(
|
| 216 |
tools=[
|
| 217 |
DuckDuckGoSearchTool(),
|
|
@@ -219,58 +132,52 @@ class BasicAgent:
|
|
| 219 |
download_task_file,
|
| 220 |
calculate,
|
| 221 |
],
|
| 222 |
-
model=
|
| 223 |
max_steps=10,
|
| 224 |
-
verbosity_level=1,
|
| 225 |
)
|
| 226 |
-
|
| 227 |
-
print("BasicAgent initialized with Qwen2.5-72B + web search + file reader + calculator.")
|
| 228 |
|
| 229 |
def __call__(self, question: str) -> str:
|
| 230 |
-
print(f"
|
| 231 |
-
print(f"Question: {question[:300]}")
|
| 232 |
-
print(f"{'='*60}")
|
| 233 |
|
| 234 |
-
prompt = f"""
|
| 235 |
|
| 236 |
-
|
| 237 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
|
| 239 |
-
|
|
|
|
| 240 |
|
| 241 |
try:
|
| 242 |
response = self.agent.run(prompt)
|
| 243 |
final_answer = str(response).strip()
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
for prefix in [
|
| 247 |
-
"FINAL ANSWER:", "FINAL ANSWER", "Answer:", "answer:",
|
| 248 |
-
"The answer is:", "The answer is"
|
| 249 |
-
]:
|
| 250 |
if final_answer.upper().startswith(prefix.upper()):
|
| 251 |
final_answer = final_answer[len(prefix):].strip()
|
| 252 |
-
|
| 253 |
-
print(f"\n✅ Final Answer: {final_answer}")
|
| 254 |
return final_answer
|
| 255 |
-
|
| 256 |
except Exception as e:
|
| 257 |
-
print(f"
|
| 258 |
return ""
|
| 259 |
|
| 260 |
|
| 261 |
-
|
| 262 |
-
# Submission Logic (from template — do not modify)
|
| 263 |
-
# ─────────────────────────────────────────────────────────────
|
| 264 |
-
|
| 265 |
-
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 266 |
"""
|
| 267 |
-
Fetches all questions, runs the BasicAgent on them,
|
| 268 |
-
|
| 269 |
"""
|
| 270 |
-
|
|
|
|
| 271 |
|
| 272 |
if profile:
|
| 273 |
-
username
|
| 274 |
print(f"User logged in: {username}")
|
| 275 |
else:
|
| 276 |
print("User not logged in.")
|
|
@@ -280,84 +187,68 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 280 |
questions_url = f"{api_url}/questions"
|
| 281 |
submit_url = f"{api_url}/submit"
|
| 282 |
|
| 283 |
-
# Instantiate Agent
|
| 284 |
try:
|
| 285 |
agent = BasicAgent()
|
| 286 |
except Exception as e:
|
| 287 |
print(f"Error instantiating agent: {e}")
|
| 288 |
return f"Error initializing agent: {e}", None
|
| 289 |
-
|
| 290 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 291 |
print(agent_code)
|
| 292 |
|
| 293 |
-
# Fetch Questions
|
| 294 |
print(f"Fetching questions from: {questions_url}")
|
| 295 |
try:
|
| 296 |
response = requests.get(questions_url, timeout=15)
|
| 297 |
response.raise_for_status()
|
| 298 |
questions_data = response.json()
|
| 299 |
if not questions_data:
|
| 300 |
-
|
| 301 |
-
|
| 302 |
print(f"Fetched {len(questions_data)} questions.")
|
| 303 |
except requests.exceptions.RequestException as e:
|
| 304 |
print(f"Error fetching questions: {e}")
|
| 305 |
return f"Error fetching questions: {e}", None
|
| 306 |
except requests.exceptions.JSONDecodeError as e:
|
| 307 |
-
|
| 308 |
-
|
|
|
|
| 309 |
except Exception as e:
|
| 310 |
-
print(f"
|
| 311 |
-
return f"
|
| 312 |
|
| 313 |
-
# Run Agent
|
| 314 |
results_log = []
|
| 315 |
answers_payload = []
|
| 316 |
print(f"Running agent on {len(questions_data)} questions...")
|
| 317 |
-
|
| 318 |
for item in questions_data:
|
| 319 |
task_id = item.get("task_id")
|
| 320 |
question_text = item.get("question")
|
| 321 |
-
|
| 322 |
if not task_id or question_text is None:
|
| 323 |
-
print(f"Skipping
|
| 324 |
continue
|
| 325 |
-
|
| 326 |
-
# Prepend task_id so the agent can use it for file downloads
|
| 327 |
-
augmented_question = f"[task_id: {task_id}]\n{question_text}"
|
| 328 |
-
|
| 329 |
try:
|
|
|
|
|
|
|
| 330 |
submitted_answer = agent(augmented_question)
|
| 331 |
-
answers_payload.append({
|
| 332 |
-
|
| 333 |
-
"submitted_answer": submitted_answer
|
| 334 |
-
})
|
| 335 |
-
results_log.append({
|
| 336 |
-
"Task ID": task_id,
|
| 337 |
-
"Question": question_text,
|
| 338 |
-
"Submitted Answer": submitted_answer
|
| 339 |
-
})
|
| 340 |
except Exception as e:
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
"Task ID": task_id,
|
| 344 |
-
"Question": question_text,
|
| 345 |
-
"Submitted Answer": f"AGENT ERROR: {e}"
|
| 346 |
-
})
|
| 347 |
|
| 348 |
if not answers_payload:
|
| 349 |
-
print("Agent did not produce any answers.")
|
| 350 |
-
return "Agent did not produce any answers.", pd.DataFrame(results_log)
|
| 351 |
-
|
| 352 |
-
# Prepare Submission
|
| 353 |
-
submission_data = {
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
print(f"Submitting {len(answers_payload)} answers
|
| 359 |
-
|
| 360 |
-
# Submit
|
| 361 |
try:
|
| 362 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 363 |
response.raise_for_status()
|
|
@@ -366,13 +257,12 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 366 |
f"Submission Successful!\n"
|
| 367 |
f"User: {result_data.get('username')}\n"
|
| 368 |
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 369 |
-
f"({result_data.get('correct_count', '?')}/"
|
| 370 |
-
f"{result_data.get('total_attempted', '?')} correct)\n"
|
| 371 |
f"Message: {result_data.get('message', 'No message received.')}"
|
| 372 |
)
|
| 373 |
print("Submission successful.")
|
| 374 |
-
|
| 375 |
-
|
| 376 |
except requests.exceptions.HTTPError as e:
|
| 377 |
error_detail = f"Server responded with status {e.response.status_code}."
|
| 378 |
try:
|
|
@@ -382,43 +272,39 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 382 |
error_detail += f" Response: {e.response.text[:500]}"
|
| 383 |
status_message = f"Submission Failed: {error_detail}"
|
| 384 |
print(status_message)
|
| 385 |
-
|
| 386 |
-
|
| 387 |
except requests.exceptions.Timeout:
|
| 388 |
-
status_message = "Submission Failed:
|
| 389 |
print(status_message)
|
| 390 |
-
|
| 391 |
-
|
| 392 |
except requests.exceptions.RequestException as e:
|
| 393 |
status_message = f"Submission Failed: Network error - {e}"
|
| 394 |
print(status_message)
|
| 395 |
-
|
| 396 |
-
|
| 397 |
except Exception as e:
|
| 398 |
-
status_message = f"
|
| 399 |
print(status_message)
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
# ─────────────────────────────────────────────────────────────
|
| 404 |
-
# Gradio Interface
|
| 405 |
-
# ─────────────────────────────────────────────────────────────
|
| 406 |
|
|
|
|
| 407 |
with gr.Blocks() as demo:
|
| 408 |
-
|
| 409 |
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 410 |
gr.Markdown(
|
| 411 |
"""
|
| 412 |
-
|
| 413 |
|
| 414 |
-
1.
|
| 415 |
-
2.
|
| 416 |
-
3.
|
| 417 |
|
| 418 |
---
|
| 419 |
**Disclaimers:**
|
| 420 |
-
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).
|
| 421 |
-
This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution.
|
| 422 |
"""
|
| 423 |
)
|
| 424 |
|
|
@@ -426,42 +312,35 @@ with gr.Blocks() as demo:
|
|
| 426 |
|
| 427 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 428 |
|
| 429 |
-
status_output = gr.Textbox(
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
interactive=False
|
| 433 |
-
)
|
| 434 |
-
|
| 435 |
-
results_table = gr.DataFrame(
|
| 436 |
-
label="Questions and Agent Answers",
|
| 437 |
-
wrap=True
|
| 438 |
-
)
|
| 439 |
|
| 440 |
run_button.click(
|
| 441 |
fn=run_and_submit_all,
|
| 442 |
outputs=[status_output, results_table]
|
| 443 |
)
|
| 444 |
|
| 445 |
-
|
| 446 |
if __name__ == "__main__":
|
| 447 |
-
print("\n" + "-"
|
| 448 |
-
|
| 449 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 450 |
-
space_id_startup = os.getenv("SPACE_ID")
|
| 451 |
|
| 452 |
if space_host_startup:
|
| 453 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 454 |
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 455 |
else:
|
| 456 |
-
print("ℹ️ SPACE_HOST not found (running locally?).")
|
| 457 |
|
| 458 |
-
if space_id_startup:
|
| 459 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 460 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 461 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 462 |
else:
|
| 463 |
-
print("ℹ️ SPACE_ID not found (running locally?).")
|
|
|
|
|
|
|
| 464 |
|
| 465 |
-
print("
|
| 466 |
-
print("Launching Gradio Interface...")
|
| 467 |
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 |
+
# --- Constants ---
|
|
|
|
|
|
|
| 8 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 9 |
|
| 10 |
+
# --- Basic Agent Definition ---
|
| 11 |
+
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 12 |
+
|
| 13 |
+
import re
|
| 14 |
+
from smolagents import CodeAgent, HfApiModel, tool
|
| 15 |
+
from smolagents.tools import DuckDuckGoSearchTool
|
| 16 |
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
@tool
|
| 19 |
def visit_webpage(url: str) -> str:
|
| 20 |
"""
|
| 21 |
Fetches and returns the visible text content of any webpage.
|
| 22 |
+
Use this after a web search to read the full content of a URL.
|
|
|
|
| 23 |
|
| 24 |
Args:
|
| 25 |
url: The full URL to fetch (must start with http:// or https://)
|
| 26 |
|
| 27 |
Returns:
|
| 28 |
+
The visible text of the page, truncated to 8000 characters.
|
| 29 |
"""
|
| 30 |
try:
|
| 31 |
+
headers = {"User-Agent": "Mozilla/5.0"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
resp = requests.get(url, headers=headers, timeout=15)
|
| 33 |
resp.raise_for_status()
|
| 34 |
+
clean = re.sub(r"<style[^>]*>.*?</style>", " ", resp.text, flags=re.DOTALL)
|
|
|
|
|
|
|
| 35 |
clean = re.sub(r"<script[^>]*>.*?</script>", " ", clean, flags=re.DOTALL)
|
| 36 |
clean = re.sub(r"<[^>]+>", " ", clean)
|
| 37 |
clean = re.sub(r"\s+", " ", clean).strip()
|
|
|
|
| 44 |
def download_task_file(task_id: str) -> str:
|
| 45 |
"""
|
| 46 |
Downloads the file attached to a GAIA task and returns its text content.
|
| 47 |
+
Use this whenever the question mentions or implies an attached file.
|
|
|
|
| 48 |
|
| 49 |
Args:
|
| 50 |
+
task_id: The task_id string from the question prefix [task_id: ...].
|
| 51 |
|
| 52 |
Returns:
|
| 53 |
+
The text content of the file, or a descriptive note if unreadable.
|
| 54 |
"""
|
| 55 |
try:
|
| 56 |
url = f"{DEFAULT_API_URL}/files/{task_id}"
|
|
|
|
| 58 |
if resp.status_code == 404:
|
| 59 |
return "No file is associated with this task."
|
| 60 |
resp.raise_for_status()
|
|
|
|
| 61 |
content_type = resp.headers.get("Content-Type", "")
|
| 62 |
+
disposition = resp.headers.get("Content-Disposition", "")
|
|
|
|
|
|
|
| 63 |
filename = ""
|
| 64 |
+
if "filename=" in disposition:
|
| 65 |
+
filename = disposition.split("filename=")[-1].strip().strip('"')
|
|
|
|
| 66 |
ext = filename.rsplit(".", 1)[-1].lower() if "." in filename else ""
|
| 67 |
|
| 68 |
+
if "text" in content_type or ext in ("txt", "csv", "tsv", "md", "py", "js", "json", "xml", "yaml", "yml"):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
return resp.text[:6000]
|
|
|
|
|
|
|
| 70 |
if ext in ("xlsx", "xls"):
|
| 71 |
try:
|
| 72 |
+
import io, openpyxl
|
|
|
|
| 73 |
wb = openpyxl.load_workbook(io.BytesIO(resp.content), data_only=True)
|
| 74 |
lines = []
|
| 75 |
for sheet in wb.sheetnames:
|
|
|
|
| 79 |
lines.append("\t".join(str(c) if c is not None else "" for c in row))
|
| 80 |
return "\n".join(lines)[:6000]
|
| 81 |
except Exception as e:
|
| 82 |
+
return f"Could not parse Excel: {e}"
|
|
|
|
|
|
|
| 83 |
if "pdf" in content_type or ext == "pdf":
|
| 84 |
try:
|
| 85 |
+
import io, pdfminer.high_level
|
|
|
|
| 86 |
text = pdfminer.high_level.extract_text(io.BytesIO(resp.content))
|
| 87 |
+
return (text or "No text in PDF.")[:6000]
|
| 88 |
except Exception as e:
|
| 89 |
return f"Could not parse PDF: {e}"
|
|
|
|
|
|
|
| 90 |
if ext in ("mp3", "wav", "m4a", "flac", "ogg") or "audio" in content_type:
|
| 91 |
+
return f"Audio file detected ({filename}). Cannot transcribe. Answer from question context."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
if ext in ("png", "jpg", "jpeg", "gif", "bmp", "webp") or "image" in content_type:
|
| 93 |
+
return f"Image file detected ({filename}). Cannot read visually. Answer from question context."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
try:
|
| 95 |
return resp.content.decode("utf-8")[:6000]
|
| 96 |
except Exception:
|
| 97 |
+
return f"Binary file ({filename}) — cannot extract text."
|
|
|
|
| 98 |
except Exception as e:
|
| 99 |
return f"Error downloading file for task {task_id}: {e}"
|
| 100 |
|
|
|
|
| 103 |
def calculate(expression: str) -> str:
|
| 104 |
"""
|
| 105 |
Safely evaluates a mathematical expression and returns the result.
|
| 106 |
+
Use this for any arithmetic, percentages, or numeric calculation.
|
| 107 |
|
| 108 |
Args:
|
| 109 |
+
expression: A valid Python math expression string.
|
| 110 |
+
Examples: "2 ** 10", "round(100 * 1.07 ** 3, 2)"
|
| 111 |
|
| 112 |
Returns:
|
| 113 |
The numeric result as a string, or an error message.
|
| 114 |
"""
|
| 115 |
try:
|
| 116 |
import math as _math
|
| 117 |
+
allowed = {k: v for k, v in _math.__dict__.items() if not k.startswith("_")}
|
| 118 |
+
allowed["round"] = round
|
| 119 |
+
allowed["abs"] = abs
|
| 120 |
+
result = eval(expression, {"__builtins__": {}}, allowed)
|
|
|
|
| 121 |
return str(result)
|
| 122 |
except Exception as e:
|
| 123 |
+
return f"Calculation error: {e}"
|
|
|
|
| 124 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
class BasicAgent:
|
|
|
|
| 127 |
def __init__(self):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
self.agent = CodeAgent(
|
| 129 |
tools=[
|
| 130 |
DuckDuckGoSearchTool(),
|
|
|
|
| 132 |
download_task_file,
|
| 133 |
calculate,
|
| 134 |
],
|
| 135 |
+
model=HfApiModel(model_id="Qwen/Qwen2.5-72B-Instruct"),
|
| 136 |
max_steps=10,
|
|
|
|
| 137 |
)
|
| 138 |
+
print("BasicAgent initialized.")
|
|
|
|
| 139 |
|
| 140 |
def __call__(self, question: str) -> str:
|
| 141 |
+
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
|
|
|
|
|
|
| 142 |
|
| 143 |
+
prompt = f"""You are an expert GAIA benchmark solving agent.
|
| 144 |
|
| 145 |
+
RULES:
|
| 146 |
+
- Output ONLY the bare final answer. Nothing else.
|
| 147 |
+
- No explanation. No reasoning. No preamble.
|
| 148 |
+
- No "FINAL ANSWER". No "The answer is".
|
| 149 |
+
- Match exact format: just a number, name, date, or comma-separated list.
|
| 150 |
+
- If a file is referenced, call download_task_file with the task_id from [task_id: ...].
|
| 151 |
+
- Always search the web and visit pages before answering.
|
| 152 |
+
- Never output an empty string.
|
| 153 |
|
| 154 |
+
Question:
|
| 155 |
+
{question}"""
|
| 156 |
|
| 157 |
try:
|
| 158 |
response = self.agent.run(prompt)
|
| 159 |
final_answer = str(response).strip()
|
| 160 |
+
# Strip any accidental prefix
|
| 161 |
+
for prefix in ["FINAL ANSWER:", "FINAL ANSWER", "Answer:", "The answer is:"]:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
if final_answer.upper().startswith(prefix.upper()):
|
| 163 |
final_answer = final_answer[len(prefix):].strip()
|
| 164 |
+
print(f"Agent returning answer: {final_answer}")
|
|
|
|
| 165 |
return final_answer
|
|
|
|
| 166 |
except Exception as e:
|
| 167 |
+
print(f"Agent error: {e}")
|
| 168 |
return ""
|
| 169 |
|
| 170 |
|
| 171 |
+
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
"""
|
| 173 |
+
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 174 |
+
and displays the results.
|
| 175 |
"""
|
| 176 |
+
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 177 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 178 |
|
| 179 |
if profile:
|
| 180 |
+
username= f"{profile.username}"
|
| 181 |
print(f"User logged in: {username}")
|
| 182 |
else:
|
| 183 |
print("User not logged in.")
|
|
|
|
| 187 |
questions_url = f"{api_url}/questions"
|
| 188 |
submit_url = f"{api_url}/submit"
|
| 189 |
|
| 190 |
+
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 191 |
try:
|
| 192 |
agent = BasicAgent()
|
| 193 |
except Exception as e:
|
| 194 |
print(f"Error instantiating agent: {e}")
|
| 195 |
return f"Error initializing agent: {e}", None
|
| 196 |
+
# 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)
|
| 197 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 198 |
print(agent_code)
|
| 199 |
|
| 200 |
+
# 2. Fetch Questions
|
| 201 |
print(f"Fetching questions from: {questions_url}")
|
| 202 |
try:
|
| 203 |
response = requests.get(questions_url, timeout=15)
|
| 204 |
response.raise_for_status()
|
| 205 |
questions_data = response.json()
|
| 206 |
if not questions_data:
|
| 207 |
+
print("Fetched questions list is empty.")
|
| 208 |
+
return "Fetched questions list is empty or invalid format.", None
|
| 209 |
print(f"Fetched {len(questions_data)} questions.")
|
| 210 |
except requests.exceptions.RequestException as e:
|
| 211 |
print(f"Error fetching questions: {e}")
|
| 212 |
return f"Error fetching questions: {e}", None
|
| 213 |
except requests.exceptions.JSONDecodeError as e:
|
| 214 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 215 |
+
print(f"Response text: {response.text[:500]}")
|
| 216 |
+
return f"Error decoding server response for questions: {e}", None
|
| 217 |
except Exception as e:
|
| 218 |
+
print(f"An unexpected error occurred fetching questions: {e}")
|
| 219 |
+
return f"An unexpected error occurred fetching questions: {e}", None
|
| 220 |
|
| 221 |
+
# 3. Run your Agent
|
| 222 |
results_log = []
|
| 223 |
answers_payload = []
|
| 224 |
print(f"Running agent on {len(questions_data)} questions...")
|
|
|
|
| 225 |
for item in questions_data:
|
| 226 |
task_id = item.get("task_id")
|
| 227 |
question_text = item.get("question")
|
|
|
|
| 228 |
if not task_id or question_text is None:
|
| 229 |
+
print(f"Skipping item with missing task_id or question: {item}")
|
| 230 |
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
| 231 |
try:
|
| 232 |
+
# Prepend task_id so agent can use it for file downloads
|
| 233 |
+
augmented_question = f"[task_id: {task_id}]\n{question_text}"
|
| 234 |
submitted_answer = agent(augmented_question)
|
| 235 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 236 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
except Exception as e:
|
| 238 |
+
print(f"Error running agent on task {task_id}: {e}")
|
| 239 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
|
|
|
|
|
|
|
|
|
|
|
|
| 240 |
|
| 241 |
if not answers_payload:
|
| 242 |
+
print("Agent did not produce any answers to submit.")
|
| 243 |
+
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 244 |
+
|
| 245 |
+
# 4. Prepare Submission
|
| 246 |
+
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 247 |
+
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 248 |
+
print(status_update)
|
| 249 |
+
|
| 250 |
+
# 5. Submit
|
| 251 |
+
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
|
|
|
|
|
|
| 252 |
try:
|
| 253 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 254 |
response.raise_for_status()
|
|
|
|
| 257 |
f"Submission Successful!\n"
|
| 258 |
f"User: {result_data.get('username')}\n"
|
| 259 |
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 260 |
+
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
|
|
|
| 261 |
f"Message: {result_data.get('message', 'No message received.')}"
|
| 262 |
)
|
| 263 |
print("Submission successful.")
|
| 264 |
+
results_df = pd.DataFrame(results_log)
|
| 265 |
+
return final_status, results_df
|
| 266 |
except requests.exceptions.HTTPError as e:
|
| 267 |
error_detail = f"Server responded with status {e.response.status_code}."
|
| 268 |
try:
|
|
|
|
| 272 |
error_detail += f" Response: {e.response.text[:500]}"
|
| 273 |
status_message = f"Submission Failed: {error_detail}"
|
| 274 |
print(status_message)
|
| 275 |
+
results_df = pd.DataFrame(results_log)
|
| 276 |
+
return status_message, results_df
|
| 277 |
except requests.exceptions.Timeout:
|
| 278 |
+
status_message = "Submission Failed: The request timed out."
|
| 279 |
print(status_message)
|
| 280 |
+
results_df = pd.DataFrame(results_log)
|
| 281 |
+
return status_message, results_df
|
| 282 |
except requests.exceptions.RequestException as e:
|
| 283 |
status_message = f"Submission Failed: Network error - {e}"
|
| 284 |
print(status_message)
|
| 285 |
+
results_df = pd.DataFrame(results_log)
|
| 286 |
+
return status_message, results_df
|
| 287 |
except Exception as e:
|
| 288 |
+
status_message = f"An unexpected error occurred during submission: {e}"
|
| 289 |
print(status_message)
|
| 290 |
+
results_df = pd.DataFrame(results_log)
|
| 291 |
+
return status_message, results_df
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
|
| 293 |
+
# --- Build Gradio Interface using Blocks ---
|
| 294 |
with gr.Blocks() as demo:
|
|
|
|
| 295 |
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 296 |
gr.Markdown(
|
| 297 |
"""
|
| 298 |
+
**Instructions:**
|
| 299 |
|
| 300 |
+
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 301 |
+
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 302 |
+
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 303 |
|
| 304 |
---
|
| 305 |
**Disclaimers:**
|
| 306 |
+
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).
|
| 307 |
+
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.
|
| 308 |
"""
|
| 309 |
)
|
| 310 |
|
|
|
|
| 312 |
|
| 313 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 314 |
|
| 315 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 316 |
+
# Removed max_rows=10 from DataFrame constructor
|
| 317 |
+
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 318 |
|
| 319 |
run_button.click(
|
| 320 |
fn=run_and_submit_all,
|
| 321 |
outputs=[status_output, results_table]
|
| 322 |
)
|
| 323 |
|
|
|
|
| 324 |
if __name__ == "__main__":
|
| 325 |
+
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 326 |
+
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 327 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 328 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 329 |
|
| 330 |
if space_host_startup:
|
| 331 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 332 |
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 333 |
else:
|
| 334 |
+
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 335 |
|
| 336 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 337 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 338 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 339 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 340 |
else:
|
| 341 |
+
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 342 |
+
|
| 343 |
+
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 344 |
|
| 345 |
+
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
|
|
|
| 346 |
demo.launch(debug=True, share=False)
|