jesusgj
Modified files
423cd4c
raw
history blame
8.88 kB
import os
import gradio as gr
import requests
import pandas as pd
from agent import initialize_agent # Import the agent initialization function
# --- Constants ---
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
# --- Helper Functions ---
def _fetch_questions(api_url: str) -> list:
"""Fetches evaluation questions from the API."""
questions_url = f"{api_url}/questions"
print(f"Fetching questions from: {questions_url}")
try:
response = requests.get(questions_url, timeout=15)
response.raise_for_status()
questions_data = response.json()
if not questions_data:
raise ValueError("Fetched questions list is empty or invalid format.")
print(f"Fetched {len(questions_data)} questions.")
return questions_data
except requests.exceptions.RequestException as e:
raise RuntimeError(f"Error fetching questions: {e}") from e
except requests.exceptions.JSONDecodeError as e:
raise RuntimeError(f"Error decoding JSON response from questions endpoint: {e}. Response: {response.text[:500]}") from e
except Exception as e:
raise RuntimeError(f"An unexpected error occurred fetching questions: {e}") from e
def _run_agent_on_questions(agent, questions_data: list) -> tuple[list, list]:
"""Runs the agent on each question and collects answers and logs."""
results_log = []
answers_payload = []
print(f"Running agent on {len(questions_data)} questions...")
for item in questions_data:
task_id = item.get("task_id")
question_text = item.get("question")
if not task_id or question_text is None:
print(f"Skipping item with missing task_id or question: {item}")
continue
try:
submitted_answer = agent(question_text)
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
except Exception as e:
print(f"Error running agent on task {task_id}: {e}")
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
return answers_payload, results_log
def _submit_answers(api_url: str, username: str, agent_code_url: str, answers_payload: list) -> dict:
"""Submits the agent's answers to the evaluation API."""
submit_url = f"{api_url}/submit"
submission_data = {"username": username.strip(), "agent_code": agent_code_url, "answers": answers_payload}
print(f"Submitting {len(answers_payload)} answers for user '{username}' to: {submit_url}")
try:
response = requests.post(submit_url, json=submission_data, timeout=60)
response.raise_for_status()
return response.json()
except requests.exceptions.HTTPError as e:
error_detail = f"Server responded with status {e.response.status_code}."
try:
error_json = e.response.json()
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
except requests.exceptions.JSONDecodeError:
error_detail += f" Response: {e.response.text[:500]}"
raise RuntimeError(f"Submission Failed: {error_detail}") from e
except requests.exceptions.Timeout:
raise RuntimeError("Submission Failed: The request timed out.") from e
except requests.exceptions.RequestException as e:
raise RuntimeError(f"Submission Failed: Network error - {e}") from e
except Exception as e:
raise RuntimeError(f"An unexpected error occurred during submission: {e}") from e
# --- Main Gradio Function ---
def run_and_submit_all(profile: gr.OAuthProfile | None):
"""
Orchestrates the fetching of questions, running the agent, and submitting answers.
"""
username = None
if profile:
username = profile.username
print(f"User logged in: {username}")
else:
print("User not logged in.")
return "Please Login to Hugging Face with the button.", None
if not username:
return "Hugging Face username not found. Please ensure you are logged in.", None
space_id = os.getenv("SPACE_ID")
if not space_id:
print("SPACE_ID environment variable not found. Cannot determine agent_code URL.")
return "Error: SPACE_ID not set. Cannot determine agent_code URL.", None
agent_code_url = f"https://huggingface.co/spaces/{space_id}/tree/main"
status_message = ""
results_df = pd.DataFrame()
try:
# 1. Instantiate Agent
print("Initializing agent...")
agent = initialize_agent()
if agent is None:
raise RuntimeError("Agent initialization failed. Check agent.py for details.")
print("Agent initialized successfully.")
# 2. Fetch Questions
questions_data = _fetch_questions(DEFAULT_API_URL)
# 3. Run Agent on Questions
answers_payload, results_log = _run_agent_on_questions(agent, questions_data)
if not answers_payload:
status_message = "Agent did not produce any answers to submit."
return status_message, pd.DataFrame(results_log)
# 4. Submit Answers
submission_result = _submit_answers(DEFAULT_API_URL, username, agent_code_url, answers_payload)
final_status = (
f"Submission Successful!\n"
f"User: {submission_result.get('username')}\n"
f"Overall Score: {submission_result.get('score', 'N/A')}% "
f"({submission_result.get('correct_count', '?')}/{submission_result.get('total_attempted', '?')} correct)\n"
f"Message: {submission_result.get('message', 'No message received.')}"
)
status_message = final_status
results_df = pd.DataFrame(results_log)
except RuntimeError as e:
status_message = f"Operation Failed: {e}"
print(status_message)
# If an error occurs during agent run, results_log might be partially filled
# Ensure results_df is created even if answers_payload is empty due to early error
if 'results_log' in locals():
results_df = pd.DataFrame(results_log)
else:
results_df = pd.DataFrame([{"Status": "Error", "Details": str(e)}])
except Exception as e:
status_message = f"An unexpected critical error occurred: {e}"
print(status_message)
results_df = pd.DataFrame([{"Status": "Critical Error", "Details": str(e)}])
return status_message, results_df
# --- Gradio Interface Definition ---
with gr.Blocks() as demo:
gr.Markdown("# GAIA Benchmark Evaluation with smolagent")
gr.Markdown(
"""
**Instructions:**
1. Clone this Space and modify `agent.py` to define your agent's logic, tools, and necessary packages.
2. Log in to your Hugging Face account using the button below. Your HF username will be used for submission.
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see your score.
---
**Important Notes:**
* The evaluation process can take some time as the agent processes all questions.
* This Space provides a basic setup. You are encouraged to develop a more robust solution (e.g., caching answers, asynchronous processing) for production use.
"""
)
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__":
print("\n" + "-"*30 + " App Starting " + "-"*30)
# Check for SPACE_HOST and SPACE_ID at startup for information
space_host_startup = os.getenv("SPACE_HOST")
space_id_startup = os.getenv("SPACE_ID")
if space_host_startup:
print(f"✅ SPACE_HOST found: {space_host_startup}")
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
else:
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
if space_id_startup:
print(f"✅ SPACE_ID found: {space_id_startup}")
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
else:
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
print("-"*(60 + len(" App Starting ")) + "\n")
print("Launching Gradio Interface for Basic Agent Evaluation...")
demo.launch(debug=True, share=False)