Final_Assignment_Template / evaluation.py
tjrtm's picture
local
89c14ba
Raw History Blame
18.2 kB
import gradio as gr
from hf_agent import HuggingFaceAgent, SmolagentsGAIAAgent
import requests
import pandas as pd
import os
# --- Constants ---
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
# Detect if running on Hugging Face Spaces
ON_SPACES = os.environ.get("SPACE_ID") is not None
# Dummy profile for local development
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"""
submit_url = f"{api_url}/submit"
submission_data = {
"username": username.strip(),
"agent_code": agent_code,
"answers": answers
}
try:
response = requests.post(submit_url, json=submission_data, timeout=6000)
response.raise_for_status()
return response.json()
except Exception as e:
print(f"Error submitting answers: {e}")
return {"error": str(e)}
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")
# Initialize the smolagents-based agent
try:
agent = SmolagentsGAIAAgent()
print("Successfully initialized SmolagentsGAIAAgent")
except Exception as e:
print(f"Failed to initialize SmolagentsGAIAAgent: {e}")
# Fallback to the wrapper agent
try:
agent = HuggingFaceAgent()
print("Using HuggingFaceAgent wrapper as fallback")
except Exception as e2:
return f"Failed to initialize any agent: {e2}", None
# Fetch questions from the GAIA API
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...")
# Process each question
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:
# Run the agent on the question
answer = agent(question_text)
# Clean the answer for submission
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...")
# Submit answers to the API
result_data = submit_answers(api_url, username, agent_code, answers_payload)
if "error" in result_data:
return f"Submission Failed: {result_data['error']}", pd.DataFrame(results_log)
# Format the final status message
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:
# Try to use the new smolagents agent first
agent = SmolagentsGAIAAgent()
except Exception as e:
print(f"Failed to initialize SmolagentsGAIAAgent, using fallback: {e}")
# Fallback to wrapper agent
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
# Gradio Interface
with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {max-width: 900px !important;}") as demo:
gr.Markdown("""
# Smolagents GAIA Evaluation Agent
<span style='color:#555'>
- **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
</span>
""")
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("<span style='color:red'><b>Warning:</b> OAuth login and profile are only available on Hugging Face Spaces. Evaluation will use a dummy profile.</span>")
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:
# Use the request to get OAuth profile data
def run_evaluation_with_oauth(request: gr.Request):
# Create a profile-like object from request data
class RequestProfile:
def __init__(self, username):
self.username = username or "authenticated_user"
profile = RequestProfile(getattr(request, 'username', None))
return run_evaluation(profile)
eval_btn.click(run_evaluation_with_oauth, outputs=[status_output, results_table])
else:
# Use dummy profile for local development
eval_btn.click(lambda: run_evaluation(DummyProfile()), outputs=[status_output, results_table])
with gr.Tab("Local Models"):
gr.Markdown("""
## Local Model Support
Run the evaluation with models downloaded locally on your machine for:
- **Privacy**: No data sent to external APIs
- **Speed**: Faster inference (with proper hardware)
- **Offline**: Works without internet connection
- **Control**: Full control over model versions
""")
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
# Build command
cmd = [sys.executable, "download_models.py", "--model-size", size]
if token:
cmd.extend(["--token", token])
# Run download script
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)}"
download_btn.click(
download_models_interface,
inputs=[model_size, hf_token],
outputs=download_status
)
set_paths_btn.click(
set_model_paths_interface,
inputs=[llm_path, fallback_path, embedding_path],
outputs=download_status
)
gr.Markdown("""
### Command Line Usage
You can also download models via command line:
```bash
# Download light models (recommended)
python download_models.py --model-size light
# Download with HuggingFace token
python download_models.py --model-size medium --token hf_your_token
# See model size information
python download_models.py --list-sizes
# Download specific model
python download_models.py --custom-model microsoft/DialoGPT-small
```
### Requirements for Local Models
- **Memory**: 8GB+ RAM for light models, 16GB+ for medium, 64GB+ for full
- **Storage**: 20GB+ free space for light models
- **GPU**: Optional but recommended for faster inference
""")
with gr.Tab("About Smolagents"):
gr.Markdown("""
## About This Agent
This agent is built using the **Smolagents** framework, specifically designed for the GAIA benchmark:
### Key Features:
- **CodeAgent**: Uses a Thought-Action-Observation cycle for complex reasoning
- **Custom Tools**: Web search, article extraction, Wikipedia, calculator, file processing
- **Multi-step Reasoning**: Breaks down complex problems into manageable steps
- **Tool Selection**: Intelligently chooses the right tools for each task
- **Code Execution**: Can write and execute Python code for calculations
- **Real-time Information**: Access to current web information
- **Local & Remote Models**: Support for both local and cloud-based models
### Architecture:
- **Primary LLM**: Llama-3.3-70B-Instruct (with fallback to Zephyr-7B)
- **Framework**: Smolagents CodeAgent
- **Tools**: DuckDuckGo search, Wikipedia, Calculator, File processors
- **Execution**: Safe Python code execution environment
- **Deployment**: Local or remote model inference
### GAIA Optimization:
- Designed specifically for GAIA benchmark requirements
- Handles diverse question types from simple facts to complex multi-step problems
- Optimized for accuracy and precision in answers
- Robust error handling and tool selection
- Local model support for privacy and offline usage
**Source Code**: Available in this Hugging Face Space
""")
gr.Markdown("---")
gr.Markdown("<center><small>Powered by Smolagents and Hugging Face models. Optimized for GAIA benchmark evaluation.</small></center>")
if __name__ == "__main__":
demo.launch()