GAIA_Agent / app.py
nikhmr1235's picture
temporay change: run this task alone: 8e867cd7-cff9-4e6c-867a-ff5ddc2550be
af668b0 verified
"""
Main application file for the GAIA Agent evaluation on Hugging Face Spaces.
This script sets up and runs a Gradio web interface that allows users to
evaluate the performance of a ReAct-style agent against the GAIA benchmark
questions provided by the Hugging Face Agents course.
The application orchestrates the entire evaluation process:
1. Handles user authentication via Hugging Face OAuth.
2. Initializes the agent, tools (e.g., search, code execution, multi-modal),
and the LLM with API key rotation.
3. Fetches the official set of questions from the scoring server.
4. Runs the agent on each question, handling attachments and retries.
5. Submits the agent's answers back to the server for automated scoring.
6. Displays the final score and a detailed log of the agent's answers in
the Gradio interface.
"""
import requests
import os
import gradio as gr
import pandas as pd
import time
import re
from langchain_classic.agents import create_react_agent
from langchain_classic.tools import Tool
from tools import (
repl_tool,
get_travily_api_search_tool,
audio_transcriber_tool,
file_saver_tool,
create_gemini_multimodal_tool,
serpapi_search_instance,
wikipedia_search_tool2,
)
from llm_rotator import ApiKeyRotator
from agent import BasicAgent
from prompt import prompt_template
# --- Constants ---
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
def run_and_submit_all(profile: gr.OAuthProfile | None):
"""
Fetches all questions, runs the BasicAgent on them, submits all answers,
and displays the results.
"""
# --- Determine HF Space Runtime URL and Repo URL ---
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
if profile:
username = f"{profile.username}"
print(f"User logged in: {username}")
else:
print("User not logged in.")
return "Please Login to Hugging Face with the button.", None
api_url = DEFAULT_API_URL
questions_url = f"{api_url}/questions"
submit_url = f"{api_url}/submit"
google_api_keys_str = os.getenv("GOOGLE_API_KEYS")
if not google_api_keys_str:
print("Google API keys not found in environment variables.")
return (
"Google API keys not found. Please set GOOGLE_API_KEYS environment variable as a comma-separated string.",
None,
)
google_api_keys = [key.strip() for key in google_api_keys_str.split(",")]
print(f"Found {len(google_api_keys)} Google API keys.")
# The primary LLM for the agent's reasoning and planning.
gemini_model = "gemini-2.5-flash-lite"
agent_llm = ApiKeyRotator(
api_keys=google_api_keys, model=gemini_model, temperature=0, streaming=True
)
serp_api_key = os.getenv("SERP_API_KEY")
if not serp_api_key:
print("SerpAPI key not found in environment variables.")
return "SerpAPI key not found. Please set SERP_API_KEY environment variable.", None
print(f"Using SerpAPI key: {serp_api_key[:4]}... (truncated for security)")
tavily_api_key = os.getenv("TAVILY_API_KEY")
if not tavily_api_key:
print("Tavily API key not found in environment variables.")
return "Tavily API key not found. Please set TAVILY_API_KEY environment variable.", None
print(f"Using Tavily API key: {tavily_api_key[:4]}... (truncated for security)")
# Whitelist of trusted domains for Tavily Search to improve result consistency
trusted_domains = [
# General Encyclopedic & Factual
"wikipedia.org",
"britannica.com",
"wolfr.am", # WolframAlpha for computation/data
"guinnessworldrecords.com",
"nobelprize.org",
"olympics.com",
"ourworldindata.org",
# Sports Statistics (very important for this question set)
"baseball-reference.com",
"pro-football-reference.com",
"basketball-reference.com",
"sports-reference.com", # General portal
"the-sports.org",
# Music & Entertainment
"musicbrainz.org",
"discogs.com",
"allmusic.com",
"imdb.com",
"rottentomatoes.com",
"boxofficemojo.com",
# Science & Academia (for paper-based questions)
"arxiv.org", # For pre-print papers
"jstor.org",
"ncbi.nlm.nih.gov", # National Library of Medicine
"nasa.gov",
"universetoday.com", # Mentioned in one question
"libretexts.org", # Mentioned in one question
]
travily_api_search_tool = get_travily_api_search_tool(
tavily_api_key, include_domains=trusted_domains
)
gemini_multimodal_tool = create_gemini_multimodal_tool(agent_llm)
serpapi_Google_Search_tool = Tool(
name="serpapi_Google Search",
description='''
Performs a Google search using SerpApi to get current and detailed information from the web.
Use this for factual queries, general knowledge, recent events, or when TavilySearch might not be sufficient.
It can return rich results including answer boxes, knowledge graphs, and multiple organic search results.
Input should be a clear, concise search query string.
''',
func=serpapi_search_instance.search_google,
)
tools = [
repl_tool,
file_saver_tool,
audio_transcriber_tool,
travily_api_search_tool,
gemini_multimodal_tool,
wikipedia_search_tool2,
serpapi_Google_Search_tool,
]
# Create a ReAct agent
react_agent = create_react_agent(llm=agent_llm, tools=tools, prompt=prompt_template)
# 1. Instantiate Agent ( modify this part to create your agent)
try:
# max_iterations for complex multi-step reasoning
agent = BasicAgent(react_agent, tools, True, True, 30)
except Exception as e:
print(f"Error instantiating agent: {e}")
return f"Error initializing agent: {e}", None
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
print(agent_code)
# 2. Fetch 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:
print("Fetched questions list is empty.")
return "Fetched questions list is empty or invalid format.", None
print(f"Fetched {len(questions_data)} questions.")
except requests.exceptions.RequestException as e:
print(f"Error fetching questions: {e}")
return f"Error fetching questions: {e}", None
except requests.exceptions.JSONDecodeError as e:
print(f"Error decoding JSON response from questions endpoint: {e}")
print(f"Response text: {response.text[:500]}")
return f"Error decoding server response for questions: {e}", None
except Exception as e:
print(f"An unexpected error occurred fetching questions: {e}")
return f"An unexpected error occurred fetching questions: {e}", None
# 3. Run your Agent
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")
file_name = item.get("file_name") # Get the file_name if it exists
# Construct the question string that your LLM will see,
# including the attachment URL if present.
full_question_for_agent = question_text
if file_name:
attachment_url = f"https://agents-course-unit4-scoring.hf.space/files/{task_id}"
full_question_for_agent += (
f"\n\nAttachment '{file_name}' available at EXACT URL: {attachment_url}"
)
allowed_ids = {
"8e867cd7-cff9-4e6c-867a-ff5ddc2550be",
#"1f975693-876d-457b-a649-393859e79bf3",
#"cca530fc-4052-43b2-b130-b30968d8aa44",
#"a1e91b78-d3d8-4675-bb8d-62741b4b68a6",
#"3f57289b-8c60-48be-bd80-01f8099ca449",
#"cf106601-ab4f-4af9-b045-5295fe67b37d",
#"7bd855d8-463d-4ed5-93ca-5fe35145f733",
#"5a0c1adf-205e-4841-a666-7c3ef95def9d",
#"f918266a-b3e0-4914-865d-4faa564f1aef",
#"3cef3a44-215e-4aed-8e3b-b1e3f08063b7",
#"2d83110e-a098-4ebb-9987-066c06fa42d0",
}
if task_id not in allowed_ids:
continue
print(f"Running agent on task {task_id}: {full_question_for_agent}", flush=True)
try:
submitted_answer = agent(full_question_for_agent)
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,
}
)
print(f"sleep 61 seconds to avoid quota issues...", flush=True)
time.sleep(61) # Add a 61 sec delay before running the agent
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}",
}
)
if not answers_payload:
print("Agent did not produce any answers to submit.")
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
# 4. Prepare Submission
submission_data = {
"username": username.strip(),
"agent_code": agent_code,
"answers": answers_payload,
}
status_update =f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
print(status_update)
# 5. Submit
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
try:
response = requests.post(submit_url, json=submission_data, timeout=60)
response.raise_for_status()
result_data = response.json()
print(f"Submission response: {result_data}")
final_status = (
f"Submission Successful!\n"
f"User: {result_data.get('username')}\n"
f"Overall Score: {result_data.get('score', 'N/A')}% "
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
f"Message: {result_data.get('message', 'No message received.')}"
)
print("Submission successful.")
cleaned_final_status = re.sub(r'[^\x20-\x7E\n\r\t]+', '', final_status)
cleaned_final_status = cleaned_final_status.strip()
results_df = pd.DataFrame(results_log)
return cleaned_final_status, results_df
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]}"
status_message = f"Submission Failed: {error_detail}"
print(status_message)
results_df = pd.DataFrame(results_log)
return status_message, results_df
except requests.exceptions.Timeout:
status_message = "Submission Failed: The request timed out."
print(status_message)
results_df = pd.DataFrame(results_log)
return status_message, results_df
except requests.exceptions.RequestException as e:
status_message = f"Submission Failed: Network error - {e}"
print(status_message)
results_df = pd.DataFrame(results_log)
return status_message, results_df
except Exception as e:
status_message = f"An unexpected error occurred during submission: {e}"
print(status_message)
results_df = pd.DataFrame(results_log)
return status_message, results_df
# --- Build Gradio Interface using Blocks ---
with gr.Blocks() as demo:
gr.Markdown("# Basic Agent Evaluation Runner")
gr.Markdown(
"""
**Instructions:**
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
---
**Disclaimers:**
Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
"""
)
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)
space_host_startup = os.getenv("SPACE_HOST")
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
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 repo URLs if SPACE_ID is found
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)