ttttim3's picture
Update agent code
90d0b3d verified
Raw History Blame Contribute Delete
3.55 kB
"""Gradio app for the HF Space (adapted from agents-course/Final_Assignment_Template).
The agent itself lives in agent.py / tools.py. It uses UF's NaviGator AI Toolkit
(OpenAI-compatible API, model gpt-oss-120b), so running it requires the Space secret
NAVIGATOR_TOOLKIT_API_KEY. The submitted answers were produced by running the same code
locally (run_all.py + submit.py).
"""
import os
import tempfile
from pathlib import Path
import gradio as gr
import pandas as pd
import requests
from agent import GaiaAgent
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
def run_and_submit_all(profile: gr.OAuthProfile | None):
space_id = os.getenv("SPACE_ID")
if not profile:
return "Please Login to Hugging Face with the button.", None
username = profile.username
if not os.getenv("NAVIGATOR_TOOLKIT_API_KEY"):
return "This Space has no NAVIGATOR_TOOLKIT_API_KEY secret configured, so the agent cannot run here.", None
agent = GaiaAgent()
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
questions = requests.get(f"{DEFAULT_API_URL}/questions", timeout=30).json()
files_dir = Path(tempfile.mkdtemp())
results_log, answers_payload = [], []
for item in questions:
task_id, question = item["task_id"], item["question"]
file_path = None
if item.get("file_name"):
r = requests.get(f"{DEFAULT_API_URL}/files/{task_id}", timeout=120)
if r.ok:
file_path = files_dir / item["file_name"]
file_path.write_bytes(r.content)
try:
answer = agent(question, str(file_path) if file_path else None)
except Exception as e:
answer = ""
print(f"Error on {task_id}: {e}")
answers_payload.append({"task_id": task_id, "submitted_answer": answer})
results_log.append({"Task ID": task_id, "Question": question, "Submitted Answer": answer})
submission = {"username": username, "agent_code": agent_code, "answers": answers_payload}
try:
r = requests.post(f"{DEFAULT_API_URL}/submit", json=submission, timeout=120)
r.raise_for_status()
d = r.json()
status = (
f"Submission Successful!\nUser: {d.get('username')}\n"
f"Overall Score: {d.get('score', 'N/A')}% ({d.get('correct_count', '?')}/{d.get('total_attempted', '?')} correct)\n"
f"Message: {d.get('message', '')}"
)
except Exception as e:
status = f"Submission Failed: {e}"
return status, pd.DataFrame(results_log)
with gr.Blocks() as demo:
gr.Markdown("# GAIA Agent (HF Agents Course, Unit 4)")
gr.Markdown(
"""
A smolagents **CodeAgent** driven by **gpt-oss-120b** (served by UF's NaviGator AI Toolkit).
Tools: web search, webpage reader, Wikipedia search / page (incl. historical revisions), file reader
(xlsx/csv/pdf/text), Python script runner, Whisper speech-to-text, vision model for images, YouTube transcripts.
See `agent.py` and `tools.py` for the implementation. Running requires the `NAVIGATOR_TOOLKIT_API_KEY` secret.
"""
)
gr.LoginButton()
run_button = gr.Button("Run Evaluation & Submit All Answers")
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
if __name__ == "__main__":
demo.launch(debug=True, share=False)