tjrtm's picture
sync
097318b
|
Raw History Blame Contribute Delete
22.2 kB
---
title: Smolagents GAIA Evaluation Agent
colorFrom: green
colorTo: blue
sdk: gradio
sdk_version: 5.25.2
app_file: evaluation.py
pinned: false
hf_oauth: true
# optional, default duration is 8 hours/480 minutes. Max duration is 30 days/43200 minutes.
hf_oauth_expiration_minutes: 480
---
# Smolagents GAIA Evaluation Agent
A robust, agentic AI assistant built with the **Smolagents framework** specifically for the GAIA benchmark. Features a CodeAgent with advanced reasoning capabilities, multi-step problem solving, and intelligent tool usage.
**IMPORTANT**: This application uses **ONLY HuggingFace models** (local or remote via Inference API). All other model providers (OpenAI, Ollama, etc.) have been removed for compliance and reliability.
### Supported Model Strategies
- βœ… **Remote**: HuggingFace Inference API (default, free, recommended)
- βœ… **Local**: Downloaded HuggingFace Transformers models (offline)
- βœ… **Local Light**: Lighter HuggingFace models (reduced memory)
- βœ… **Auto**: Auto-select between local and remote HuggingFace
### NOT Supported (Removed)
- ❌ OpenAI API
- ❌ Ollama server
- ❌ Anthropic/Claude
- ❌ Any non-HuggingFace providers
## Key Features
### Smolagents Architecture
- **CodeAgent**: Uses Thought-Action-Observation cycle for complex reasoning
- **Custom Tools**: Web search, Wikipedia, calculator, file processing, article extraction
- **Code Execution**: Safe Python environment for calculations and data processing
- **Multi-step Reasoning**: Breaks down complex problems into manageable steps
- **Tool Selection**: Intelligently chooses the right tools for each task
### GAIA Benchmark Optimization
- **Designed for GAIA**: Optimized specifically for GAIA evaluation requirements
- **Diverse Task Handling**: Simple facts to complex multi-step problems
- **Accuracy Focus**: Precise answers with exact-match scoring compatibility
- **Robustness**: Handles diverse, real-world scenarios across domains
### Capabilities
- **Real-time Web Search**: DuckDuckGo integration with article extraction
- **File Processing**: PDF, CSV, TXT, DOCX, XLSX, images
- **Mathematical Calculations**: Built-in calculator with safe evaluation
- **Wikipedia Search**: Factual information retrieval
- **Article Extraction**: Full content reading from web sources
- **Multi-modal**: Text and image file support
## Technical Architecture
### Models (2025 Updated - HuggingFace Exclusive, Ungated)
- **Primary LLM**: `mistralai/Mistral-7B-Instruct-v0.2` - Free, ungated, Apache 2.0 license, 3.2M+ downloads/month
- **Fallback LLM**: `HuggingFaceH4/zephyr-7b-beta` - Free, ungated, MIT license, reliable performance
- **Embedding Model**: `sentence-transformers/all-MiniLM-L6-v2` - Free, ungated, efficient embeddings
- **Framework**: Smolagents CodeAgent with custom tools
- **Default Strategy**: Remote (HuggingFace Serverless Inference API)
- **Access**: NO approval required - all models are openly accessible
- **API Endpoint**: `https://router.huggingface.co/hf-inference` - FORCED to HuggingFace infrastructure only (no external providers)
### Tools
1. **Web Search Tool**: DuckDuckGo-based real-time information retrieval
2. **Article Extractor**: Full content extraction from web articles
3. **Wikipedia Search**: Factual information from Wikipedia
4. **Calculator**: Safe mathematical evaluation
5. **File Processor**: Multi-format file content extraction
6. **RAG Search**: Vector-based knowledge retrieval (expandable)
### Safety & Security
- Sandboxed code execution environment
- Input validation and sanitization
- Safe mathematical expression evaluation
- Rate limiting for web requests
## Setup Instructions
### For Hugging Face Spaces
1. **Clone this Space** or upload required files:
- `evaluation.py` - Main Gradio interface (required)
- `hf_agent.py` - Smolagents-based agent implementation (required)
- `config.py` - Configuration and model settings (required)
- `requirements.txt` - Dependencies including smolagents (required)
- `README.md` - This documentation (required)
- `download_models.py` - Local model downloader (optional, for local mode)
- `local_config.json` - Configuration file (optional, has defaults)
2. **Environment Variables** (recommended):
- `HF_TOKEN` - Hugging Face API token for Inference API access
- Set in Space settings β†’ Variables β†’ New Secret
- Get your token from: https://huggingface.co/settings/tokens
- Required for accessing HuggingFace models via Inference API
3. **Dependencies** (automatically installed from requirements.txt):
- `smolagents>=0.5.0` - Core agent framework
- `transformers>=4.36.0` - Model loading
- `gradio>=4.0.0` - UI framework
- `langchain>=0.1.0` + `langchain-core`, `langchain-text-splitters` - RAG components (updated 2025)
- `torch>=2.0.0` - PyTorch for local models (optional)
- Plus web scraping (ddgs, wikipedia, newspaper3k) and file processing libraries (pdfplumber, python-docx, Pillow)
### Local Development
#### Quick Start (Remote Models)
```bash
# Clone the repository
git clone <repository-url>
cd gaia-smolagents-agent
# Install dependencies
pip install -r requirements.txt
# Set environment variables
export HF_TOKEN="your_hugging_face_token"
# Run the application
python evaluation.py
```
#### Local Models Setup
```bash
# Install dependencies with local model support
pip install -r requirements.txt
# Download light models (recommended for most users)
python download_models.py --model-size light
# Or download medium models for better performance
python download_models.py --model-size medium --token hf_your_token
# Run with local models
python evaluation.py
```
#### System Requirements for Local Models
| Model Size | Storage | RAM | GPU VRAM | Recommended For |
|------------|---------|-----|----------|-----------------|
| Light | 20GB | 8-16GB | 6GB+ (optional) | Most users |
| Medium | 18GB | 16-32GB | 12GB+ (optional) | Balanced performance |
| Full | 155GB | 64GB+ | 80GB+ (recommended) | High-end systems |
### Local Models - Detailed Guide
#### Model Strategy Options (HuggingFace Only)
- **`remote`** (default): Use HuggingFace Inference API (free, no GPU needed)
- **`local`**: Use locally downloaded HuggingFace models (privacy, offline capability)
- **`local_light`**: Use lighter local HuggingFace models (reduced memory requirements)
- **`auto`**: Try local first, fallback to remote HuggingFace
```python
from config import set_model_strategy
set_model_strategy("remote") # Valid options: "remote", "local", "local_light", "auto"
```
**Note**: Only HuggingFace models are supported. OpenAI and Ollama support has been removed for compliance.
#### Download Models for Offline Use
```bash
# Download light models (~20GB, 8-16GB RAM)
python download_models.py --model-size light
# Download with HuggingFace token (for gated models)
python download_models.py --model-size light --token hf_your_token
# Download medium models (~18GB, better performance)
python download_models.py --model-size medium --token hf_your_token
# List available model sizes
python download_models.py --list-sizes
```
#### Custom Model Paths
```python
from config import set_local_model_paths, set_model_strategy
# Set custom paths to your models
set_local_model_paths(
llm_path="./models/Qwen2.5-7B-Instruct",
fallback_path="./models/Llama-3.1-8B-Instruct",
embedding_path="./models/all-MiniLM-L6-v2"
)
# Enable local models
set_model_strategy("local")
```
#### Memory Optimization for Local Models
For systems with limited RAM, enable quantization:
```python
from config import MODEL_CONFIG
# Enable 8-bit quantization (reduces memory by ~50%)
MODEL_CONFIG["load_in_8bit"] = True
# Or 4-bit quantization (reduces memory by ~75%)
MODEL_CONFIG["load_in_4bit"] = True
```
## Usage
### Individual Q&A
1. **Ask Questions**: Enter any question in the "Ask a Question" tab
2. **Upload Files**: Attach PDFs, CSVs, images, or documents for context
3. **Get Answers**: The agent will use appropriate tools and reasoning
**Examples:**
- "What's the latest news about AI developments?"
- "Calculate the compound interest for $1000 at 5% for 10 years"
- "What is the capital of France and its population?"
- "Analyze this CSV file and tell me the trends"
### GAIA Evaluation
1. **Login**: Use your Hugging Face account (required for submission)
2. **Run Evaluation**: Click "Run Evaluation & Submit All Answers"
3. **Monitor Progress**: Watch real-time processing of GAIA questions
4. **View Results**: See your score and detailed question-by-question results
## Agent Workflow
The Smolagents CodeAgent follows this reasoning pattern:
1. **Question Analysis**: Parse and understand the task requirements
2. **Tool Selection**: Choose appropriate tools (web search, calculator, etc.)
3. **Step Planning**: Break down complex problems into steps
4. **Code Execution**: Write and run Python code when needed
5. **Information Synthesis**: Combine results from multiple sources
6. **Answer Formulation**: Provide precise, well-reasoned responses
## GAIA Performance
This agent is optimized for the GAIA benchmark which evaluates:
- **Tool Usage**: Ability to select and use external tools effectively
- **Reasoning**: Multi-step reasoning for complex problems
- **Accuracy**: Precise answers with exact-match scoring
- **Robustness**: Handling diverse real-world scenarios
**Recent Improvements (2025)**:
- βœ… Fixed langchain compatibility (text_splitters module)
- βœ… Enhanced security: replaced unsafe eval() with AST-based safe math evaluator
- βœ… Improved answer extraction: better <think> tag removal and reasoning cleanup
- βœ… Updated to free HuggingFace models (Qwen2.5-72B, Llama-3.1-8B)
- βœ… HuggingFace-only compliance: removed OpenAI and Ollama support
- βœ… Fixed Novita.ai routing error: explicit HF provider configuration
- βœ… Security compliance: removed all comments, emojis, and icons from code
- βœ… Repository cleanup: removed 15+ demo/test files for professional structure
- βœ… Fixed application initialization: added demo.launch() and UI handlers
**Target Performance**: Designed to achieve high scores on GAIA validation and test sets through:
- Intelligent tool selection and usage
- Multi-step reasoning capabilities with CodeAgent
- Robust error handling and retry logic
- Precise answer formatting with multiple extraction strategies
## File Support
- **Text Files**: `.txt`, `.csv`, `.docx`, `.xlsx`
- **PDFs**: Full text extraction with pdfplumber
- **Images**: `.png`, `.jpg`, `.jpeg` (basic processing)
## Configuration
Key settings in `config.py`:
- **Model Selection**: Primary and fallback LLMs
- **Tool Enablement**: Enable/disable specific tools
- **Search Parameters**: Results count, timeouts
- **Safety Settings**: Code execution limits
## Contributing
This is an open-source implementation of a GAIA-optimized agent. Contributions welcome:
- Additional tools and capabilities
- Performance optimizations
- GAIA benchmark improvements
- Documentation enhancements
## Technical Details
**Framework**: Built on Smolagents - a lightweight (~1,000 lines) agent framework with deep Hugging Face integration
**Code Agents vs Tool Calling**: Uses CodeAgent (Python execution) which outperforms traditional JSON-based tool calling by ~30% on complex benchmarks
**Extensibility**: Easy to add new tools using the `@tool` decorator pattern
---
## Recent Changes & Fixes (2025)
### Critical Fixes
#### 1. Module Import Error (FIXED βœ…)
**Issue:** `ModuleNotFoundError: No module named 'langchain.text_splitter'`
**Solution:** LangChain restructured packages in 2025. Updated to use new imports:
```python
# Updated imports
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_core.documents import Document as LangchainDocument
```
Added `langchain-text-splitters` and `langchain-core` to requirements.txt.
#### 2. Security Vulnerabilities (FIXED βœ…)
**Issue:** Three instances of unsafe `eval()` usage that could lead to code injection.
**Solution:** Implemented `safe_math_eval()` using AST parsing:
- Only allows arithmetic operations: +, -, *, /, **, ()
- Validates expressions before evaluation
- Prevents arbitrary code execution
- Enhanced calculator tool with safe evaluation
#### 3. Answer Extraction Improved (FIXED βœ…)
**Issue:** Thinking process tags and reasoning leaking into final answers.
**Solution:** Enhanced cleaning:
- Removes all `<think>...</think>` tag variations (case-insensitive)
- Removes Thought:/Action:/Observation: markers
- Better handling of unclosed tags and edge cases
- Improved answer precision for GAIA submission
### Configuration Updates
#### Updated to Free 2025 Models (HuggingFace Only, Ungated)
- **Primary:** `mistralai/Mistral-7B-Instruct-v0.2` (Apache 2.0, ungated, no approval needed)
- **Fallback:** `HuggingFaceH4/zephyr-7b-beta` (MIT license, ungated, no approval needed)
- **Embedding:** `sentence-transformers/all-MiniLM-L6-v2` (ungated)
- **Default:** Remote strategy (HuggingFace Serverless Inference API)
- **API Endpoint:** Hardcoded to `https://router.huggingface.co/hf-inference` - routes to HuggingFace infrastructure only
#### Benefits
- Uses latest high-performance ungated models
- Completely free via HuggingFace Inference Providers (monthly credits)
- No GPU or local resources required
- NO approval or gating - works immediately
- Optimized for GAIA benchmark tasks
- No external dependencies (OpenAI, Ollama, etc. removed)
#### Why These Models?
- **Mistral-7B-Instruct-v0.2**: Ungated, Apache 2.0 license, 3.2M+ downloads/month, excellent reasoning
- **Zephyr-7b-beta**: Ungated, MIT license, fine-tuned on Mistral, reliable fallback
- Both work with Inference Providers' free tier
- No waiting for model approval required
#### Removed Features
- OpenAI API support (removed for compliance)
- Ollama server support (removed for compliance)
- All non-HuggingFace model providers (removed)
- Application now uses EXCLUSIVELY HuggingFace infrastructure
---
## Troubleshooting
### Common Issues
#### Import Errors
```bash
# Install missing langchain modules
pip install langchain-text-splitters langchain-core
# Verify imports work
python -c "from hf_agent import SmolagentsGAIAAgent; print('βœ… Success')"
```
#### Authentication Errors (403 Client Error)
```bash
# Set your HuggingFace token
export HF_TOKEN="hf_your_token_here"
# Or for gated models, request access first:
# Visit: https://huggingface.co/meta-llama/Llama-3.1-8B-Instruct
# Click "Request access to model"
# Wait for approval (usually instant)
```
#### Out of Memory with Local Models
```python
# Enable quantization
from config import MODEL_CONFIG
MODEL_CONFIG["load_in_8bit"] = True # Reduces memory by ~50%
# Or use lighter models
from config import set_model_strategy
set_model_strategy("local_light") # Uses smaller models
```
#### Slow Performance
```bash
# Use remote models (fastest, no local compute)
python -c "from config import set_model_strategy; set_model_strategy('remote')"
# Or download lighter local models
python download_models.py --model-size light
```
#### GAIA Submission Failures
- Ensure HF_TOKEN is set in environment
- Check internet connection for API access
- Verify answer format (should be clean text, no tags)
- Review logs for specific error messages
#### Novita.ai or Wrong Provider Errors
If you see errors like "403 Forbidden: https://api.novita.ai/...":
- **Cause**: InferenceClient auto-detected wrong provider
- **Fix**: Application now explicitly uses `provider="hf-inference"`
- **Prevention**: Do not set OPENAI_API_KEY or other provider API keys
- **Solution**: Use only HF_TOKEN environment variable
```bash
# Correct setup
export HF_TOKEN="hf_your_token_here"
unset OPENAI_API_KEY # Remove if set
# Run application
python evaluation.py
```
### Verification Commands
```bash
# Check configuration
python -c "from config import get_model_config; print(get_model_config())"
# Test agent initialization
python -c "from hf_agent import SmolagentsGAIAAgent; agent = SmolagentsGAIAAgent(); print('βœ… Agent ready')"
# Test imports
python -c "import evaluation; print('βœ… All imports working')"
```
---
## Deployment Guide
### HuggingFace Spaces Deployment
#### Step 1: Prepare Files
Essential files for deployment:
- βœ… `evaluation.py` - Main Gradio app (required)
- βœ… `hf_agent.py` - Agent implementation (required)
- βœ… `config.py` - Configuration (required)
- βœ… `requirements.txt` - Dependencies (required)
- βœ… `README.md` - Documentation (required for Space metadata)
Optional files:
- `download_models.py` - Only needed if using local models
- `local_config.json` - Optional, has defaults in config.py
- `questions.md` - Question log (development only)
#### Step 2: Create Space
1. Go to https://huggingface.co/new-space
2. Choose Space name
3. Select SDK: **Gradio**
4. Select SDK version: **5.25.2** (or latest)
5. Choose visibility (Public recommended for GAIA)
#### Step 3: Upload Files
```bash
# Clone your Space
git clone https://huggingface.co/spaces/YOUR_USERNAME/YOUR_SPACE_NAME
cd YOUR_SPACE_NAME
# Copy files
cp /path/to/evaluation.py .
cp /path/to/hf_agent.py .
cp /path/to/config.py .
cp /path/to/requirements.txt .
cp /path/to/README.md .
# Commit and push
git add .
git commit -m "Initial deployment"
git push
```
#### Step 4: Configure Environment
In Space settings:
1. Go to **Settings** β†’ **Variables**
2. Add **New Secret**:
- Name: `HF_TOKEN`
- Value: Your token from https://huggingface.co/settings/tokens
3. Save changes
#### Step 5: Verify OAuth Configuration
OAuth is already configured in the README.md header for GAIA submission:
- `hf_oauth: true` - Enables HuggingFace authentication
- `hf_oauth_expiration_minutes: 480` - 8-hour token expiration
No additional configuration needed.
#### Step 6: Deploy
- Space auto-builds on push
- Check **Logs** tab for build status
- Once built, test the interface
- Run a test GAIA evaluation
### Local Deployment
#### Development Server
```bash
# Install dependencies
pip install -r requirements.txt
# Set environment variable
export HF_TOKEN="your_token_here"
# Run Gradio app
python evaluation.py
# Access at: http://localhost:7860
```
#### Production Server
```bash
# Run with specific host/port
python evaluation.py --server-name 0.0.0.0 --server-port 8080
# Note: Gradio handles its own server, gunicorn not typically needed
```
### Docker Deployment
```dockerfile
FROM python:3.10-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
ENV HF_TOKEN=""
ENV PORT=7860
CMD ["python", "evaluation.py"]
```
```bash
# Build and run
docker build -t gaia-agent .
docker run -p 7860:7860 -e HF_TOKEN="your_token" gaia-agent
```
---
## System Status
### βœ… Production Ready
- Complete Smolagents framework implementation
- 6 custom tools working (web search, Wikipedia, calculator, files, articles, RAG)
- Gradio interface with multiple tabs
- Local and remote model support
- Comprehensive error handling
- Security hardened (safe eval, input validation)
### 🎯 GAIA Optimized
- CodeAgent with Thought-Action-Observation reasoning
- Multi-step problem solving
- Tool selection intelligence
- Answer extraction and formatting
- Retry logic for reliability
### πŸ“Š Performance
- **Remote Mode**: Fastest, no local compute, completely free
- **Local Mode**: Privacy-focused, offline capable, full control
- **Hybrid Mode**: Best of both worlds with auto-fallback
### πŸ”’ Security
- Safe mathematical expression evaluation (AST-based)
- Input validation and sanitization
- Sandboxed code execution
- No unsafe eval() usage
- Rate limiting for external APIs
---
**Powered by Smolagents and Hugging Face models. Optimized for GAIA benchmark evaluation.**
---
## Model Access Instructions
### Current Models (NO Approval Required)
The application is configured with **ungated models** that work immediately:
1. **mistralai/Mistral-7B-Instruct-v0.2**
- License: Apache 2.0
- Status: Openly accessible, no gating
- Access: https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2
- Action: None needed - works immediately with HF_TOKEN
2. **HuggingFaceH4/zephyr-7b-beta**
- License: MIT
- Status: Openly accessible, no gating
- Access: https://huggingface.co/HuggingFaceH4/zephyr-7b-beta
- Action: None needed - works immediately with HF_TOKEN
3. **sentence-transformers/all-MiniLM-L6-v2**
- Status: Openly accessible
- Action: None needed
### If You Want to Use Gated Models (Optional)
Some models require approval before use. If you want to use gated models like Meta-Llama:
#### Step 1: Request Access
1. Visit the model page (e.g., https://huggingface.co/meta-llama/Llama-3.1-8B-Instruct)
2. Click "Request access to model" button
3. Accept the license agreement
4. Wait for approval (usually instant for Llama models)
#### Step 2: Verify Access
1. Go to https://huggingface.co/settings/gated-repos
2. Check that the model appears in your approved list
#### Step 3: Update Configuration
```python
# In config.py, change remote_models:
"remote_models": {
"llm_model": "meta-llama/Llama-3.1-8B-Instruct", # After approval
"fallback_model": "HuggingFaceH4/zephyr-7b-beta",
"embedding_model": "sentence-transformers/all-MiniLM-L6-v2",
}
```
#### Step 4: Ensure Your HF Token Has Correct Permissions
1. Go to https://huggingface.co/settings/tokens
2. Create new token or use existing
3. Ensure permissions include:
- "Make calls to the serverless Inference API"
- "Access content from gated repos" (for gated models)
4. Copy token and set as HF_TOKEN
### Popular Ungated Alternatives
If you want different models but don't want to wait for approval:
**For Better Reasoning:**
- `mistralai/Mistral-7B-Instruct-v0.3` (ungated, Apache 2.0)
- `microsoft/phi-2` (ungated, MIT license)
- `google/flan-t5-xxl` (ungated, but not on serverless inference)
**For Faster Inference:**
- `HuggingFaceH4/zephyr-7b-beta` (already configured)
- `microsoft/DialoGPT-medium` (ungated, smaller)
**Note**: Always check the model page to verify current gating status.
---