Spaces:
Sleeping
Sleeping
File size: 5,096 Bytes
281882c 10e9b7d 281882c 10e9b7d 3c4371f 10e9b7d 281882c 31243f4 281882c 31243f4 281882c eccf8e4 281882c 7d65c66 281882c 31243f4 281882c 31243f4 281882c e80aab9 281882c 7d65c66 281882c e80aab9 281882c e80aab9 281882c e80aab9 281882c e80aab9 281882c e80aab9 281882c | 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 | """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)
|