File size: 3,546 Bytes
90d0b3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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)