Commit ·
8e01d85
1
Parent(s): 81917a3
Initial setup with smolagents implementation
Browse files- Add smolagents-based agent implementation
- Create CLI interface for local testing
- Implement web search, browsing, file reading, and Excel analysis tools
- Update Gradio web interface to use new agent
- Add OpenRouter API client integration
- Create documentation and setup instructions
- .env.example +5 -0
- .gitignore +30 -0
- README.md +100 -15
- agent.py +268 -0
- app.py +70 -6
- cli.py +171 -0
- requirements.txt +8 -1
.env.example
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# OpenRouter API Configuration
|
| 2 |
+
OPENROUTER_API_KEY=your_openrouter_api_key_here
|
| 3 |
+
OPENROUTER_MODEL=anthropic/claude-3-5-sonnet
|
| 4 |
+
|
| 5 |
+
# Save this file as .env and add your actual API key
|
.gitignore
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Python virtual environment
|
| 2 |
+
venv/
|
| 3 |
+
|
| 4 |
+
# Environment variables
|
| 5 |
+
.env
|
| 6 |
+
|
| 7 |
+
# Claude configuration
|
| 8 |
+
CLAUDE.md
|
| 9 |
+
|
| 10 |
+
# Mac OS files
|
| 11 |
+
.DS_Store
|
| 12 |
+
|
| 13 |
+
# Downloaded files
|
| 14 |
+
downloaded_files/
|
| 15 |
+
|
| 16 |
+
# Cached Python files
|
| 17 |
+
__pycache__/
|
| 18 |
+
*.py[cod]
|
| 19 |
+
*$py.class
|
| 20 |
+
|
| 21 |
+
# Distribution / packaging
|
| 22 |
+
dist/
|
| 23 |
+
build/
|
| 24 |
+
*.egg-info/
|
| 25 |
+
|
| 26 |
+
# Jupyter Notebook checkpoints
|
| 27 |
+
.ipynb_checkpoints/
|
| 28 |
+
|
| 29 |
+
# Test results
|
| 30 |
+
results.json
|
README.md
CHANGED
|
@@ -1,15 +1,100 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# AI Agent Evaluation Project
|
| 2 |
+
|
| 3 |
+
This project implements an AI agent using the smolagents library to answer questions for evaluation. The agent connects to the OpenRouter API to access LLM capabilities and is equipped with various tools to help answer questions effectively.
|
| 4 |
+
|
| 5 |
+
## Project Structure
|
| 6 |
+
|
| 7 |
+
- `app.py`: Gradio web interface for the agent evaluation
|
| 8 |
+
- `agent.py`: Implementation of the SmolAgent using smolagents
|
| 9 |
+
- `cli.py`: Command-line interface for testing the agent locally
|
| 10 |
+
- `.env.example`: Example environment variable configuration
|
| 11 |
+
|
| 12 |
+
## Setup Instructions
|
| 13 |
+
|
| 14 |
+
1. Clone this repository:
|
| 15 |
+
```
|
| 16 |
+
git clone https://github.com/your-username/ai-agent-evaluation.git
|
| 17 |
+
cd ai-agent-evaluation
|
| 18 |
+
```
|
| 19 |
+
|
| 20 |
+
2. Create a virtual environment and install dependencies:
|
| 21 |
+
```
|
| 22 |
+
python3 -m venv venv
|
| 23 |
+
source venv/bin/activate
|
| 24 |
+
pip install -r requirements.txt
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
3. Set up your OpenRouter API key:
|
| 28 |
+
- Create an account at [OpenRouter](https://openrouter.ai/)
|
| 29 |
+
- Obtain an API key
|
| 30 |
+
- Copy `.env.example` to `.env` and add your API key:
|
| 31 |
+
```
|
| 32 |
+
cp .env.example .env
|
| 33 |
+
```
|
| 34 |
+
- Edit the `.env` file and replace `your_openrouter_api_key_here` with your actual API key
|
| 35 |
+
|
| 36 |
+
## Usage
|
| 37 |
+
|
| 38 |
+
### CLI Testing
|
| 39 |
+
|
| 40 |
+
The CLI allows you to test the agent against individual questions or all questions from the evaluation API:
|
| 41 |
+
|
| 42 |
+
```bash
|
| 43 |
+
# Run against a random question
|
| 44 |
+
./cli.py --random --save-files
|
| 45 |
+
|
| 46 |
+
# Run against all questions
|
| 47 |
+
./cli.py --all --save-files
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
### Web Interface
|
| 51 |
+
|
| 52 |
+
To run the Gradio web interface:
|
| 53 |
+
|
| 54 |
+
```bash
|
| 55 |
+
python3 app.py
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
Then:
|
| 59 |
+
1. Open the provided URL in your browser
|
| 60 |
+
2. Log in to your Hugging Face account
|
| 61 |
+
3. Click "Run Evaluation & Submit All Answers"
|
| 62 |
+
|
| 63 |
+
## Agent Tools
|
| 64 |
+
|
| 65 |
+
The agent is equipped with the following tools:
|
| 66 |
+
|
| 67 |
+
1. **Web Search**: Search the web for information
|
| 68 |
+
2. **Web Browsing**: Fetch and extract content from a specific URL
|
| 69 |
+
3. **File Reading**: Read files attached to questions
|
| 70 |
+
4. **Calculation**: Perform mathematical calculations
|
| 71 |
+
|
| 72 |
+
## Configuration
|
| 73 |
+
|
| 74 |
+
You can configure the following parameters in your `.env` file:
|
| 75 |
+
|
| 76 |
+
- `OPENROUTER_API_KEY`: Your OpenRouter API key
|
| 77 |
+
- `OPENROUTER_MODEL`: The model to use (default: anthropic/claude-3-5-sonnet)
|
| 78 |
+
|
| 79 |
+
## Evaluation API
|
| 80 |
+
|
| 81 |
+
The agent is evaluated using the API at `https://agents-course-unit4-scoring.hf.space`, which provides:
|
| 82 |
+
|
| 83 |
+
- `/questions`: All questions for evaluation
|
| 84 |
+
- `/random-question`: A single random question
|
| 85 |
+
- `/files/{task_id}`: Files associated with questions
|
| 86 |
+
- `/submit`: Endpoint for submitting answers
|
| 87 |
+
|
| 88 |
+
## Submission Requirements
|
| 89 |
+
|
| 90 |
+
For submission, the API requires:
|
| 91 |
+
|
| 92 |
+
1. **Username**: Your Hugging Face username
|
| 93 |
+
2. **Code Link**: URL to your Hugging Face Space code
|
| 94 |
+
3. **Answers**: List of responses for scoring, formatted as `{"task_id": "...", "submitted_answer": "..."}`
|
| 95 |
+
|
| 96 |
+
## Important Notes
|
| 97 |
+
|
| 98 |
+
- The agent is designed to answer questions directly without including phrases like "FINAL ANSWER:" in the response
|
| 99 |
+
- Files associated with questions are automatically downloaded and made available to the agent
|
| 100 |
+
- The agent uses smolagents for tool calling capabilities with the OpenRouter API
|
agent.py
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import time
|
| 4 |
+
import requests
|
| 5 |
+
import pandas as pd
|
| 6 |
+
from openai import OpenAI
|
| 7 |
+
from bs4 import BeautifulSoup
|
| 8 |
+
from smolagents import ToolCallingAgent, Tool
|
| 9 |
+
|
| 10 |
+
class WebSearchTool(Tool):
|
| 11 |
+
name = "web_search"
|
| 12 |
+
description = "Search the web for information on a query. Useful for finding up-to-date information."
|
| 13 |
+
inputs = {"query": "The search query"}
|
| 14 |
+
output_type = "string"
|
| 15 |
+
|
| 16 |
+
def __init__(self):
|
| 17 |
+
pass
|
| 18 |
+
|
| 19 |
+
def forward(self, query):
|
| 20 |
+
try:
|
| 21 |
+
# Use a search engine API to get results
|
| 22 |
+
response = requests.get(
|
| 23 |
+
f"https://www.google.com/search?q={query}",
|
| 24 |
+
headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36"}
|
| 25 |
+
)
|
| 26 |
+
response.raise_for_status()
|
| 27 |
+
|
| 28 |
+
soup = BeautifulSoup(response.text, 'html.parser')
|
| 29 |
+
search_results = []
|
| 30 |
+
|
| 31 |
+
# Extract search results
|
| 32 |
+
for result in soup.select(".tF2Cxc"):
|
| 33 |
+
title = result.select_one(".DKV0Md").text if result.select_one(".DKV0Md") else ""
|
| 34 |
+
link = result.select_one("a")["href"] if result.select_one("a") else ""
|
| 35 |
+
snippet = result.select_one(".VwiC3b").text if result.select_one(".VwiC3b") else ""
|
| 36 |
+
|
| 37 |
+
if title and link:
|
| 38 |
+
search_results.append({
|
| 39 |
+
"title": title,
|
| 40 |
+
"link": link,
|
| 41 |
+
"snippet": snippet
|
| 42 |
+
})
|
| 43 |
+
|
| 44 |
+
# Format results into a readable string
|
| 45 |
+
if search_results:
|
| 46 |
+
formatted_results = "\n\n".join([
|
| 47 |
+
f"Title: {r['title']}\nURL: {r['link']}\nSnippet: {r['snippet']}"
|
| 48 |
+
for r in search_results[:5] # Limit to top 5 results
|
| 49 |
+
])
|
| 50 |
+
return f"Search results for '{query}':\n\n{formatted_results}"
|
| 51 |
+
else:
|
| 52 |
+
return f"No results found for '{query}'."
|
| 53 |
+
|
| 54 |
+
except Exception as e:
|
| 55 |
+
return f"Error searching the web: {str(e)}"
|
| 56 |
+
|
| 57 |
+
class WebBrowseTool(Tool):
|
| 58 |
+
name = "web_browse"
|
| 59 |
+
description = "Browse a specific webpage and extract its content."
|
| 60 |
+
inputs = {"url": "The URL of the webpage to browse"}
|
| 61 |
+
output_type = "string"
|
| 62 |
+
|
| 63 |
+
def __init__(self):
|
| 64 |
+
pass
|
| 65 |
+
|
| 66 |
+
def forward(self, url):
|
| 67 |
+
try:
|
| 68 |
+
headers = {
|
| 69 |
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36"
|
| 70 |
+
}
|
| 71 |
+
response = requests.get(url, headers=headers, timeout=10)
|
| 72 |
+
response.raise_for_status()
|
| 73 |
+
|
| 74 |
+
soup = BeautifulSoup(response.text, 'html.parser')
|
| 75 |
+
|
| 76 |
+
# Remove script and style elements
|
| 77 |
+
for script in soup(["script", "style"]):
|
| 78 |
+
script.extract()
|
| 79 |
+
|
| 80 |
+
# Get text
|
| 81 |
+
text = soup.get_text()
|
| 82 |
+
|
| 83 |
+
# Clean up text: break into lines and remove leading and trailing space
|
| 84 |
+
lines = (line.strip() for line in text.splitlines())
|
| 85 |
+
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
|
| 86 |
+
text = '\n'.join(chunk for chunk in chunks if chunk)
|
| 87 |
+
|
| 88 |
+
# Limit text length to avoid LLM context limitations
|
| 89 |
+
if len(text) > 8000:
|
| 90 |
+
text = text[:8000] + "...\n[Content truncated due to length]"
|
| 91 |
+
|
| 92 |
+
return f"Content from {url}:\n\n{text}"
|
| 93 |
+
|
| 94 |
+
except Exception as e:
|
| 95 |
+
return f"Error accessing {url}: {str(e)}"
|
| 96 |
+
|
| 97 |
+
class ReadFileTool(Tool):
|
| 98 |
+
name = "read_file"
|
| 99 |
+
description = "Read the content of a file."
|
| 100 |
+
inputs = {"file_path": "The path to the file to read"}
|
| 101 |
+
output_type = "string"
|
| 102 |
+
|
| 103 |
+
def __init__(self):
|
| 104 |
+
pass
|
| 105 |
+
|
| 106 |
+
def forward(self, file_path):
|
| 107 |
+
try:
|
| 108 |
+
if not os.path.exists(file_path):
|
| 109 |
+
return f"Error: File not found at {file_path}"
|
| 110 |
+
|
| 111 |
+
with open(file_path, 'rb') as f:
|
| 112 |
+
content = f.read()
|
| 113 |
+
|
| 114 |
+
# Try to decode as text
|
| 115 |
+
try:
|
| 116 |
+
text_content = content.decode('utf-8')
|
| 117 |
+
return f"Content of {file_path}:\n\n{text_content}"
|
| 118 |
+
except UnicodeDecodeError:
|
| 119 |
+
# If it's not text, just return info about the binary file
|
| 120 |
+
return f"Binary file {file_path}, size: {len(content)} bytes"
|
| 121 |
+
|
| 122 |
+
except Exception as e:
|
| 123 |
+
return f"Error reading file: {str(e)}"
|
| 124 |
+
|
| 125 |
+
class CalculateTool(Tool):
|
| 126 |
+
name = "calculate"
|
| 127 |
+
description = "Perform a calculation."
|
| 128 |
+
inputs = {"expression": "The mathematical expression to calculate"}
|
| 129 |
+
output_type = "string"
|
| 130 |
+
|
| 131 |
+
def __init__(self):
|
| 132 |
+
pass
|
| 133 |
+
|
| 134 |
+
def forward(self, expression):
|
| 135 |
+
try:
|
| 136 |
+
# Be very careful with eval - in production this should be replaced with a safer alternative
|
| 137 |
+
# like the `simpleeval` library
|
| 138 |
+
result = eval(expression, {"__builtins__": {}})
|
| 139 |
+
return f"Result: {result}"
|
| 140 |
+
except Exception as e:
|
| 141 |
+
return f"Error calculating '{expression}': {str(e)}"
|
| 142 |
+
|
| 143 |
+
class AnalyzeExcelTool(Tool):
|
| 144 |
+
name = "analyze_excel"
|
| 145 |
+
description = "Analyze an Excel file and extract data from it."
|
| 146 |
+
inputs = {"file_path": "The path to the Excel file", "query": "The specific data or analysis you want from the file"}
|
| 147 |
+
output_type = "string"
|
| 148 |
+
|
| 149 |
+
def __init__(self):
|
| 150 |
+
pass
|
| 151 |
+
|
| 152 |
+
def forward(self, file_path, query):
|
| 153 |
+
try:
|
| 154 |
+
if not os.path.exists(file_path):
|
| 155 |
+
return f"Error: File not found at {file_path}"
|
| 156 |
+
|
| 157 |
+
# Read the Excel file
|
| 158 |
+
try:
|
| 159 |
+
df = pd.read_excel(file_path)
|
| 160 |
+
except Exception as e:
|
| 161 |
+
# Try with different engine if default fails
|
| 162 |
+
try:
|
| 163 |
+
df = pd.read_excel(file_path, engine='openpyxl')
|
| 164 |
+
except Exception as e2:
|
| 165 |
+
try:
|
| 166 |
+
df = pd.read_excel(file_path, engine='xlrd')
|
| 167 |
+
except Exception as e3:
|
| 168 |
+
return f"Error reading Excel file: {str(e)}, {str(e2)}, {str(e3)}"
|
| 169 |
+
|
| 170 |
+
# Basic info about the Excel file
|
| 171 |
+
file_info = f"Excel file contains {len(df.columns)} columns and {len(df)} rows.\n"
|
| 172 |
+
file_info += f"Columns: {', '.join(df.columns.tolist())}\n"
|
| 173 |
+
|
| 174 |
+
# Sample of the data
|
| 175 |
+
sample = df.head(5).to_string()
|
| 176 |
+
|
| 177 |
+
# Try to answer specific query about the data
|
| 178 |
+
query_lower = query.lower()
|
| 179 |
+
|
| 180 |
+
# Handle sum queries
|
| 181 |
+
if "sum" in query_lower or "total" in query_lower:
|
| 182 |
+
# Try to identify which column(s) to sum based on the query
|
| 183 |
+
numeric_cols = df.select_dtypes(include=['number']).columns.tolist()
|
| 184 |
+
|
| 185 |
+
column_sums = {}
|
| 186 |
+
for col in numeric_cols:
|
| 187 |
+
column_sums[col] = df[col].sum()
|
| 188 |
+
|
| 189 |
+
sums_info = "Sum of numeric columns:\n"
|
| 190 |
+
for col, total in column_sums.items():
|
| 191 |
+
sums_info += f"Sum of {col}: {total}\n"
|
| 192 |
+
|
| 193 |
+
return f"{file_info}\n\n{sample}\n\n{sums_info}"
|
| 194 |
+
|
| 195 |
+
# Handle filter queries
|
| 196 |
+
elif "filter" in query_lower or "where" in query_lower or "only" in query_lower:
|
| 197 |
+
# This is a simple example - in a real implementation,
|
| 198 |
+
# you would use NLP to understand the filter conditions
|
| 199 |
+
filter_info = "To filter data, please specify the exact column and condition."
|
| 200 |
+
return f"{file_info}\n\n{sample}\n\n{filter_info}"
|
| 201 |
+
|
| 202 |
+
# Default response with file overview
|
| 203 |
+
else:
|
| 204 |
+
return f"{file_info}\n\nSample data:\n{sample}"
|
| 205 |
+
|
| 206 |
+
except Exception as e:
|
| 207 |
+
return f"Error analyzing Excel file: {str(e)}"
|
| 208 |
+
|
| 209 |
+
def get_agent_tools():
|
| 210 |
+
"""Return a list of tools available to the agent."""
|
| 211 |
+
return [
|
| 212 |
+
WebSearchTool(),
|
| 213 |
+
WebBrowseTool(),
|
| 214 |
+
ReadFileTool(),
|
| 215 |
+
CalculateTool(),
|
| 216 |
+
AnalyzeExcelTool()
|
| 217 |
+
]
|
| 218 |
+
|
| 219 |
+
class SmolAgent:
|
| 220 |
+
def __init__(self, openrouter_api_key, model="anthropic/claude-3-5-sonnet"):
|
| 221 |
+
# Setup the OpenAI client with OpenRouter
|
| 222 |
+
self.client = OpenAI(
|
| 223 |
+
base_url="https://openrouter.ai/api/v1",
|
| 224 |
+
api_key=openrouter_api_key,
|
| 225 |
+
default_headers={
|
| 226 |
+
"HTTP-Referer": "https://github.com/neuralconfig/osticket-agent",
|
| 227 |
+
"X-Title": "Agent Evaluation Tool"
|
| 228 |
+
}
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
self.model = model
|
| 232 |
+
|
| 233 |
+
# Create the Smol Agent with tools
|
| 234 |
+
system_message = """You are a helpful AI assistant designed to answer questions accurately.
|
| 235 |
+
|
| 236 |
+
When presented with a question:
|
| 237 |
+
1. Think carefully about what is being asked
|
| 238 |
+
2. Use the provided tools when necessary to gather accurate information
|
| 239 |
+
3. Provide clear, concise answers based on the information available
|
| 240 |
+
4. Always present your final answer directly without adding 'FINAL ANSWER:' or similar phrases
|
| 241 |
+
5. If you use research or external information, incorporate it naturally into your response
|
| 242 |
+
|
| 243 |
+
Be precise and focus only on answering the question asked. Do not add disclaimers, avoid hallucinating information, and acknowledge when you don't know something."""
|
| 244 |
+
|
| 245 |
+
self.agent = ToolCallingAgent(
|
| 246 |
+
model=self.model,
|
| 247 |
+
tools=get_agent_tools(),
|
| 248 |
+
system_message=system_message,
|
| 249 |
+
llm_client=self.client
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
def __call__(self, question, context=None):
|
| 253 |
+
"""Run the agent on a question and return the answer."""
|
| 254 |
+
# Add context about any files if provided
|
| 255 |
+
if context and "file_path" in context:
|
| 256 |
+
question += f"\n\nAttached file information: {context.get('file_name', '')}"
|
| 257 |
+
question += f"\nYou can access this file using the read_file tool with the path: {context.get('file_path')}"
|
| 258 |
+
|
| 259 |
+
try:
|
| 260 |
+
response = self.agent(question)
|
| 261 |
+
# Make sure we're not including "FINAL ANSWER:" in the response
|
| 262 |
+
final_answer = response
|
| 263 |
+
if "FINAL ANSWER:" in final_answer:
|
| 264 |
+
final_answer = final_answer.split("FINAL ANSWER:", 1)[1].strip()
|
| 265 |
+
|
| 266 |
+
return final_answer
|
| 267 |
+
except Exception as e:
|
| 268 |
+
return f"Error processing question: {str(e)}"
|
app.py
CHANGED
|
@@ -3,21 +3,85 @@ import gradio as gr
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
# (Keep Constants as is)
|
| 8 |
# --- Constants ---
|
| 9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 10 |
|
| 11 |
-
# ---
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
class BasicAgent:
|
| 14 |
def __init__(self):
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
def __call__(self, question: str) -> str:
|
| 17 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 23 |
"""
|
|
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
+
from dotenv import load_dotenv
|
| 7 |
+
|
| 8 |
+
# Load environment variables
|
| 9 |
+
load_dotenv()
|
| 10 |
|
| 11 |
# (Keep Constants as is)
|
| 12 |
# --- Constants ---
|
| 13 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 14 |
|
| 15 |
+
# --- Import and use our SmolAgent implementation ---
|
| 16 |
+
from agent import SmolAgent
|
| 17 |
+
|
| 18 |
+
# Function to download file for a task
|
| 19 |
+
def download_file(task_id, file_name, api_url=DEFAULT_API_URL):
|
| 20 |
+
"""Download a file for a task if one exists."""
|
| 21 |
+
file_url = f"{api_url}/files/{task_id}"
|
| 22 |
+
try:
|
| 23 |
+
response = requests.get(file_url, timeout=15)
|
| 24 |
+
if response.status_code == 404:
|
| 25 |
+
print(f"No file found for task {task_id}")
|
| 26 |
+
return None, None
|
| 27 |
+
response.raise_for_status()
|
| 28 |
+
|
| 29 |
+
# Save the file
|
| 30 |
+
os.makedirs("downloaded_files", exist_ok=True)
|
| 31 |
+
file_path = os.path.join("downloaded_files", file_name)
|
| 32 |
+
with open(file_path, "wb") as f:
|
| 33 |
+
f.write(response.content)
|
| 34 |
+
print(f"File saved to: {file_path}")
|
| 35 |
+
return file_path, response.content
|
| 36 |
+
except Exception as e:
|
| 37 |
+
print(f"Error downloading file: {e}")
|
| 38 |
+
return None, None
|
| 39 |
+
|
| 40 |
+
# --- Agent Wrapper Class ---
|
| 41 |
class BasicAgent:
|
| 42 |
def __init__(self):
|
| 43 |
+
# Get API key from environment variables
|
| 44 |
+
openrouter_api_key = os.getenv("OPENROUTER_API_KEY")
|
| 45 |
+
if not openrouter_api_key:
|
| 46 |
+
print("WARNING: OPENROUTER_API_KEY not set in environment!")
|
| 47 |
+
# Will raise an exception when the agent is used
|
| 48 |
+
|
| 49 |
+
self.model = os.getenv("OPENROUTER_MODEL", "anthropic/claude-3-5-sonnet")
|
| 50 |
+
print(f"BasicAgent initializing with model: {self.model}")
|
| 51 |
+
|
| 52 |
+
self.agent = SmolAgent(openrouter_api_key, model=self.model)
|
| 53 |
+
print("BasicAgent initialized successfully.")
|
| 54 |
+
|
| 55 |
def __call__(self, question: str) -> str:
|
| 56 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 57 |
+
|
| 58 |
+
# Extract task_id and file_name if present in the context
|
| 59 |
+
task_id = None
|
| 60 |
+
file_name = None
|
| 61 |
+
file_path = None
|
| 62 |
+
context = {}
|
| 63 |
+
|
| 64 |
+
# Check if this is a question that includes file metadata
|
| 65 |
+
if isinstance(question, dict):
|
| 66 |
+
task_id = question.get("task_id")
|
| 67 |
+
file_name = question.get("file_name", "")
|
| 68 |
+
|
| 69 |
+
# If there's a file, download it
|
| 70 |
+
if file_name:
|
| 71 |
+
file_path, _ = download_file(task_id, file_name)
|
| 72 |
+
if file_path:
|
| 73 |
+
context = {
|
| 74 |
+
"file_name": file_name,
|
| 75 |
+
"file_path": file_path
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
# Get the actual question text
|
| 79 |
+
question = question.get("question", "")
|
| 80 |
+
|
| 81 |
+
# Process the question with our agent
|
| 82 |
+
answer = self.agent(question, context=context)
|
| 83 |
+
print(f"Agent returning answer (first 50 chars): {answer[:50]}...")
|
| 84 |
+
return answer
|
| 85 |
|
| 86 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 87 |
"""
|
cli.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
import os
|
| 3 |
+
import json
|
| 4 |
+
import requests
|
| 5 |
+
import argparse
|
| 6 |
+
from dotenv import load_dotenv
|
| 7 |
+
|
| 8 |
+
# Load environment variables
|
| 9 |
+
load_dotenv()
|
| 10 |
+
|
| 11 |
+
# Constants
|
| 12 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 13 |
+
|
| 14 |
+
# Import the agent
|
| 15 |
+
from agent import SmolAgent
|
| 16 |
+
|
| 17 |
+
def fetch_questions(api_url=DEFAULT_API_URL):
|
| 18 |
+
"""Fetch all questions from the API."""
|
| 19 |
+
questions_url = f"{api_url}/questions"
|
| 20 |
+
print(f"Fetching questions from: {questions_url}")
|
| 21 |
+
try:
|
| 22 |
+
response = requests.get(questions_url, timeout=15)
|
| 23 |
+
response.raise_for_status()
|
| 24 |
+
questions_data = response.json()
|
| 25 |
+
if not questions_data:
|
| 26 |
+
print("Fetched questions list is empty.")
|
| 27 |
+
return None
|
| 28 |
+
print(f"Fetched {len(questions_data)} questions.")
|
| 29 |
+
return questions_data
|
| 30 |
+
except requests.exceptions.RequestException as e:
|
| 31 |
+
print(f"Error fetching questions: {e}")
|
| 32 |
+
return None
|
| 33 |
+
except requests.exceptions.JSONDecodeError as e:
|
| 34 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 35 |
+
print(f"Response text: {response.text[:500]}")
|
| 36 |
+
return None
|
| 37 |
+
except Exception as e:
|
| 38 |
+
print(f"An unexpected error occurred fetching questions: {e}")
|
| 39 |
+
return None
|
| 40 |
+
|
| 41 |
+
def fetch_random_question(api_url=DEFAULT_API_URL):
|
| 42 |
+
"""Fetch a single random question from the API."""
|
| 43 |
+
random_question_url = f"{api_url}/random-question"
|
| 44 |
+
print(f"Fetching random question from: {random_question_url}")
|
| 45 |
+
try:
|
| 46 |
+
response = requests.get(random_question_url, timeout=15)
|
| 47 |
+
response.raise_for_status()
|
| 48 |
+
question_data = response.json()
|
| 49 |
+
return question_data
|
| 50 |
+
except requests.exceptions.RequestException as e:
|
| 51 |
+
print(f"Error fetching random question: {e}")
|
| 52 |
+
return None
|
| 53 |
+
except requests.exceptions.JSONDecodeError as e:
|
| 54 |
+
print(f"Error decoding JSON response from random question endpoint: {e}")
|
| 55 |
+
print(f"Response text: {response.text[:500]}")
|
| 56 |
+
return None
|
| 57 |
+
except Exception as e:
|
| 58 |
+
print(f"An unexpected error occurred fetching random question: {e}")
|
| 59 |
+
return None
|
| 60 |
+
|
| 61 |
+
def fetch_file(task_id, api_url=DEFAULT_API_URL):
|
| 62 |
+
"""Fetch a file for a task if one exists."""
|
| 63 |
+
file_url = f"{api_url}/files/{task_id}"
|
| 64 |
+
print(f"Fetching file for task {task_id} from: {file_url}")
|
| 65 |
+
try:
|
| 66 |
+
response = requests.get(file_url, timeout=15)
|
| 67 |
+
if response.status_code == 404:
|
| 68 |
+
print(f"No file found for task {task_id}")
|
| 69 |
+
return None
|
| 70 |
+
response.raise_for_status()
|
| 71 |
+
return response.content
|
| 72 |
+
except requests.exceptions.RequestException as e:
|
| 73 |
+
print(f"Error fetching file: {e}")
|
| 74 |
+
return None
|
| 75 |
+
except Exception as e:
|
| 76 |
+
print(f"An unexpected error occurred fetching file: {e}")
|
| 77 |
+
return None
|
| 78 |
+
|
| 79 |
+
def test_agent_on_question(agent, question, save_file=False):
|
| 80 |
+
"""Test the agent on a single question and display the result."""
|
| 81 |
+
task_id = question.get("task_id")
|
| 82 |
+
question_text = question.get("question")
|
| 83 |
+
level = question.get("Level", "Unknown")
|
| 84 |
+
file_name = question.get("file_name", "")
|
| 85 |
+
|
| 86 |
+
print(f"\n{'='*80}")
|
| 87 |
+
print(f"Task ID: {task_id}")
|
| 88 |
+
print(f"Level: {level}")
|
| 89 |
+
print(f"Question: {question_text}")
|
| 90 |
+
|
| 91 |
+
# Check if there's a file associated with this question
|
| 92 |
+
file_content = None
|
| 93 |
+
file_path = None
|
| 94 |
+
if file_name:
|
| 95 |
+
print(f"File Name: {file_name}")
|
| 96 |
+
file_content = fetch_file(task_id)
|
| 97 |
+
if file_content and save_file:
|
| 98 |
+
os.makedirs("downloaded_files", exist_ok=True)
|
| 99 |
+
file_path = os.path.join("downloaded_files", file_name)
|
| 100 |
+
with open(file_path, "wb") as f:
|
| 101 |
+
f.write(file_content)
|
| 102 |
+
print(f"File saved to: {file_path}")
|
| 103 |
+
|
| 104 |
+
try:
|
| 105 |
+
print("\nRunning agent...")
|
| 106 |
+
# Pass additional context to the agent if there's a file
|
| 107 |
+
context = {}
|
| 108 |
+
if file_content and file_path:
|
| 109 |
+
context = {
|
| 110 |
+
"file_name": file_name,
|
| 111 |
+
"file_path": file_path
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
answer = agent(question_text, context=context)
|
| 115 |
+
print(f"\nAgent's answer: {answer}")
|
| 116 |
+
return {"task_id": task_id, "submitted_answer": answer}
|
| 117 |
+
except Exception as e:
|
| 118 |
+
print(f"\nError running agent: {e}")
|
| 119 |
+
return None
|
| 120 |
+
|
| 121 |
+
def main():
|
| 122 |
+
parser = argparse.ArgumentParser(description="CLI for the Agent Evaluation")
|
| 123 |
+
parser.add_argument("--all", action="store_true", help="Run against all questions")
|
| 124 |
+
parser.add_argument("--random", action="store_true", help="Run against a random question")
|
| 125 |
+
parser.add_argument("--save-files", action="store_true", help="Save downloaded files")
|
| 126 |
+
parser.add_argument("--api-url", default=DEFAULT_API_URL, help="API URL")
|
| 127 |
+
parser.add_argument("--openrouter-key", help="OpenRouter API key (or set OPENROUTER_API_KEY env var)")
|
| 128 |
+
parser.add_argument("--model", default="anthropic/claude-3-5-sonnet", help="Model to use for the agent")
|
| 129 |
+
|
| 130 |
+
args = parser.parse_args()
|
| 131 |
+
|
| 132 |
+
# Get API key either from command line or environment variable
|
| 133 |
+
openrouter_api_key = args.openrouter_key or os.getenv("OPENROUTER_API_KEY")
|
| 134 |
+
if not openrouter_api_key:
|
| 135 |
+
print("OpenRouter API key is required. Set it via --openrouter-key or OPENROUTER_API_KEY env var.")
|
| 136 |
+
return
|
| 137 |
+
|
| 138 |
+
# Initialize the agent
|
| 139 |
+
try:
|
| 140 |
+
agent = SmolAgent(openrouter_api_key, model=args.model)
|
| 141 |
+
print("Agent initialized successfully.")
|
| 142 |
+
except Exception as e:
|
| 143 |
+
print(f"Error initializing agent: {e}")
|
| 144 |
+
return
|
| 145 |
+
|
| 146 |
+
# Run agent on questions
|
| 147 |
+
results = []
|
| 148 |
+
|
| 149 |
+
if args.all:
|
| 150 |
+
questions = fetch_questions(args.api_url)
|
| 151 |
+
if questions:
|
| 152 |
+
for question in questions:
|
| 153 |
+
result = test_agent_on_question(agent, question, args.save_files)
|
| 154 |
+
if result:
|
| 155 |
+
results.append(result)
|
| 156 |
+
|
| 157 |
+
# Save results to a file
|
| 158 |
+
with open("results.json", "w") as f:
|
| 159 |
+
json.dump(results, f, indent=2)
|
| 160 |
+
print(f"\nSaved {len(results)} results to results.json")
|
| 161 |
+
|
| 162 |
+
elif args.random:
|
| 163 |
+
question = fetch_random_question(args.api_url)
|
| 164 |
+
if question:
|
| 165 |
+
test_agent_on_question(agent, question, args.save_files)
|
| 166 |
+
|
| 167 |
+
else:
|
| 168 |
+
parser.print_help()
|
| 169 |
+
|
| 170 |
+
if __name__ == "__main__":
|
| 171 |
+
main()
|
requirements.txt
CHANGED
|
@@ -1,2 +1,9 @@
|
|
| 1 |
gradio
|
| 2 |
-
requests
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
gradio
|
| 2 |
+
requests
|
| 3 |
+
openai
|
| 4 |
+
bs4
|
| 5 |
+
python-dotenv
|
| 6 |
+
smolagents
|
| 7 |
+
pandas
|
| 8 |
+
openpyxl
|
| 9 |
+
xlrd
|