File size: 7,853 Bytes
6ac4b26 | 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 | import os
import time
import traceback
from typing import Optional
import gradio as gr
import pandas as pd
import requests
from agent import BasicAgent
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
QUESTIONS_URL = f"{DEFAULT_API_URL}/questions"
SUBMIT_URL = f"{DEFAULT_API_URL}/submit"
REQUEST_TIMEOUT = 60
MAX_RETRIES = 3
def fetch_questions():
"""Retrieve the GAIA evaluation questions."""
last_error = None
for attempt in range(MAX_RETRIES):
try:
response = requests.get(
QUESTIONS_URL,
timeout=REQUEST_TIMEOUT,
)
response.raise_for_status()
data = response.json()
if isinstance(data, dict):
questions = data.get(
"questions",
data.get("data", []),
)
else:
questions = data
if not isinstance(questions, list):
raise ValueError(
"Unexpected questions API response format."
)
if not questions:
raise ValueError("The questions list is empty.")
return questions
except Exception as exc:
last_error = exc
if attempt < MAX_RETRIES - 1:
time.sleep(2 ** attempt)
raise RuntimeError(
f"Could not fetch questions: {last_error}"
)
def submit_answers(
username: str,
agent_code: str,
answers: list,
):
"""Submit generated answers to the official scoring API."""
payload = {
"username": username,
"agent_code": agent_code,
"answers": answers,
}
response = requests.post(
SUBMIT_URL,
json=payload,
timeout=REQUEST_TIMEOUT,
)
response.raise_for_status()
return response.json()
def run_and_submit_all(
profile: Optional[gr.OAuthProfile],
progress=gr.Progress(),
):
"""Run the agent on all questions and submit the answers."""
if profile is None:
return (
"Login required. Use the Hugging Face login button first.",
pd.DataFrame(),
)
username = getattr(profile, "username", None)
if not username:
return (
"Could not identify the logged-in Hugging Face user.",
pd.DataFrame(),
)
space_id = os.getenv("SPACE_ID")
if not space_id:
return (
"SPACE_ID is missing. Run this application inside "
"your Hugging Face Space.",
pd.DataFrame(),
)
agent_code = (
f"https://huggingface.co/spaces/{space_id}/tree/main"
)
try:
progress(0.03, desc="Initializing agent...")
agent = BasicAgent()
except Exception as exc:
traceback.print_exc()
return (
f"Agent initialization failed: {exc}",
pd.DataFrame(),
)
try:
progress(0.08, desc="Fetching GAIA questions...")
questions = fetch_questions()
except Exception as exc:
return (
str(exc),
pd.DataFrame(),
)
answers_payload = []
results_log = []
total = len(questions)
for index, item in enumerate(questions):
task_id = item.get("task_id")
question = item.get("question")
progress(
0.10 + (0.80 * index / max(total, 1)),
desc=f"Solving question {index + 1}/{total}",
)
if not task_id or question is None:
results_log.append({
"Task ID": task_id,
"Question": question,
"Submitted Answer": "",
"Status": "Skipped: missing task information",
})
continue
try:
answer = agent(
question=str(question),
task_id=str(task_id),
)
if not answer:
answer = ""
answers_payload.append({
"task_id": task_id,
"submitted_answer": answer,
})
results_log.append({
"Task ID": task_id,
"Question": question,
"Submitted Answer": answer,
"Status": "Completed",
})
except Exception as exc:
traceback.print_exc()
results_log.append({
"Task ID": task_id,
"Question": question,
"Submitted Answer": "",
"Status": f"Agent error: {exc}",
})
progress(
0.10 + (0.80 * (index + 1) / max(total, 1)),
desc=f"Completed {index + 1}/{total}",
)
if not answers_payload:
return (
"No answers were generated. Nothing was submitted.",
pd.DataFrame(results_log),
)
progress(0.93, desc="Submitting answers to GAIA scoring API...")
try:
result = submit_answers(
username=username,
agent_code=agent_code,
answers=answers_payload,
)
score = result.get("score", "N/A")
correct = result.get("correct_count", "?")
attempted = result.get("total_attempted", "?")
message = result.get("message", "No message returned.")
status = (
"Submission successful.\n\n"
f"Username: {result.get('username', username)}\n"
f"Score: {score}%\n"
f"Correct answers: {correct}/{attempted}\n"
f"Message: {message}"
)
except requests.HTTPError as exc:
response_text = (
exc.response.text[:1000]
if exc.response is not None
else str(exc)
)
status = (
"Submission failed.\n"
f"HTTP error: {response_text}"
)
except Exception as exc:
traceback.print_exc()
status = f"Submission failed: {exc}"
progress(1.0, desc="Finished.")
return status, pd.DataFrame(results_log)
with gr.Blocks(
title="GAIA Agent - Final Assignment",
) as demo:
gr.Markdown(
"""
# Hugging Face Agents Course
## Unit 4 — GAIA Final Assignment
This application runs an AI agent against the course's
20 selected GAIA Level 1 questions and submits the results
to the official scoring API.
**Important:** Answers are evaluated using exact matching.
The agent is instructed to return concise answers only.
"""
)
with gr.Row():
login_button = gr.LoginButton()
gr.Markdown(
"""
### Evaluation
1. Log in with your Hugging Face account.
2. Run the evaluation.
3. Wait for all questions to be processed.
4. Review the answers and final score.
"""
)
run_button = gr.Button(
"Run Evaluation & Submit All Answers",
variant="primary",
)
status_output = gr.Textbox(
label="Evaluation Status",
lines=7,
interactive=False,
)
results_table = gr.DataFrame(
label="GAIA Answers",
wrap=True,
interactive=False,
)
run_button.click(
fn=run_and_submit_all,
inputs=[login_button],
outputs=[
status_output,
results_table,
],
)
if __name__ == "__main__":
demo.launch(
server_name="0.0.0.0",
server_port=int(os.getenv("PORT", "7860")),
) |