SeppoR's picture
Replace template with LangGraph GAIA agent (HF/Groq/Ollama backends)
5910b8a verified
Raw
History Blame Contribute Delete
5.84 kB
"""Gradio Space app for the HF Agents Course final assignment.
Mirrors the official template's flow:
1. Hugging Face OAuth login (identifies your submission).
2. Fetch the evaluation questions from the scoring API.
3. Run your agent over every question.
4. Submit answers + a link to this Space's code for scoring.
Set your HF Inference token as the `HF_TOKEN` Space secret so the agent can
call the model.
"""
from __future__ import annotations
import os
import gradio as gr
import pandas as pd
import requests
try:
from dotenv import load_dotenv
load_dotenv() # load HF_TOKEN etc. from a local .env when running locally
except ImportError:
pass
from agent import GaiaAgent
# --- Constants --------------------------------------------------------------
DEFAULT_API_URL = os.getenv(
"GAIA_API_URL", "https://agents-course-unit4-scoring.hf.space"
)
QUESTIONS_URL = f"{DEFAULT_API_URL}/questions"
SUBMIT_URL = f"{DEFAULT_API_URL}/submit"
def run_and_submit_all(profile: gr.OAuthProfile | None):
"""Fetch all questions, run the agent on each, and submit the answers.
Returns a status string and a results dataframe for display.
"""
# 1. Resolve the logged-in HF username.
if profile is None:
return "Please log in to Hugging Face using the button above.", None
username = profile.username
print(f"User logged in: {username}")
# 2. Derive the public code link for this Space (used for verification).
space_id = os.getenv("SPACE_ID")
if space_id:
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
else:
agent_code = "https://huggingface.co/spaces/local/run/tree/main"
print(f"Agent code link: {agent_code}")
# 3. Instantiate the agent.
try:
agent = GaiaAgent()
except Exception as exc: # noqa: BLE001
return f"Error initializing agent: {exc}", None
# 4. Fetch the questions.
try:
resp = requests.get(QUESTIONS_URL, timeout=30)
resp.raise_for_status()
questions = resp.json()
except Exception as exc: # noqa: BLE001
return f"Error fetching questions: {exc}", None
if not questions:
return "Fetched questions list is empty.", None
print(f"Fetched {len(questions)} questions.")
# 5. Run the agent over every question.
results_log = []
answers_payload = []
for item in questions:
task_id = item.get("task_id")
question_text = item.get("question")
if not task_id or question_text is None:
continue
print(f"Running task {task_id}...")
try:
submitted = agent(question_text, task_id, item.get("file_name"))
except Exception as exc: # noqa: BLE001
submitted = f"AGENT ERROR: {exc}"
answers_payload.append(
{"task_id": task_id, "submitted_answer": submitted}
)
results_log.append(
{
"Task ID": task_id,
"Question": question_text,
"Submitted Answer": submitted,
}
)
if not answers_payload:
return "Agent produced no answers to submit.", pd.DataFrame(results_log)
# 6. Submit to the scoring API.
submission = {
"username": username.strip(),
"agent_code": agent_code,
"answers": answers_payload,
}
print(f"Submitting {len(answers_payload)} answers for {username}...")
try:
resp = requests.post(SUBMIT_URL, json=submission, timeout=120)
resp.raise_for_status()
data = resp.json()
except requests.exceptions.HTTPError as exc:
detail = ""
try:
detail = exc.response.json().get("detail", "")
except Exception: # noqa: BLE001
detail = exc.response.text[:500] if exc.response is not None else ""
return f"Submission failed: {detail or exc}", pd.DataFrame(results_log)
except Exception as exc: # noqa: BLE001
return f"Submission error: {exc}", pd.DataFrame(results_log)
status = (
"Submission Successful!\n"
f"User: {data.get('username')}\n"
f"Overall Score: {data.get('score', 'N/A')}% "
f"({data.get('correct_count', '?')}/"
f"{data.get('total_attempted', '?')} correct)\n"
f"Message: {data.get('message', '')}"
)
return status, pd.DataFrame(results_log)
# --- UI ---------------------------------------------------------------------
with gr.Blocks(title="GAIA Final Agent") as demo:
gr.Markdown("# GAIA Final Assignment — Agent Runner")
gr.Markdown(
"""
**How to use**
1. Log in to your Hugging Face account with the button below.
2. Make sure the `HF_TOKEN` secret is set in this Space (Settings →
Variables and secrets) so the agent can call the model.
3. Click **Run Evaluation & Submit All Answers**.
The agent fetches all questions, answers each one, and submits the
results for scoring. Running the full set can take several minutes.
"""
)
gr.LoginButton()
run_button = gr.Button("Run Evaluation & Submit All Answers", variant="primary")
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__":
print("-" * 30 + " App Starting " + "-" * 30)
space_id = os.getenv("SPACE_ID")
if space_id:
print(f"Space ID: {space_id}")
print(f"Code: https://huggingface.co/spaces/{space_id}/tree/main")
else:
print("SPACE_ID not set (running locally).")
demo.launch(debug=True, share=False)