murphynetworks commited on
Commit
ebb5880
·
1 Parent(s): e365088

docs: Update README and fix agent compatibility

Browse files

- Update README.md with comprehensive documentation
- Fix agent.py to work with newer smolagents API
- Update requirements.txt with additional dependencies

Files changed (3) hide show
  1. README.md +70 -37
  2. agent.py +84 -38
  3. requirements.txt +12 -2
README.md CHANGED
@@ -1,13 +1,27 @@
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
 
@@ -31,57 +45,75 @@ This project implements an AI agent using the smolagents library to answer quest
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
 
@@ -95,6 +127,7 @@ For submission, the API requires:
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
 
 
1
+ # Enhanced Agent for API Question Evaluation
2
 
3
+ This project implements an advanced AI agent capable of answering questions from an evaluation API. The agent uses OpenRouter to access LLMs and is equipped with specialized tools for handling different types of data and performing various tasks.
4
+
5
+ ## Key Features
6
+
7
+ - **Multiple Specialized Tools**: Web search, Excel analysis, audio transcription, code execution, and more
8
+ - **File Attachment Handling**: Automatically downloads and processes file attachments from the API
9
+ - **Minimal Answer Enforcement**: Ensures answers are concise and match the expected format
10
+ - **Robust Error Handling**: Prevents crashes with fallbacks for all tool operations
11
+ - **Comprehensive Logging**: Detailed colorful logs for all agent operations
12
+ - **Multi-Engine Web Search**: Falls back between search engines for more reliable results
13
 
14
  ## Project Structure
15
 
16
+ - **enhanced_agent.py**: Main agent implementation with all specialized tools integrated
17
+ - **tools/**: Directory containing specialized tool implementations
18
+ - **attachment_handler.py**: File download and cleanup utilities
19
+ - **audio_transcription.py**: Audio transcription with specialized extractors
20
+ - **enhanced_web_search.py**: Multi-engine web search with fallbacks
21
+ - **code_execution.py**: Safe Python code execution in sandbox
22
+ - **enhanced_integration.py**: Script to integrate the enhanced agent with the evaluation system
23
+ - **run_enhanced_evaluation.py**: Script to run the enhanced agent against the API
24
+ - **test_enhanced_agent.py**: Test script for the enhanced agent with various question types
25
 
26
  ## Setup Instructions
27
 
 
45
  ```
46
  cp .env.example .env
47
  ```
48
+ - Edit the `.env` file with the following variables:
49
+ ```
50
+ OPENROUTER_API_KEY=your_api_key_here
51
+ OPENROUTER_MODEL=anthropic/claude-3-5-sonnet
52
+ USERNAME=your_username_here
53
+ CODE_LINK=your_github_repo_link_here
54
+ ```
55
 
56
  ## Usage
57
 
58
+ ### Running the Evaluation
 
 
59
 
60
  ```bash
61
+ # Run the evaluation against the API
62
+ python run_enhanced_evaluation.py
63
 
64
+ # Use a different model
65
+ python run_enhanced_evaluation.py --model anthropic/claude-3-opus-20240229
 
66
 
67
+ # Run with parallel workers (experimental)
68
+ python run_enhanced_evaluation.py --workers 2
69
+
70
+ # Provide username and code link via command line
71
+ python run_enhanced_evaluation.py --username "YourName" --code-link "https://github.com/yourusername/your-repo"
72
+ ```
73
 
74
+ ### Testing the Agent
75
 
76
  ```bash
77
+ # Run tests with basic questions
78
+ python test_enhanced_agent.py
79
 
80
+ # Test with a specific model
81
+ python test_enhanced_agent.py --model openai/gpt-4o
 
 
82
 
83
+ # Test file attachment handling with a task ID
84
+ python test_enhanced_agent.py --task-id your_task_id_here
85
 
86
+ # Use custom test questions from a JSON file
87
+ python test_enhanced_agent.py --questions custom_questions.json
88
+ ```
89
 
90
+ ## How It Works
 
 
 
91
 
92
+ 1. **Question Processing**: The agent analyzes the question to determine what tools are needed
93
+ 2. **Tool Selection**: The appropriate specialized tools are invoked based on the question type
94
+ 3. **File Handling**: If a file attachment is referenced, it's downloaded and processed
95
+ 4. **Answer Generation**: The LLM generates a detailed answer using the tool outputs
96
+ 5. **Answer Enforcement**: The answer is post-processed to ensure it's minimal and correctly formatted
97
+ 6. **Submission**: The minimal answer is submitted to the evaluation API
98
 
99
+ ## Agent Tools
100
+
101
+ The enhanced agent is equipped with the following specialized tools:
102
 
103
+ 1. **Enhanced Web Search**: Multi-engine web search with automatic fallbacks
104
+ 2. **Web Browsing**: Fetch and extract content from a specific URL
105
+ 3. **Audio Transcription**: Transcribe audio files and extract specific information
106
+ 4. **Excel Analysis**: Analyze Excel files and extract data based on queries
107
+ 5. **Code Execution**: Safely execute Python code to determine outputs
108
+ 6. **File Reading**: Read and process files attached to questions
109
+ 7. **Image Analysis**: Analyze images and extract information
110
+ 8. **Attachment Handler**: Download and manage file attachments from the API
111
 
112
  ## Evaluation API
113
 
114
  The agent is evaluated using the API at `https://agents-course-unit4-scoring.hf.space`, which provides:
115
 
116
  - `/questions`: All questions for evaluation
 
117
  - `/files/{task_id}`: Files associated with questions
118
  - `/submit`: Endpoint for submitting answers
119
 
 
127
 
128
  ## Important Notes
129
 
130
+ - The agent is designed to provide minimal answers without explanations or reasoning
131
+ - Special handling is implemented for different question types (who/what/where, lists, yes/no, etc.)
132
+ - The agent can automatically download and process file attachments referenced in questions
133
+ - Multiple fallbacks and error recovery mechanisms ensure the agent always returns a response
agent.py CHANGED
@@ -7,16 +7,26 @@ 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(
@@ -55,15 +65,23 @@ class WebSearchTool(Tool):
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"
@@ -95,15 +113,23 @@ class WebBrowseTool(Tool):
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}"
@@ -123,15 +149,23 @@ class ReadFileTool(Tool):
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
@@ -141,15 +175,27 @@ class CalculateTool(Tool):
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}"
@@ -245,8 +291,8 @@ Be precise and focus only on answering the question asked. Do not add disclaimer
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):
@@ -257,7 +303,7 @@ Be precise and focus only on answering the question asked. Do not add disclaimer
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:
 
7
  from bs4 import BeautifulSoup
8
  from smolagents import ToolCallingAgent, Tool
9
 
10
+ from smolagents import Tool
11
+
12
  class WebSearchTool(Tool):
 
 
 
 
 
13
  def __init__(self):
14
+ super().__init__(
15
+ name="web_search",
16
+ description="Search the web for information on a query. Useful for finding up-to-date information.",
17
+ input_schema={
18
+ "type": "object",
19
+ "properties": {
20
+ "query": {
21
+ "type": "string",
22
+ "description": "The search query"
23
+ }
24
+ },
25
+ "required": ["query"]
26
+ }
27
+ )
28
 
29
+ def _run(self, query):
30
  try:
31
  # Use a search engine API to get results
32
  response = requests.get(
 
65
  return f"Error searching the web: {str(e)}"
66
 
67
  class WebBrowseTool(Tool):
 
 
 
 
 
68
  def __init__(self):
69
+ super().__init__(
70
+ name="web_browse",
71
+ description="Browse a specific webpage and extract its content.",
72
+ input_schema={
73
+ "type": "object",
74
+ "properties": {
75
+ "url": {
76
+ "type": "string",
77
+ "description": "The URL of the webpage to browse"
78
+ }
79
+ },
80
+ "required": ["url"]
81
+ }
82
+ )
83
 
84
+ def _run(self, url):
85
  try:
86
  headers = {
87
  "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"
 
113
  return f"Error accessing {url}: {str(e)}"
114
 
115
  class ReadFileTool(Tool):
 
 
 
 
 
116
  def __init__(self):
117
+ super().__init__(
118
+ name="read_file",
119
+ description="Read the content of a file.",
120
+ input_schema={
121
+ "type": "object",
122
+ "properties": {
123
+ "file_path": {
124
+ "type": "string",
125
+ "description": "The path to the file to read"
126
+ }
127
+ },
128
+ "required": ["file_path"]
129
+ }
130
+ )
131
 
132
+ def _run(self, file_path):
133
  try:
134
  if not os.path.exists(file_path):
135
  return f"Error: File not found at {file_path}"
 
149
  return f"Error reading file: {str(e)}"
150
 
151
  class CalculateTool(Tool):
 
 
 
 
 
152
  def __init__(self):
153
+ super().__init__(
154
+ name="calculate",
155
+ description="Perform a calculation.",
156
+ input_schema={
157
+ "type": "object",
158
+ "properties": {
159
+ "expression": {
160
+ "type": "string",
161
+ "description": "The mathematical expression to calculate"
162
+ }
163
+ },
164
+ "required": ["expression"]
165
+ }
166
+ )
167
 
168
+ def _run(self, expression):
169
  try:
170
  # Be very careful with eval - in production this should be replaced with a safer alternative
171
  # like the `simpleeval` library
 
175
  return f"Error calculating '{expression}': {str(e)}"
176
 
177
  class AnalyzeExcelTool(Tool):
 
 
 
 
 
178
  def __init__(self):
179
+ super().__init__(
180
+ name="analyze_excel",
181
+ description="Analyze an Excel file and extract data from it.",
182
+ input_schema={
183
+ "type": "object",
184
+ "properties": {
185
+ "file_path": {
186
+ "type": "string",
187
+ "description": "The path to the Excel file"
188
+ },
189
+ "query": {
190
+ "type": "string",
191
+ "description": "The specific data or analysis you want from the file"
192
+ }
193
+ },
194
+ "required": ["file_path", "query"]
195
+ }
196
+ )
197
 
198
+ def _run(self, file_path, query):
199
  try:
200
  if not os.path.exists(file_path):
201
  return f"Error: File not found at {file_path}"
 
291
  self.agent = ToolCallingAgent(
292
  model=self.model,
293
  tools=get_agent_tools(),
294
+ system=system_message,
295
+ client=self.client
296
  )
297
 
298
  def __call__(self, question, context=None):
 
303
  question += f"\nYou can access this file using the read_file tool with the path: {context.get('file_path')}"
304
 
305
  try:
306
+ response = self.agent.run(question)
307
  # Make sure we're not including "FINAL ANSWER:" in the response
308
  final_answer = response
309
  if "FINAL ANSWER:" in final_answer:
requirements.txt CHANGED
@@ -3,7 +3,17 @@ requests
3
  openai
4
  bs4
5
  python-dotenv
6
- smolagents
7
  pandas
8
  openpyxl
9
- xlrd
 
 
 
 
 
 
 
 
 
 
 
 
3
  openai
4
  bs4
5
  python-dotenv
 
6
  pandas
7
  openpyxl
8
+ xlrd
9
+ concurrent-log-handler
10
+ colorama
11
+ retrying
12
+ beautifulsoup4
13
+ tiktoken
14
+ difflib
15
+ python-magic
16
+ pillow
17
+ nltk
18
+ regex
19
+ loguru