Download app.py from agents-course/Final_Assignment_Template: direct link, hf CLI and curl.
- Browser
- Download file 7.85 kB
-
https://huggingface.co/spaces/agents-course/Final_Assignment_Template/resolve/refs%2Fpr%2F653/app.py
- Command line
-
hf download hf://spaces/agents-course/Final_Assignment_Template@refs/pr/653/app.py
-
curl -L -o app.py https://huggingface.co/spaces/agents-course/Final_Assignment_Template/resolve/refs%2Fpr%2F653/app.py
7.85 kB
| 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")), | |
| ) |