import os
import requests
import gradio as gr
from smolagents import CodeAgent, InferenceClientModel, DuckDuckGoSearchTool, tool
from markdownify import markdownify

--- The API the course gives us ---

DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"

--- A small tool so the agent can read a web page ---

@tool
def visit_webpage(url: str) -> str:
"""Visit a webpage and return its text content.

Args:
    url: The full URL of the page to read.
"""
try:
    response = requests.get(url, timeout=20)
    response.raise_for_status()
    return markdownify(response.text).strip()[:10000]
except Exception as e:
    return f"Error visiting {url}: {e}"

--- This is the "brain" ---

class BasicAgent:
def init(self):
print("Agent ready.")
# The model that thinks. Uses your Space's free HF token automatically.
model = InferenceClientModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct")
self.agent = CodeAgent(
tools=[DuckDuckGoSearchTool(), visit_webpage],
model=model,
add_base_tools=True,
)

def __call__(self, question: str) -> str:
    # Force the agent to give ONLY the final answer, no extra words.
    prompt = (
        f"{question}\n\n"
        "Answer with ONLY the final answer. No explanation, no extra words, "
        "no units unless asked. If it's a list, separate with commas."
    )
    answer = self.agent.run(prompt)
    return str(answer).strip()

--- The part that submits your answers (do not change) ---

def run_and_submit_all(profile: gr.OAuthProfile | None):
if profile is None:
return "Please log in to Hugging Face using the button above.", None
username = profile.username

space_id = os.getenv("SPACE_ID")
questions_url = f"{DEFAULT_API_URL}/questions"
submit_url = f"{DEFAULT_API_URL}/submit"
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"

try:
    agent = BasicAgent()
except Exception as e:
    return f"Error starting agent: {e}", None

questions = requests.get(questions_url, timeout=30).json()

results, payload = [], []
for item in questions:
    task_id = item.get("task_id")
    question = item.get("question")
    if not task_id or question is None:
        continue
    try:
        answer = agent(question)
    except Exception as e:
        answer = f"AGENT ERROR: {e}"
    payload.append({"task_id": task_id, "submitted_answer": answer})
    results.append({"Task ID": task_id, "Question": question, "Answer": answer})

submission = {"username": username, "agent_code": agent_code, "answers": payload}
response = requests.post(submit_url, json=submission, timeout=120).json()

status = (
    f"Submission Successful!\n"
    f"User: {response.get('username')}\n"
    f"Score: {response.get('score')}% "
    f"({response.get('correct_count')}/{response.get('total_attempted')} correct)\n"
    f"Message: {response.get('message')}"
)
return status, gr.DataFrame(results)

--- The simple web page with the button ---

with gr.Blocks() as demo:
gr.Markdown("# My GAIA Agent โ€” Final Assignment")
gr.LoginButton()
run_button = gr.Button("Run Evaluation & Submit All Answers")
status_box = gr.Textbox(label="Result", lines=5, interactive=False)
table = gr.DataFrame(label="Questions and Answers")
run_button.click(fn=run_and_submit_all, outputs=[status_box, table])

if name == "main":
demo.launch()

Ready to merge
This branch is ready to get merged automatically.

Sign up or log in to comment