Spaces:
Sleeping
Sleeping
File size: 15,726 Bytes
10e9b7d 129dbb0 10e9b7d eccf8e4 7d65c66 3c4371f 129dbb0 edde1df 129dbb0 10e9b7d d59f015 e80aab9 3db6293 e80aab9 129dbb0 edde1df 129dbb0 31243f4 d59f015 31243f4 0230330 382a50a edde1df 0230330 129dbb0 edde1df 129dbb0 edde1df 129dbb0 31243f4 129dbb0 31243f4 129dbb0 edde1df 129dbb0 edde1df 129dbb0 4021bf3 129dbb0 31243f4 129dbb0 7d65c66 129dbb0 3c4371f 7e4a06b 129dbb0 3c4371f 7e4a06b 3c4371f 7d65c66 3c4371f 7e4a06b 31243f4 e80aab9 b177367 31243f4 30b2b31 3c4371f 31243f4 129dbb0 36ed51a c1fd3d2 3c4371f 7d65c66 31243f4 eccf8e4 31243f4 7d65c66 31243f4 129dbb0 31243f4 30b2b31 31243f4 30b2b31 129dbb0 30b2b31 129dbb0 e80aab9 b177367 7d65c66 3c4371f 31243f4 129dbb0 7d65c66 31243f4 129dbb0 31243f4 3c4371f 31243f4 129dbb0 31243f4 e80aab9 129dbb0 e80aab9 30b2b31 129dbb0 30b2b31 129dbb0 30b2b31 129dbb0 30b2b31 129dbb0 e80aab9 129dbb0 e80aab9 31243f4 129dbb0 30b2b31 129dbb0 e80aab9 129dbb0 e80aab9 31243f4 0ee0419 e514fd7 129dbb0 e514fd7 129dbb0 e80aab9 129dbb0 7e4a06b e80aab9 129dbb0 31243f4 e80aab9 129dbb0 e80aab9 129dbb0 e80aab9 129dbb0 7d65c66 129dbb0 7d65c66 129dbb0 7d65c66 3c4371f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 | import os
import re
import gradio as gr
import requests
import inspect
import pandas as pd
import spaces
from smolagents import CodeAgent, LiteLLMModel, VisitWebpageTool, tool
# (Keep Constants as is)
# --- Constants ---
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
# --- ZeroGPU: the Space needs at least one @spaces.GPU function to start ---
@spaces.GPU(duration=120)
def _zero_gpu_keepalive():
return "ok"
# --- Gemini with Google Search grounding ---
# DuckDuckGo rate-limits requests coming from HF Spaces ("No results found"),
# so web search goes through Gemini's built-in Google Search grounding instead.
GEMINI_MODEL = "gemini-3.8-flash"
GEMINI_URL = f"https://generativelanguage.googleapis.com/v1beta/models/{GEMINI_MODEL}:generateContent"
def gemini_grounded(prompt: str, timeout: int = 90) -> str:
"""Ask Gemini a question with Google Search grounding and return its text."""
resp = requests.post(
GEMINI_URL,
headers={"x-goog-api-key": os.getenv("GEMINI_API_KEY", ""), "Content-Type": "application/json"},
json={"contents": [{"parts": [{"text": prompt}]}], "tools": [{"google_search": {}}]},
timeout=timeout,
)
resp.raise_for_status()
parts = resp.json()["candidates"][0]["content"]["parts"]
return "".join(p.get("text", "") for p in parts).strip()
@tool
def google_search(query: str) -> str:
"""Search the web with Google (via Gemini grounding) and return a factual summary with key details.
Args:
query: The search query or factual question to look up.
"""
try:
return gemini_grounded(
"Search the web and give a factual, detailed answer with specific names, numbers and dates. "
"Query: " + query
)[:6000]
except Exception as e:
return f"Search failed: {e}"
# --- Extra tools for the GAIA agent ---
@tool
def search_wikipedia(query: str) -> str:
"""Search English Wikipedia for a topic and return a short summary of the best matching article.
Args:
query: The topic or question to look up on Wikipedia.
"""""
try:
search_url = "https://en.wikipedia.org/w/api.php"
params = {"action": "query", "list": "search", "srsearch": query, "srlimit": 3, "format": "json"}
headers = {"User-Agent": "GAIA-agent-course/1.0"}
resp = requests.get(search_url, params=params, headers=headers, timeout=20)
resp.raise_for_status()
results = resp.json().get("query", {}).get("search", [])
if not results:
return "No Wikipedia article found."
title = results[0]["title"]
summary_url = "https://en.wikipedia.org/api/rest_v1/page/summary/" + requests.utils.quote(title)
summary_resp = requests.get(summary_url, headers=headers, timeout=20)
summary_resp.raise_for_status()
data = summary_resp.json()
text = data.get("extract", "")
if text:
return f"Wikipedia article '{title}': {text}"
return f"Wikipedia article found: {title} (no summary available)."
except Exception as e:
return f"Wikipedia search failed: {e}"
@tool
def read_file(path: str) -> str:
"""Read a local file and return its contents as text. Supports .txt, .py, .md, .csv and .json files and .xlsx spreadsheets (returned as a table). Use this to inspect files attached to a task.
Args:
path: The local file path to read.
"""""
try:
if path.lower().endswith(".xlsx"):
df = pd.read_excel(path)
return df.to_string(index=False)
if path.lower().endswith((".mp3", ".wav", ".png", ".jpg", ".jpeg")):
return f"The file {path} is an audio or image file and cannot be read as text with the available tools."
with open(path, "r", encoding="utf-8", errors="replace") as f:
content = f.read()
if len(content) > 8000:
return content[:8000]
return content
except Exception as e:
return f"Could not read file {path}: {e}"
@tool
def get_youtube_transcript(video_url: str) -> str:
"""Fetch the transcript (subtitles) of a YouTube video, given its URL or video ID.
Args:
video_url: The full YouTube video URL or the video ID.
"""""
try:
from youtube_transcript_api import YouTubeTranscriptApi
match = re.search(r"(?:v=|youtu\.be/|shorts/)([A-Za-z0-9_-]{11})", video_url)
video_id = match.group(1) if match else video_url.strip()
try:
transcript = YouTubeTranscriptApi().fetch(video_id)
lines = [entry.text for entry in transcript]
except Exception:
transcript = YouTubeTranscriptApi.get_transcript(video_id)
lines = [entry["text"] for entry in transcript]
text = " ".join(lines)
if len(text) > 8000:
return text[:8000]
return text
except Exception as e:
return f"Could not fetch YouTube transcript: {e}"
# --- Basic Agent Definition ---
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
class BasicAgent:
def __init__(self):
# Gemini via LiteLLM. gemini-2.5-flash and gemini-2.0-flash are retired
# for this key (Google returns 404), so use the current flash model.
model = LiteLLMModel(
model_id=f"gemini/{GEMINI_MODEL}",
api_key=os.getenv("GEMINI_API_KEY"),
)
self.agent = CodeAgent(
tools=[google_search, VisitWebpageTool(), search_wikipedia, read_file, get_youtube_transcript],
model=model,
max_steps=12,
)
print("BasicAgent initialized.")
def __call__(self, question: str) -> str:
print(f"Agent received question (first 50 chars): {question[:50]}...")
prompt = (
question
+ "\n\nUse your tools to research the question and verify the facts before answering. "
"When you know the answer, finish with exactly one line in this format: FINAL ANSWER: <your answer> "
"Do not add anything after that line."
)
try:
result = self.agent.run(prompt)
except Exception as e:
print(f"Agent run failed: {e}")
result = None
answer = self._clean(result)
if self._is_junk(answer):
print(f"Agent answer unusable ({answer!r}); using grounded fallback.")
try:
answer = self._clean(gemini_grounded(
question
+ "\n\nResearch this carefully, then reply with ONLY the final answer on the last line as "
"'FINAL ANSWER: <answer>'. The answer must be a number, a few words, or a comma-separated list, "
"with no units or explanation unless the question asks for them."
))
except Exception as e:
print(f"Fallback failed: {e}")
print(f"Agent returning answer: {answer}")
return answer
@staticmethod
def _clean(result) -> str:
"""Pull the text after the last 'FINAL ANSWER:' and keep its first line."""
answer = "" if result is None else str(result).strip()
if "FINAL ANSWER:" in answer:
answer = answer.split("FINAL ANSWER:")[-1].strip()
return answer.split("\n")[0].strip().strip("*").strip()
@staticmethod
def _is_junk(answer: str) -> bool:
"""True for empty answers or obvious leftovers like 'None', 'Thought:' or '{answer}'."""
low = answer.lower()
return (not answer or low in ("none", "null", "thought:") or "{answer}" in low
or low.startswith("thought") or len(answer) > 200)
def run_and_submit_all(profile: gr.OAuthProfile | None):
"""
Fetches all questions, runs the BasicAgent on them, submits all answers,
and displays the results.
"""""
# --- Determine HF Space Runtime URL and Repo URL ---
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
if profile:
username = f"{profile.username}"
print(f"User logged in: {username}")
else:
print("User not logged in.")
return "Please Login to Hugging Face with the button.", None
api_url = DEFAULT_API_URL
questions_url = f"{api_url}/questions"
submit_url = f"{api_url}/submit"
# 1. Instantiate Agent ( modify this part to create your agent)
try:
agent = BasicAgent()
except Exception as e:
print(f"Error instantiating agent: {e}")
return f"Error initializing agent: {e}", None
# In the case of an app running as a hugging Face space, this link points toward your codebase ( use the SPACE_ID environment variable if you don't want to hardcode it)
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
print(agent_code)
# 2. Fetch Questions
print(f"Fetching questions from: {questions_url}")
try:
response = requests.get(questions_url, timeout=15)
response.raise_for_status()
questions_data = response.json()
if not questions_data:
print("Fetched questions list is empty.")
return "Fetched questions list is empty or invalid format.", None
print(f"Fetched {len(questions_data)} questions.")
except requests.exceptions.RequestException as e:
print(f"Error fetching questions: {e}")
return f"Error fetching questions: {e}", None
except requests.exceptions.JSONDecodeError as e:
print(f"Error decoding JSON response of questions: {e}")
return f"Error decoding JSON response of questions: {e}", None
except Exception as e:
print(f"Unexpected error fetching questions: {e}")
return f"Unexpected error fetching questions: {e}", None
# 3. Run your Agent
results_log = []
answers_payload = []
print(f"Running agent on {len(questions_data)} questions...")
for item in questions_data:
task_id = item.get("task_id")
question_text = item.get("question")
if not task_id or question_text is None:
print(f"Skipping item with missing task_id or question: {item}")
continue
try:
# Download the file attached to this task, if any, so the agent can inspect it
file_name = item.get("file_name") or ""
question_for_agent = question_text
if file_name:
try:
file_url = f"{api_url}/files/{task_id}"
file_response = requests.get(file_url, timeout=60)
file_response.raise_for_status()
local_path = os.path.join("/tmp", file_name)
with open(local_path, "wb") as f:
f.write(file_response.content)
question_for_agent = (
question_text
+ f"\n\nAn attached file for this task was downloaded to: {local_path}. Use the read_file tool to inspect it if it helps answer the question."
)
except Exception as fe:
print(f"Could not download file for task {task_id}: {fe}")
submitted_answer = agent(question_for_agent)
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
except Exception as e:
print(f"Error running agent on task {task_id}: {e}")
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
if not answers_payload:
print("Agent did not produce any answers to submit.")
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
# 4. Submit Answers
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
try:
payload = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
response = requests.post(submit_url, json=payload, timeout=60)
response.raise_for_status()
result_data = response.json()
except requests.exceptions.HTTPError as e:
error_detail = f"HTTP Error: {e}"
try:
error_json = response.json()
error_detail += f" | Server response: {error_json}"
except Exception:
error_detail += f" | Server raw response: {response.text[:500]}"
print(error_detail)
return error_detail, pd.DataFrame(results_log)
except requests.exceptions.RequestException as e:
print(f"Error submitting answers: {e}")
return f"Error submitting answers: {e}", pd.DataFrame(results_log)
except requests.exceptions.JSONDecodeError as e:
print(f"Error decoding JSON response of submission: {e}")
return f"Error decoding JSON response of submission: {e}", pd.DataFrame(results_log)
except Exception as e:
print(f"Unexpected error submitting answers: {e}")
return f"Unexpected error submitting answers: {e}", pd.DataFrame(results_log)
# 5. Format Submission Results
try:
status_message = (
f"Submission Successful!\n"
f"User: {result_data.get('username')}\n"
f"Score: {result_data.get('score')} ({result_data.get('correct_count')}/{result_data.get('total_attempted')} correct)\n"
f"Message: {result_data.get('message')}"
)
print(status_message)
return status_message, pd.DataFrame(results_log)
except Exception as e:
print(f"Error formatting submission results: {e}")
return f"Submission worked but formatting failed: {e}\nRaw data: {result_data}", pd.DataFrame(results_log)
# --- Build the Gradio UI ---
with gr.Blocks() as demo:
gr.Markdown("# Basic Agent Evaluation Runner")
gr.Markdown(
"""
**Instructions:**
1. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
2. Click 'Run Evaluation & Submit All Answers' to fetch the 20 GAIA level-1 questions, run the agent on them, submit the answers, and see the score.
---
**Disclaimer:**
Running the evaluation can take quite some time (this is the time for the agent to answer all 20 questions). Please be patient.
"""""
)
# --- OAuth ---
gr.LoginButton()
# --- Interactive Components ---
run_button = gr.Button("Run Evaluation & Submit All Answers")
status_output = gr.Textbox(label="Status Message", lines=5, interactive=False)
results_dataframe = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
# --- UI Events ---
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_dataframe])
# --- Launch the App ---
if __name__ == "__main__":
space_host = os.getenv("SPACE_HOST")
space_id = os.getenv("SPACE_ID")
if space_host:
print(f"SPACE_HOST found: {space_host}")
print(f"SPACE_ID='{space_id}'")
else:
print("SPACE_HOST environment variable not found (running locally?).")
print("SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
launch_kwargs = {"debug": True, "share": False}
if space_host:
launch_kwargs["server_name"] = "0.0.0.0"
launch_kwargs["server_port"] = 7860
demo.launch(**launch_kwargs)
|