Download app.py from agents-course/Final_Assignment_Template: direct link, hf CLI and curl.
- Browser
- Download file 5.1 kB
-
https://huggingface.co/spaces/agents-course/Final_Assignment_Template/resolve/refs%2Fpr%2F631/app.py
- Command line
-
hf download hf://spaces/agents-course/Final_Assignment_Template@refs/pr/631/app.py
-
curl -L -o app.py https://huggingface.co/spaces/agents-course/Final_Assignment_Template/resolve/refs%2Fpr%2F631/app.py
5.1 kB
| """Gradio app for the Agents Course final assignment. | |
| Changes from the course template: | |
| - The agent also gets the file attached to each question (GET /files/{task_id}). | |
| - Answers are cached to disk after every question, so a crash or timeout does not | |
| lose earlier work, and re-running only processes what is missing. | |
| - Running and submitting are separate buttons: inspect the answers, then submit. | |
| """ | |
| import os | |
| import traceback | |
| import gradio as gr | |
| import pandas as pd | |
| import gaia_api as api | |
| AGENT = None # built lazily so the UI loads even if the model config is wrong | |
| def get_agent(): | |
| global AGENT | |
| if AGENT is None: | |
| from agent import GaiaAgent | |
| AGENT = GaiaAgent() | |
| return AGENT | |
| def cache_table(cache: dict) -> pd.DataFrame: | |
| rows = [ | |
| {"Task ID": tid, "Question": v.get("question", "")[:150], | |
| "File": v.get("file_name", ""), "Answer": v.get("submitted_answer", ""), | |
| "Error": v.get("error", "")} | |
| for tid, v in cache.items() | |
| ] | |
| return pd.DataFrame(rows, columns=["Task ID", "Question", "File", "Answer", "Error"]) | |
| def run_agent(rerun_errors: bool, profile: gr.OAuthProfile | None): | |
| """Generator: answers every uncached question, streaming progress to the UI.""" | |
| if not profile: | |
| yield "Please log in with the Hugging Face button first.", None | |
| return | |
| try: | |
| questions = api.fetch_questions() | |
| except Exception as e: | |
| yield f"Could not fetch questions: {e}", None | |
| return | |
| try: | |
| agent = get_agent() | |
| except Exception as e: | |
| yield f"Could not build the agent (check MODEL_ID and API key secrets): {e}", None | |
| return | |
| cache = api.load_cache() | |
| todo = [ | |
| q for q in questions | |
| if q["task_id"] not in cache or (rerun_errors and cache[q["task_id"]].get("error")) | |
| ] | |
| yield f"{len(questions)} questions, {len(questions) - len(todo)} cached, running {len(todo)}...", cache_table(cache) | |
| for i, q in enumerate(todo, 1): | |
| tid, question, file_name = q["task_id"], q["question"], q.get("file_name", "") | |
| entry = {"question": question, "file_name": file_name} | |
| try: | |
| file_path = api.download_task_file(tid, file_name) | |
| entry["submitted_answer"] = agent(question, file_path) | |
| except Exception as e: | |
| traceback.print_exc() | |
| entry["submitted_answer"] = "" | |
| entry["error"] = f"{type(e).__name__}: {e}"[:300] | |
| cache[tid] = entry | |
| api.save_cache(cache) | |
| yield f"Done {i}/{len(todo)}. Last answer: {entry['submitted_answer']!r}", cache_table(cache) | |
| yield f"Finished. {len(cache)} answers cached. Review them, then press Submit.", cache_table(cache) | |
| def submit_answers(profile: gr.OAuthProfile | None): | |
| if not profile: | |
| return "Please log in with the Hugging Face button first.", None | |
| cache = api.load_cache() | |
| answers = [ | |
| {"task_id": tid, "submitted_answer": v.get("submitted_answer", "")} | |
| for tid, v in cache.items() if v.get("submitted_answer") | |
| ] | |
| if not answers: | |
| return "No cached answers yet. Run the agent first.", cache_table(cache) | |
| space_id = os.getenv("SPACE_ID", "") | |
| agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" | |
| try: | |
| result = api.submit(profile.username, agent_code, answers) | |
| except Exception as e: | |
| detail = getattr(getattr(e, "response", None), "text", "")[:500] | |
| return f"Submission failed: {e} {detail}", cache_table(cache) | |
| status = ( | |
| f"Submission successful!\nUser: {result.get('username')}\n" | |
| f"Score: {result.get('score', 'N/A')}% " | |
| f"({result.get('correct_count', '?')}/{result.get('total_attempted', '?')} correct)\n" | |
| f"Message: {result.get('message', '')}" | |
| ) | |
| return status, cache_table(cache) | |
| def clear_cache(): | |
| api.save_cache({}) | |
| return "Cache cleared.", cache_table({}) | |
| with gr.Blocks() as demo: | |
| gr.Markdown("# GAIA Agent: Final Assignment Runner") | |
| gr.Markdown( | |
| "1. Log in with Hugging Face. \n" | |
| "2. **Run agent** answers the questions and caches each answer as it goes. " | |
| "If it stops part-way, press it again: only missing answers are processed. \n" | |
| "3. Check the table, then **Submit** sends the cached answers for scoring." | |
| ) | |
| gr.LoginButton() | |
| with gr.Row(): | |
| rerun_errors = gr.Checkbox(label="Also re-run questions that errored", value=True) | |
| with gr.Row(): | |
| run_btn = gr.Button("Run agent", variant="primary") | |
| submit_btn = gr.Button("Submit cached answers") | |
| clear_btn = gr.Button("Clear cache") | |
| status = gr.Textbox(label="Status", lines=5, interactive=False) | |
| table = gr.DataFrame(label="Cached answers", wrap=True, value=cache_table(api.load_cache())) | |
| run_btn.click(run_agent, inputs=[rerun_errors], outputs=[status, table]) | |
| submit_btn.click(submit_answers, outputs=[status, table]) | |
| clear_btn.click(clear_cache, outputs=[status, table]) | |
| if __name__ == "__main__": | |
| demo.queue().launch(debug=True, share=False) | |