import gradio as gr
from hf_agent import HuggingFaceAgent, SmolagentsGAIAAgent
import requests
import pandas as pd
import os
import time
import json
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
ON_SPACES = os.environ.get("SPACE_ID") is not None
class DummyProfile:
def __init__(self, username="local_user"):
self.username = username
def fetch_questions(api_url):
"""Fetch GAIA evaluation questions from the API"""
questions_url = f"{api_url}/questions"
try:
response = requests.get(questions_url, timeout=15)
response.raise_for_status()
return response.json()
except Exception as e:
print(f"Error fetching questions: {e}")
return []
def submit_answers(api_url, username, agent_code, answers):
"""Submit answers to the GAIA evaluation API with retry logic"""
submit_url = f"{api_url}/submit"
submission_data = {
"username": username.strip(),
"agent_code": agent_code,
"answers": answers
}
max_retries = 3
retry_delay = 5
for attempt in range(max_retries):
try:
print(f"Submission attempt {attempt + 1}/{max_retries}")
print(f"Submitting to: {submit_url}")
print(f"Username: {username}")
print(f"Number of answers: {len(answers)}")
headers = {
'Content-Type': 'application/json',
'User-Agent': 'Smolagents-GAIA-Agent/1.0'
}
response = requests.post(
submit_url,
json=submission_data,
headers=headers,
timeout=60
)
print(f"Response status: {response.status_code}")
print(f"Response headers: {dict(response.headers)}")
if response.status_code == 200:
result = response.json()
print(f"Submission successful: {result}")
return result
else:
print(f"Server returned status {response.status_code}")
print(f"Response text: {response.text}")
response.raise_for_status()
except requests.exceptions.Timeout:
print(f"Timeout on attempt {attempt + 1}")
if attempt < max_retries - 1:
print(f"Retrying in {retry_delay} seconds...")
time.sleep(retry_delay)
continue
else:
return {"error": "Request timed out after multiple attempts"}
except requests.exceptions.ConnectionError:
print(f"Connection error on attempt {attempt + 1}")
if attempt < max_retries - 1:
print(f"Retrying in {retry_delay} seconds...")
time.sleep(retry_delay)
continue
else:
return {"error": "Unable to connect to server after multiple attempts"}
except requests.exceptions.HTTPError as e:
if response.status_code >= 500:
print(f"Server error {response.status_code} on attempt {attempt + 1}")
if attempt < max_retries - 1:
print(f"Retrying in {retry_delay} seconds...")
time.sleep(retry_delay)
retry_delay *= 2
continue
else:
return {"error": f"Server error {response.status_code}: {response.text}"}
else:
print(f"Client error {response.status_code}: {response.text}")
return {"error": f"Client error {response.status_code}: {response.text}"}
except Exception as e:
print(f"Unexpected error on attempt {attempt + 1}: {e}")
if attempt < max_retries - 1:
print(f"Retrying in {retry_delay} seconds...")
time.sleep(retry_delay)
continue
else:
return {"error": f"Unexpected error: {str(e)}"}
return {"error": "All retry attempts failed"}
def save_results_locally(username, answers_payload, results_log):
"""Save evaluation results locally when server submission fails"""
timestamp = pd.Timestamp.now().strftime("%Y%m%d_%H%M%S")
filename = f"gaia_evaluation_{username}_{timestamp}.json"
local_results = {
"timestamp": timestamp,
"username": username,
"agent_type": "Smolagents GAIA Agent",
"total_questions": len(answers_payload),
"answers": answers_payload,
"detailed_log": results_log
}
try:
with open(filename, 'w') as f:
json.dump(local_results, f, indent=2, default=str)
print(f"Results saved locally to: {filename}")
return filename
except Exception as e:
print(f"Failed to save results locally: {e}")
return None
def run_evaluation(profile):
"""Run the full GAIA evaluation using the smolagents-based agent"""
api_url = DEFAULT_API_URL
space_id = "tjrtm"
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
if not profile:
return "Please login to Hugging Face.", None
username = getattr(profile, "username", "local_user")
try:
agent = SmolagentsGAIAAgent()
print("Successfully initialized SmolagentsGAIAAgent")
except Exception as e:
print(f"Failed to initialize SmolagentsGAIAAgent: {e}")
try:
agent = HuggingFaceAgent()
print("Using HuggingFaceAgent wrapper as fallback")
except Exception as e2:
return f"Failed to initialize any agent: {e2}", None
questions = fetch_questions(api_url)
if not questions:
return "No questions fetched from server. Please check your connection.", None
answers_payload = []
results_log = []
print(f"Processing {len(questions)} GAIA questions...")
for i, item in enumerate(questions, 1):
task_id = item.get("task_id")
question_text = item.get("question")
if not task_id or question_text is None:
print(f"Skipping invalid question {i}")
continue
print(f"Processing question {i}/{len(questions)}: {task_id}")
try:
answer = agent(question_text)
if isinstance(answer, str):
cleaned_answer = answer.strip()
else:
cleaned_answer = str(answer).strip()
answers_payload.append({
"task_id": task_id,
"submitted_answer": cleaned_answer
})
results_log.append({
"Task ID": task_id,
"Question": question_text[:100] + "..." if len(question_text) > 100 else question_text,
"Submitted Answer": cleaned_answer[:200] + "..." if len(cleaned_answer) > 200 else cleaned_answer
})
print(f"Successfully processed question {task_id}")
except Exception as e:
error_msg = f"AGENT ERROR: {str(e)}"
print(f"Error processing question {task_id}: {e}")
results_log.append({
"Task ID": task_id,
"Question": question_text[:100] + "..." if len(question_text) > 100 else question_text,
"Submitted Answer": error_msg
})
if not answers_payload:
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
print(f"Submitting {len(answers_payload)} answers to GAIA API...")
result_data = submit_answers(api_url, username, agent_code, answers_payload)
if "error" in result_data:
save_results_locally(username, answers_payload, results_log)
return f"Submission Failed: {result_data['error']}", pd.DataFrame(results_log)
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.')}\n\n"
f"Agent: Smolagents-based GAIA Agent\n"
f"Questions Processed: {len(questions)}\n"
f"Answers Submitted: {len(answers_payload)}"
)
return final_status, pd.DataFrame(results_log)
def agent_qa(question, files):
"""Handle individual Q&A with the smolagents agent"""
try:
agent = SmolagentsGAIAAgent()
except Exception as e:
print(f"Failed to initialize SmolagentsGAIAAgent, using fallback: {e}")
agent = HuggingFaceAgent()
try:
answer = agent(question, files)
return answer
except Exception as e:
return f"Error processing your question: {str(e)}. Please try rephrasing your question."
def file_preview(files):
"""Generate preview widgets for uploaded files"""
previews = []
for file in files or []:
name = file.name
ext = name.split('.')[-1].lower()
if ext in ["png", "jpg", "jpeg"]:
previews.append(gr.Image(value=file, label=name))
else:
previews.append(gr.Textbox(value=f"Uploaded: {name}", label=name))
return previews
with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {max-width: 900px !important;}") as demo:
gr.Markdown("""
- **Smolagents CodeAgent** - Advanced reasoning with code execution
- **Real-time web search** with DuckDuckGo integration
- **Article content extraction** - reads full articles from search results
- **Intelligent synthesis** - combines information from multiple sources
- **Custom tools** - Wikipedia search, calculator, file processing
- **GAIA benchmark optimized** - designed for complex multi-step reasoning
- Handles all question types and file attachments
- Beautiful, modern UI
- Robust agentic flows for GAIA evaluation
""")
gr.Markdown("""
**Instructions:**
1. Login with your Hugging Face account (required for evaluation submission).
2. Ask any question, optionally upload files (PDF, CSV, TXT, DOCX, images).
3. **Web Search**: Ask for latest news, current information, or real-time data.
4. **Article Extraction**: Use keywords like "detailed", "full analysis", or "comprehensive" for in-depth article reading.
5. **Calculations**: Ask math questions and the agent will use its calculator tool.
6. **Wikipedia**: Ask factual questions and the agent will search Wikipedia.
7. Or run the full GAIA evaluation and submit your answers.
**Search Tips:**
- For quick results: "brief news about X" or "quick summary of Y"
- For detailed analysis: "comprehensive report on X" or "detailed analysis of Y"
- For news: "latest news in [location]" automatically extracts article content
- For calculations: "calculate the area of a circle with radius 5"
- For facts: "what is the capital of France"
""")
if not ON_SPACES:
gr.Markdown("Warning: OAuth login and profile are only available on Hugging Face Spaces. Evaluation will use a dummy profile.")
gr.LoginButton(visible=ON_SPACES)
with gr.Tab("Ask a Question"):
with gr.Row():
question = gr.Textbox(
label="Your Question",
lines=2,
scale=3,
placeholder="Ask me anything! I can search the web, do calculations, and process files..."
)
files = gr.File(
label="Attach Files",
file_types=[".txt", ".pdf", ".csv", ".docx", ".xlsx", ".png", ".jpg", ".jpeg"],
file_count="multiple",
scale=2
)
file_previews = gr.Group()
answer = gr.Textbox(label="Agent Answer", lines=8)
ask_btn = gr.Button("Get Answer", variant="primary")
ask_btn.click(agent_qa, inputs=[question, files], outputs=answer)
with gr.Tab("GAIA Evaluation"):
gr.Markdown("""
**GAIA Benchmark Evaluation**
This will run the full GAIA evaluation using the smolagents-based agent:
- Fetch all GAIA questions from the official API
- Process each question using the CodeAgent with tools
- Submit answers for scoring
- Display results and performance metrics
**Note**: This may take several minutes to complete as the agent processes complex multi-step questions.
""")
status_output = gr.Textbox(
label="Run Status / Submission Result",
lines=8,
interactive=False,
placeholder="Click 'Run Evaluation' to start the GAIA benchmark test..."
)
results_table = gr.DataFrame(
label="Questions and Agent Answers",
wrap=True,
headers=["Task ID", "Question", "Submitted Answer"]
)
eval_btn = gr.Button("Run Evaluation & Submit All Answers", variant="primary", size="lg")
if ON_SPACES:
def run_evaluation_with_oauth(request: gr.Request):
class RequestProfile:
def __init__(self, username):
self.username = username or "tjrtm"
profile = RequestProfile(getattr(request, 'username', None))
return run_evaluation(profile)
eval_btn.click(run_evaluation_with_oauth, outputs=[status_output, results_table])
else:
eval_btn.click(lambda: run_evaluation(DummyProfile()), outputs=[status_output, results_table])
with gr.Tab("Model Configuration"):
gr.Markdown("""
Choose your preferred model strategy for the GAIA evaluation:
""")
strategy_selector = gr.Radio(
choices=[
("Local Models", "local"),
("Remote (HuggingFace)", "remote"),
("Auto Select", "auto")
],
value="local",
label="Model Strategy",
info="Select which type of models to use for inference"
)
with gr.Tab("Local Models"):
gr.Markdown("""
Run with models downloaded locally for privacy and offline usage:
""")
with gr.Row():
with gr.Column():
gr.Markdown("### Quick Setup")
model_size = gr.Radio(
choices=["light", "medium", "full"],
value="light",
label="Model Size",
info="Light: ~20GB, Medium: ~18GB, Full: ~155GB"
)
hf_token = gr.Textbox(
label="HuggingFace Token (optional)",
placeholder="hf_...",
type="password",
info="Required for some gated models"
)
download_btn = gr.Button("Download Models", variant="primary")
with gr.Column():
gr.Markdown("### Manual Setup")
llm_path = gr.Textbox(
label="LLM Model Path",
placeholder="./models/Llama-3.2-3B-Instruct",
info="Path to your local LLM"
)
fallback_path = gr.Textbox(
label="Fallback Model Path",
placeholder="./models/Qwen2.5-7B-Instruct",
info="Path to your fallback model"
)
embedding_path = gr.Textbox(
label="Embedding Model Path",
placeholder="./models/all-MiniLM-L6-v2",
info="Path to your embedding model"
)
set_paths_btn = gr.Button("Set Model Paths", variant="secondary")
download_status = gr.Textbox(
label="Status",
interactive=False,
lines=10
)
def download_models_interface(size, token):
try:
import subprocess
import sys
cmd = [sys.executable, "download_models.py", "--model-size", size]
if token:
cmd.extend(["--token", token])
result = subprocess.run(
cmd,
capture_output=True,
text=True,
cwd="."
)
if result.returncode == 0:
return f" Successfully downloaded {size} models!\n\n{result.stdout}"
else:
return f" Download failed:\n{result.stderr}\n{result.stdout}"
except Exception as e:
return f" Error running download script: {str(e)}"
def set_model_paths_interface(llm, fallback, embedding):
try:
from config import set_local_model_paths, set_model_strategy
paths_set = []
if llm and os.path.exists(llm):
paths_set.append(f"LLM: {llm}")
if fallback and os.path.exists(fallback):
paths_set.append(f"Fallback: {fallback}")
if embedding and os.path.exists(embedding):
paths_set.append(f"Embedding: {embedding}")
if paths_set:
set_local_model_paths(llm, fallback, embedding)
set_model_strategy("local")
return f" Local model paths updated:\n" + "\n".join(paths_set) + "\n\nRestart the application to use local models."
else:
return " No valid model paths found. Please check that the directories exist."
except Exception as e:
return f" Error setting model paths: {str(e)}"
def set_strategy_interface(strategy):
try:
from config import set_model_strategy
set_model_strategy(strategy)
return f" Model strategy set to: {strategy}\n\nRestart the application to apply changes."
except Exception as e:
return f" Error setting strategy: {str(e)}"
download_btn.click(
fn=download_models_interface,
inputs=[model_size, hf_token],
outputs=download_status
)
set_paths_btn.click(
fn=set_model_paths_interface,
inputs=[llm_path, fallback_path, embedding_path],
outputs=download_status
)
strategy_selector.change(
fn=set_strategy_interface,
inputs=strategy_selector,
outputs=download_status
)
if __name__ == "__main__":
demo.launch()