File size: 22,203 Bytes
2705160
337873f
d579ced
 
2705160
 
28fa73f
2705160
d123508
 
 
2705160
 
337873f
d579ced
337873f
d579ced
9f54091
 
 
 
 
 
 
 
 
 
 
 
 
 
337873f
d579ced
337873f
 
 
 
 
 
28fa73f
337873f
 
 
 
 
28fa73f
337873f
 
 
 
 
 
 
28fa73f
337873f
 
9f54091
4dab09a
9f54091
 
337873f
4dab09a
9f54091
097318b
337873f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f54091
 
 
 
 
 
 
 
337873f
e8f2491
 
 
 
 
337873f
e8f2491
 
 
 
 
 
 
337873f
 
89c14ba
 
337873f
 
 
 
 
 
 
 
 
 
 
 
 
 
28fa73f
89c14ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b174d42
 
9f54091
b174d42
9f54091
 
 
b174d42
 
 
9f54091
b174d42
 
9f54091
 
b174d42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89c14ba
b112eb6
337873f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8f2491
 
 
 
 
9f54091
 
 
 
 
e8f2491
337873f
 
e8f2491
 
 
28fa73f
b112eb6
337873f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d579ced
337873f
d579ced
337873f
d579ced
b112eb6
d579ced
b174d42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f54091
 
 
 
4dab09a
097318b
b174d42
 
9f54091
 
b174d42
9f54091
b174d42
9f54091
 
 
 
 
 
 
 
 
 
 
 
 
b174d42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f54091
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b174d42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f54091
 
 
 
 
 
 
 
 
 
 
b174d42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f54091
 
 
 
 
 
b174d42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f54091
b174d42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f54091
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
---
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.

---