Add GAIA Unit 4 workbench
Browse filesFiles changed (7)
- .gitignoreAdded+6
- README.md+55-9
- answers.template.jsonAdded+1
- app.py+113-182
- deploy_to_hf.pyAdded+37
- gaia_workbench.pyAdded+186
- requirements.txt+5-2
123456.venv/__pycache__/*.pyc.envanswers.local.jsondata/123452374510111267158910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061---title: Template Final Assignmentemoji: 🕵🏻♂️colorFrom: indigocolorTo: indigotitle: GAIA Unit 4 Workbenchsdk: gradiosdk_version: 5.25.2app_file: app.pypinned: falsehf_oauth: true# optional, default duration is 8 hours/480 minutes. Max duration is 30 days/43200 minutes.hf_oauth_expiration_minutes: 480---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference# Hugging Face GAIA Agent Workbench
Small Hugging Face Space/workbench for the Agents Course Unit 4 final assignment.
## What It Does
- Fetches the 20 filtered GAIA Level 1 questions from the course API.- Downloads task files into `data/files/`.- Lets you maintain exact-match answers in `answers.local.json`.- Submits answers to the course scoring API from the Gradio UI or CLI.
## Required For Final Submission
- Hugging Face account.- Public Hugging Face Space with this code.- HF login in the Space UI.- Exact final answers without `FINAL ANSWER` prefix.
## Local Setup
```bashpython -m venv .venvsource .venv/bin/activatepip install -r requirements.txtpython gaia_workbench.py fetchpython app.py```
## CLI
```bashpython gaia_workbench.py fetchpython gaia_workbench.py download-filespython gaia_workbench.py statuspython gaia_workbench.py submit --username YOUR_HF_USERNAME --agent-code https://huggingface.co/spaces/YOUR_USERNAME/YOUR_SPACE/tree/main```
## Answer File
Create `answers.local.json` from the template:
```bashcp answers.template.json answers.local.json```
Then fill:
```json{ "task-id": "exact answer"}```
`answers.local.json` is gitignored because it may contain your final submission answers.1{}12345346778910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910089101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145585960616263646566676869707172737475767778798081828384147148149150151152153154155156157158858687888990161919216393949596971651661679899100169170171101102103104105106107108109110111112113114115116117118119120121122123124175176177178179180181182183184185186187188189190191192193194195196125126127from __future__ import annotations
import os
import gradio as grimport requestsimport inspectimport pandas as pd
# (Keep Constants as is)# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
# --- Basic Agent Definition ---# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------class BasicAgent: def __init__(self): print("BasicAgent initialized.") def __call__(self, question: str) -> str: print(f"Agent received question (first 50 chars): {question[:50]}...") fixed_answer = "This is a default answer." print(f"Agent returning fixed answer: {fixed_answer}") return fixed_answer
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 ( usefull for others so please keep it public) 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 from questions endpoint: {e}") print(f"Response text: {response.text[:500]}") return f"Error decoding server response for questions: {e}", None except Exception as e: print(f"An unexpected error occurred fetching questions: {e}") return f"An unexpected error occurred 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: submitted_answer = agent(question_text) 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. Prepare Submission submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload} status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..." print(status_update)
# 5. Submit print(f"Submitting {len(answers_payload)} answers to: {submit_url}")from gaia_workbench import ( API_URL, answer_payload, download_files, fetch_questions, load_answers, load_questions, status_rows, submit_answers, write_answer,)
def refresh_questions() -> tuple[str, pd.DataFrame]: questions = fetch_questions() return f"Fetched {len(questions)} questions from {API_URL}", pd.DataFrame(status_rows())
def refresh_status() -> pd.DataFrame: return pd.DataFrame(status_rows())
def save_answer(task_id: str, answer: str) -> tuple[str, pd.DataFrame]: if not task_id.strip(): return "Missing task_id", refresh_status() if not answer.strip(): return "Missing answer", refresh_status() write_answer(task_id.strip(), answer.strip()) return f"Saved answer for {task_id.strip()}", refresh_status()
def download_attached_files() -> str: downloaded, failed = download_files() parts = [] if downloaded: parts.append("Downloaded:\n" + "\n".join(str(path) for path in downloaded)) if failed: parts.append("Failed:\n" + "\n".join(failed)) return "\n\n".join(parts) if parts else "No attached files found."
def _default_agent_code() -> str: space_id = os.getenv("SPACE_ID", "").strip() return f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else ""
def _submit_with(username: str, agent_code: str) -> tuple[str, pd.DataFrame]: agent_code = agent_code.strip() or _default_agent_code()
try: response = requests.post(submit_url, json=submission_data, timeout=60) response.raise_for_status() result_data = response.json() final_status = ( f"Submission Successful!\n" f"User: {result_data.get('username')}\n" f"Overall Score: {result_data.get('score', 'N/A')}% " f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n" f"Message: {result_data.get('message', 'No message received.')}" ) print("Submission successful.") results_df = pd.DataFrame(results_log) return final_status, results_df except requests.exceptions.HTTPError as e: error_detail = f"Server responded with status {e.response.status_code}." try: error_json = e.response.json() error_detail += f" Detail: {error_json.get('detail', e.response.text)}" except requests.exceptions.JSONDecodeError: error_detail += f" Response: {e.response.text[:500]}" status_message = f"Submission Failed: {error_detail}" print(status_message) results_df = pd.DataFrame(results_log) return status_message, results_df except requests.exceptions.Timeout: status_message = "Submission Failed: The request timed out." print(status_message) results_df = pd.DataFrame(results_log) return status_message, results_df except requests.exceptions.RequestException as e: status_message = f"Submission Failed: Network error - {e}" print(status_message) results_df = pd.DataFrame(results_log) return status_message, results_df except Exception as e: status_message = f"An unexpected error occurred during submission: {e}" print(status_message) results_df = pd.DataFrame(results_log) return status_message, results_df
# --- Build Gradio Interface using Blocks ---with gr.Blocks() as demo: gr.Markdown("# Basic Agent Evaluation Runner") result = submit_answers(username=username, agent_code=agent_code) except Exception as exc: return f"Submission failed: {exc}", refresh_status()
return ( "Submission successful\n" f"User: {result.get('username')}\n" f"Score: {result.get('score')}%\n" f"Correct: {result.get('correct_count')}/{result.get('total_attempted')}\n" f"Message: {result.get('message')}", refresh_status(), )
def submit_logged_in(profile: gr.OAuthProfile | None) -> tuple[str, pd.DataFrame]: if not profile: return "Please login with Hugging Face first, or use manual submit.", refresh_status() return _submit_with(profile.username, _default_agent_code())
def submit_manual(manual_username: str, manual_agent_code: str) -> tuple[str, pd.DataFrame]: return _submit_with(manual_username.strip(), manual_agent_code.strip())
with gr.Blocks(title="GAIA Unit 4 Workbench") as demo: gr.Markdown("# GAIA Unit 4 Workbench") gr.Markdown( """ **Instructions:**
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ... 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission. 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
--- **Disclaimers:** 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). 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. """ "Fetch the course questions, fill exact-match answers, then submit. " "On Hugging Face Spaces, login with the button before submission." )
is_space_runtime = bool(os.getenv("SPACE_ID", "").strip()) if is_space_runtime: gr.LoginButton() gr.LoginButton()
run_button = gr.Button("Run Evaluation & Submit All Answers") with gr.Row(): fetch_button = gr.Button("Fetch Questions") download_button = gr.Button("Download Attached Files") refresh_button = gr.Button("Refresh Status")
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False) # Removed max_rows=10 from DataFrame constructor results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True) status = gr.Textbox(label="Status", lines=5) table = gr.DataFrame(label="Questions / Answers", wrap=True, value=pd.DataFrame(status_rows()))
run_button.click( fn=run_and_submit_all, outputs=[status_output, results_table] with gr.Row(): task_id_input = gr.Textbox(label="Task ID") answer_input = gr.Textbox(label="Exact Answer") save_button = gr.Button("Save Answer")
gr.Markdown("## Submit") manual_username = gr.Textbox(label="HF Username fallback", placeholder="Used only when not logged in via HF OAuth") manual_agent_code = gr.Textbox( label="Agent Code URL fallback", placeholder="https://huggingface.co/spaces/YOUR_USERNAME/YOUR_SPACE/tree/main", ) with gr.Row(): submit_login_button = gr.Button("Submit With HF Login", visible=is_space_runtime) submit_manual_button = gr.Button("Submit Manual")
fetch_button.click(fn=refresh_questions, outputs=[status, table]) download_button.click(fn=download_attached_files, outputs=status) refresh_button.click(fn=refresh_status, outputs=table) save_button.click(fn=save_answer, inputs=[task_id_input, answer_input], outputs=[status, table]) submit_login_button.click(fn=submit_logged_in, outputs=[status, table]) submit_manual_button.click(fn=submit_manual, inputs=[manual_username, manual_agent_code], outputs=[status, table])
if __name__ == "__main__": print("\n" + "-"*30 + " App Starting " + "-"*30) # Check for SPACE_HOST and SPACE_ID at startup for information space_host_startup = os.getenv("SPACE_HOST") space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
if space_host_startup: print(f"✅ SPACE_HOST found: {space_host_startup}") print(f" Runtime URL should be: https://{space_host_startup}.hf.space") else: print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
if space_id_startup: # Print repo URLs if SPACE_ID is found print(f"✅ SPACE_ID found: {space_id_startup}") print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}") print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main") else: print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
print("-"*(60 + len(" App Starting ")) + "\n")
print("Launching Gradio Interface for Basic Agent Evaluation...") demo.launch(debug=True, share=False) print(f"Loaded {len(load_questions())} questions and {len(load_answers())} local answers.") print(f"Prepared {len(answer_payload())} answers for submission.") demo.launch()12345678910111213141516171819202122232425262728293031323334353637from __future__ import annotations
import getpassfrom pathlib import Path
from huggingface_hub import HfApi
ROOT = Path(__file__).resolve().parentREPO_ID = "smashburger-dev/Final_Assignment_Template"
def main() -> None: token = getpass.getpass("HF token: ").strip() if not token: raise SystemExit("Missing token")
api = HfApi(token=token) api.upload_folder( repo_id=REPO_ID, repo_type="space", folder_path=str(ROOT), ignore_patterns=[ ".venv/**", "__pycache__/**", "data/**", "answers.local.json", "*.pyc", ".env", ], commit_message="Add GAIA Unit 4 workbench", ) print(f"Uploaded to https://huggingface.co/spaces/{REPO_ID}/tree/main")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186from __future__ import annotations
import argparseimport jsonimport osfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any
import requests
API_URL = "https://agents-course-unit4-scoring.hf.space"ROOT = Path(__file__).resolve().parentDATA_DIR = ROOT / "data"QUESTIONS_PATH = DATA_DIR / "questions.json"FILES_DIR = DATA_DIR / "files"ANSWERS_PATH = ROOT / "answers.local.json"
@dataclass(frozen=True)class Question: task_id: str question: str file_name: str = ""
def _request_json(method: str, url: str, **kwargs: Any) -> Any: response = requests.request(method, url, timeout=60, **kwargs) response.raise_for_status() return response.json()
def fetch_questions() -> list[Question]: DATA_DIR.mkdir(parents=True, exist_ok=True) raw_questions = _request_json("GET", f"{API_URL}/questions") QUESTIONS_PATH.write_text(json.dumps(raw_questions, indent=2, ensure_ascii=False), encoding="utf-8") return [ Question( task_id=str(item["task_id"]), question=str(item["question"]), file_name=str(item.get("file_name") or ""), ) for item in raw_questions ]
def load_questions() -> list[Question]: if not QUESTIONS_PATH.exists(): return fetch_questions() raw_questions = json.loads(QUESTIONS_PATH.read_text(encoding="utf-8")) return [ Question( task_id=str(item["task_id"]), question=str(item["question"]), file_name=str(item.get("file_name") or ""), ) for item in raw_questions ]
def load_answers() -> dict[str, str]: if not ANSWERS_PATH.exists(): return {} raw_answers = json.loads(ANSWERS_PATH.read_text(encoding="utf-8")) return {str(task_id): str(answer).strip() for task_id, answer in raw_answers.items() if str(answer).strip()}
def write_answer(task_id: str, answer: str) -> None: answers = load_answers() answers[task_id] = answer.strip() ANSWERS_PATH.write_text(json.dumps(answers, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
def download_task_file(task_id: str, file_name: str = "") -> Path: FILES_DIR.mkdir(parents=True, exist_ok=True) response = requests.get(f"{API_URL}/files/{task_id}", timeout=60) response.raise_for_status() target_name = file_name or task_id target = FILES_DIR / target_name target.write_bytes(response.content) return target
def download_files() -> tuple[list[Path], list[str]]: downloaded: list[Path] = [] failed: list[str] = [] for question in load_questions(): if question.file_name: try: downloaded.append(download_task_file(question.task_id, question.file_name)) except requests.HTTPError as exc: failed.append(f"{question.task_id} ({question.file_name}): {exc}") return downloaded, failed
def answer_payload() -> list[dict[str, str]]: answers = load_answers() questions = load_questions() return [ {"task_id": question.task_id, "submitted_answer": answers[question.task_id]} for question in questions if question.task_id in answers ]
def submit_answers(username: str, agent_code: str) -> dict[str, Any]: payload = { "username": username.strip(), "agent_code": agent_code.strip(), "answers": answer_payload(), } if not payload["username"]: raise ValueError("Missing username") if not payload["agent_code"]: raise ValueError("Missing agent_code") if not payload["answers"]: raise ValueError("No answers found in answers.local.json") return _request_json("POST", f"{API_URL}/submit", json=payload)
def status_rows() -> list[dict[str, str]]: answers = load_answers() rows = [] for index, question in enumerate(load_questions(), start=1): rows.append( { "#": str(index), "task_id": question.task_id, "file": question.file_name, "answered": "yes" if question.task_id in answers else "no", "answer": answers.get(question.task_id, ""), "question": question.question, } ) return rows
def main() -> None: parser = argparse.ArgumentParser(description="Hugging Face GAIA Unit 4 workbench") subparsers = parser.add_subparsers(dest="command", required=True)
subparsers.add_parser("fetch", help="Fetch and cache questions") subparsers.add_parser("download-files", help="Download all attached task files") subparsers.add_parser("status", help="Print answer coverage")
set_answer_parser = subparsers.add_parser("set-answer", help="Set one exact-match answer") set_answer_parser.add_argument("task_id") set_answer_parser.add_argument("answer")
submit_parser = subparsers.add_parser("submit", help="Submit filled local answers") submit_parser.add_argument("--username", default=os.getenv("HF_USERNAME", "")) submit_parser.add_argument("--agent-code", default=os.getenv("AGENT_CODE", ""))
args = parser.parse_args()
if args.command == "fetch": questions = fetch_questions() print(f"Fetched {len(questions)} questions -> {QUESTIONS_PATH}") elif args.command == "download-files": downloaded, failed = download_files() print(f"Downloaded {len(downloaded)} files") for path in downloaded: print(path) if failed: print(f"Failed {len(failed)} files") for item in failed: print(item) elif args.command == "status": rows = status_rows() answered_count = sum(1 for row in rows if row["answered"] == "yes") print(f"Answered {answered_count}/{len(rows)}") for row in rows: marker = "[x]" if row["answered"] == "yes" else "[ ]" file_part = f" file={row['file']}" if row["file"] else "" print(f"{marker} {row['#']}. {row['task_id']}{file_part} - {row['question']}") elif args.command == "set-answer": write_answer(args.task_id, args.answer) print(f"Saved answer for {args.task_id}") elif args.command == "submit": result = submit_answers(args.username, args.agent_code) print(json.dumps(result, indent=2, ensure_ascii=False))
if __name__ == "__main__": main()1212345gradiorequestsgradio[oauth]>=4.44.0huggingface_hub<1.0pandas>=2.2.0openpyxl>=3.1.0requests>=2.32.0.gitignoreAdded+6
README.md+55-9
answers.template.jsonAdded+1
app.py+113-182
deploy_to_hf.pyAdded+37
gaia_workbench.pyAdded+186
requirements.txt+5-2