Update agent.py
Browse files
agent.py
CHANGED
@@ -1,24 +1,34 @@
|
|
1 |
"""
|
2 |
-
agent.py
|
3 |
-----------------------------------------------------------
|
4 |
-
|
|
|
|
|
|
|
5 |
"""
|
6 |
|
|
|
|
|
7 |
import base64
|
8 |
import mimetypes
|
9 |
import os
|
10 |
import re
|
11 |
import tempfile
|
12 |
-
import time
|
13 |
-
import random
|
14 |
from typing import List, Dict, Any, Optional
|
|
|
15 |
import requests
|
16 |
from urllib.parse import urlparse
|
17 |
|
18 |
-
from smolagents import
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
|
20 |
# --------------------------------------------------------------------------- #
|
21 |
-
#
|
22 |
# --------------------------------------------------------------------------- #
|
23 |
DEFAULT_API_URL = os.getenv(
|
24 |
"GAIA_API_URL", "https://agents-course-unit4-scoring.hf.space"
|
@@ -33,99 +43,17 @@ def _download_file(file_id: str) -> bytes:
|
|
33 |
return resp.content
|
34 |
|
35 |
# --------------------------------------------------------------------------- #
|
36 |
-
#
|
37 |
-
# --------------------------------------------------------------------------- #
|
38 |
-
class DirectClaudeModel:
|
39 |
-
"""
|
40 |
-
Direct interface to Claude via litellm that works with smolagents
|
41 |
-
This avoids the message format issues by keeping things very simple
|
42 |
-
"""
|
43 |
-
|
44 |
-
def __init__(
|
45 |
-
self,
|
46 |
-
api_key: Optional[str] = None,
|
47 |
-
temperature: float = 0.1
|
48 |
-
):
|
49 |
-
"""Initialize the Claude model"""
|
50 |
-
self.api_key = api_key or os.getenv("ANTHROPIC_API_KEY")
|
51 |
-
if not self.api_key:
|
52 |
-
raise ValueError("No Anthropic API key provided")
|
53 |
-
|
54 |
-
self.temperature = temperature
|
55 |
-
self.model_name = "anthropic/claude-3-5-sonnet-20240620"
|
56 |
-
|
57 |
-
print(f"Initialized DirectClaudeModel with {self.model_name}")
|
58 |
-
|
59 |
-
# Sleep random amount to avoid race conditions with many queries
|
60 |
-
time.sleep(random.uniform(1, 3))
|
61 |
-
|
62 |
-
def __call__(self, prompt: str, **kwargs) -> str:
|
63 |
-
"""
|
64 |
-
Simple call method that works with smolagents
|
65 |
-
|
66 |
-
Args:
|
67 |
-
prompt: The user prompt
|
68 |
-
**kwargs: Additional parameters (ignored)
|
69 |
-
|
70 |
-
Returns:
|
71 |
-
Claude's response as a string
|
72 |
-
"""
|
73 |
-
# Import here to avoid any circular imports
|
74 |
-
from litellm import completion
|
75 |
-
|
76 |
-
# Use a simple format: system message + user message
|
77 |
-
messages = [
|
78 |
-
{
|
79 |
-
"role": "system",
|
80 |
-
"content": """You are a concise, highly accurate assistant specialized in solving challenges.
|
81 |
-
Your answers should be precise, direct, and exactly match the expected format.
|
82 |
-
All answers are graded by exact string match, so format carefully!"""
|
83 |
-
},
|
84 |
-
{
|
85 |
-
"role": "user",
|
86 |
-
"content": prompt
|
87 |
-
}
|
88 |
-
]
|
89 |
-
|
90 |
-
# Add delay to avoid rate limits
|
91 |
-
time.sleep(random.uniform(0.5, 2.0))
|
92 |
-
|
93 |
-
try:
|
94 |
-
# Make API call with simple format
|
95 |
-
response = completion(
|
96 |
-
model=self.model_name,
|
97 |
-
messages=messages,
|
98 |
-
temperature=self.temperature,
|
99 |
-
max_tokens=1024,
|
100 |
-
api_key=self.api_key
|
101 |
-
)
|
102 |
-
|
103 |
-
# Extract and return the text content only
|
104 |
-
return response.choices[0].message.content
|
105 |
-
|
106 |
-
except Exception as e:
|
107 |
-
# If it's a rate limit error, wait and retry
|
108 |
-
if "rate_limit" in str(e).lower():
|
109 |
-
print(f"Rate limit hit, waiting 30 seconds: {e}")
|
110 |
-
time.sleep(30)
|
111 |
-
return self.__call__(prompt, **kwargs)
|
112 |
-
else:
|
113 |
-
print(f"Error: {str(e)}")
|
114 |
-
raise
|
115 |
-
|
116 |
-
# --------------------------------------------------------------------------- #
|
117 |
-
# Tools section - All tools used by the agent
|
118 |
# --------------------------------------------------------------------------- #
|
119 |
@tool
|
120 |
def gaia_file_reader(file_id: str) -> str:
|
121 |
"""
|
122 |
Download a GAIA attachment and return its contents.
|
123 |
-
|
124 |
Args:
|
125 |
-
file_id:
|
126 |
-
|
127 |
Returns:
|
128 |
-
|
|
|
129 |
"""
|
130 |
try:
|
131 |
raw = _download_file(file_id)
|
@@ -136,17 +64,21 @@ def gaia_file_reader(file_id: str) -> str:
|
|
136 |
except Exception as exc:
|
137 |
return f"ERROR downloading {file_id}: {exc}"
|
138 |
|
|
|
|
|
|
|
139 |
@tool
|
140 |
def save_and_read_file(content: str, filename: Optional[str] = None) -> str:
|
141 |
"""
|
142 |
Save content to a temporary file and return the path.
|
|
|
143 |
|
144 |
Args:
|
145 |
-
content: The content to save to the file
|
146 |
-
filename: Optional filename, will generate a random name if not provided
|
147 |
|
148 |
Returns:
|
149 |
-
Path to the saved file
|
150 |
"""
|
151 |
temp_dir = tempfile.gettempdir()
|
152 |
if filename is None:
|
@@ -155,64 +87,11 @@ def save_and_read_file(content: str, filename: Optional[str] = None) -> str:
|
|
155 |
else:
|
156 |
filepath = os.path.join(temp_dir, filename)
|
157 |
|
|
|
158 |
with open(filepath, 'w') as f:
|
159 |
f.write(content)
|
160 |
|
161 |
-
return f"File saved to {filepath}."
|
162 |
-
|
163 |
-
@tool
|
164 |
-
def analyze_csv_file(file_path: str, query: str) -> str:
|
165 |
-
"""
|
166 |
-
Analyze a CSV file using pandas and answer questions about it.
|
167 |
-
|
168 |
-
Args:
|
169 |
-
file_path: Path to the CSV file to analyze.
|
170 |
-
query: A question or instruction about what to analyze in the file.
|
171 |
-
|
172 |
-
Returns:
|
173 |
-
Analysis results as text.
|
174 |
-
"""
|
175 |
-
try:
|
176 |
-
import pandas as pd
|
177 |
-
df = pd.read_csv(file_path)
|
178 |
-
|
179 |
-
result = f"CSV file loaded with {len(df)} rows and {len(df.columns)} columns.\n"
|
180 |
-
result += f"Columns: {', '.join(df.columns)}\n\n"
|
181 |
-
result += "Summary statistics:\n"
|
182 |
-
result += str(df.describe())
|
183 |
-
|
184 |
-
return result
|
185 |
-
except ImportError:
|
186 |
-
return "Error: pandas is not installed."
|
187 |
-
except Exception as e:
|
188 |
-
return f"Error analyzing CSV file: {str(e)}"
|
189 |
-
|
190 |
-
@tool
|
191 |
-
def analyze_excel_file(file_path: str, query: str) -> str:
|
192 |
-
"""
|
193 |
-
Analyze an Excel file using pandas and answer questions about it.
|
194 |
-
|
195 |
-
Args:
|
196 |
-
file_path: Path to the Excel file to analyze.
|
197 |
-
query: A question or instruction about what to analyze in the file.
|
198 |
-
|
199 |
-
Returns:
|
200 |
-
Analysis results as text.
|
201 |
-
"""
|
202 |
-
try:
|
203 |
-
import pandas as pd
|
204 |
-
df = pd.read_excel(file_path)
|
205 |
-
|
206 |
-
result = f"Excel file loaded with {len(df)} rows and {len(df.columns)} columns.\n"
|
207 |
-
result += f"Columns: {', '.join(df.columns)}\n\n"
|
208 |
-
result += "Summary statistics:\n"
|
209 |
-
result += str(df.describe())
|
210 |
-
|
211 |
-
return result
|
212 |
-
except ImportError:
|
213 |
-
return "Error: pandas and openpyxl are not installed."
|
214 |
-
except Exception as e:
|
215 |
-
return f"Error analyzing Excel file: {str(e)}"
|
216 |
|
217 |
@tool
|
218 |
def download_file_from_url(url: str, filename: Optional[str] = None) -> str:
|
@@ -220,11 +99,11 @@ def download_file_from_url(url: str, filename: Optional[str] = None) -> str:
|
|
220 |
Download a file from a URL and save it to a temporary location.
|
221 |
|
222 |
Args:
|
223 |
-
url: The URL to download from
|
224 |
-
filename: Optional filename, will generate one based on URL if not provided
|
225 |
|
226 |
Returns:
|
227 |
-
Path to the downloaded file
|
228 |
"""
|
229 |
try:
|
230 |
# Parse URL to get filename if not provided
|
@@ -259,10 +138,10 @@ def extract_text_from_image(image_path: str) -> str:
|
|
259 |
Extract text from an image using pytesseract (if available).
|
260 |
|
261 |
Args:
|
262 |
-
image_path: Path to the image file
|
263 |
|
264 |
Returns:
|
265 |
-
Extracted text
|
266 |
"""
|
267 |
try:
|
268 |
# Try to import pytesseract
|
@@ -281,134 +160,410 @@ def extract_text_from_image(image_path: str) -> str:
|
|
281 |
except Exception as e:
|
282 |
return f"Error extracting text from image: {str(e)}"
|
283 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
284 |
# --------------------------------------------------------------------------- #
|
285 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
286 |
# --------------------------------------------------------------------------- #
|
287 |
class ClaudeAgent:
|
288 |
-
"""
|
289 |
|
290 |
def __init__(self):
|
291 |
-
|
292 |
try:
|
293 |
# Get API key
|
294 |
api_key = os.getenv("ANTHROPIC_API_KEY")
|
295 |
if not api_key:
|
296 |
raise ValueError("ANTHROPIC_API_KEY environment variable not found")
|
297 |
|
298 |
-
print("✅ Initializing
|
299 |
-
|
300 |
-
# Create the model with direct implementation
|
301 |
-
model = DirectClaudeModel(api_key=api_key, temperature=0.1)
|
302 |
|
303 |
-
#
|
304 |
-
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
analyze_csv_file,
|
309 |
-
analyze_excel_file,
|
310 |
-
gaia_file_reader,
|
311 |
-
download_file_from_url,
|
312 |
-
extract_text_from_image
|
313 |
-
]
|
314 |
-
|
315 |
-
# Create the CodeAgent
|
316 |
-
self.agent = CodeAgent(
|
317 |
-
tools=tools,
|
318 |
-
model=model,
|
319 |
-
additional_authorized_imports=["pandas", "numpy", "json", "re", "math"],
|
320 |
-
executor_type="local",
|
321 |
-
verbosity_level=2
|
322 |
)
|
323 |
-
|
324 |
-
print("Agent initialized successfully")
|
325 |
-
|
326 |
except Exception as e:
|
327 |
-
print(f"Error initializing
|
328 |
raise
|
329 |
|
330 |
def __call__(self, question: str) -> str:
|
331 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
332 |
try:
|
333 |
-
print(f"
|
334 |
|
335 |
-
#
|
336 |
-
|
|
|
|
|
337 |
|
338 |
-
#
|
339 |
file_match = re.search(r"<file:([^>]+)>", question)
|
340 |
if file_match:
|
341 |
file_id = file_match.group(1)
|
342 |
-
print(f"Detected file: {file_id}")
|
343 |
|
344 |
-
# Download file
|
345 |
try:
|
346 |
file_content = _download_file(file_id)
|
|
|
|
|
347 |
temp_dir = tempfile.gettempdir()
|
348 |
file_path = os.path.join(temp_dir, file_id)
|
349 |
|
|
|
350 |
with open(file_path, 'wb') as f:
|
351 |
f.write(file_content)
|
352 |
|
|
|
|
|
353 |
# Remove file tag from question
|
354 |
clean_question = re.sub(r"<file:[^>]+>", "", question).strip()
|
355 |
|
356 |
-
#
|
357 |
-
|
358 |
-
|
359 |
-
There is a file available at path: {file_path}
|
360 |
-
Use appropriate tools to analyze this file if needed.
|
361 |
-
Answer the question directly and precisely.
|
362 |
-
"""
|
363 |
except Exception as e:
|
364 |
-
print(f"Error
|
365 |
-
|
366 |
-
else:
|
367 |
-
# Handle reversed text separately
|
368 |
-
if question.startswith(".") or ".rewsna eht sa" in question:
|
369 |
-
prompt = f"""
|
370 |
-
This question is in reversed text. Here's the normal version:
|
371 |
-
{question[::-1]}
|
372 |
-
Answer the question directly and precisely.
|
373 |
-
"""
|
374 |
-
else:
|
375 |
-
prompt = question
|
376 |
-
|
377 |
-
# Execute agent with prompt
|
378 |
-
answer = self.agent.run(prompt)
|
379 |
-
|
380 |
-
# Clean up response
|
381 |
-
answer = self._clean_answer(answer)
|
382 |
-
|
383 |
-
print(f"Generated answer: {answer}")
|
384 |
-
return answer
|
385 |
|
|
|
|
|
|
|
386 |
except Exception as e:
|
387 |
-
print(f"Error: {
|
388 |
-
|
|
|
389 |
|
390 |
-
def _clean_answer(self, answer:
|
391 |
-
"""
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
#
|
396 |
-
answer
|
397 |
-
|
398 |
-
|
399 |
-
prefixes = [
|
400 |
-
"The answer is ", "Answer: ", "Final answer: ",
|
401 |
-
"The result is ", "Based on the information provided, "
|
402 |
-
]
|
403 |
-
|
404 |
-
for prefix in prefixes:
|
405 |
-
if answer.startswith(prefix):
|
406 |
-
answer = answer[len(prefix):].strip()
|
407 |
-
|
408 |
-
# Remove quotes
|
409 |
-
if (answer.startswith('"') and answer.endswith('"')) or (
|
410 |
-
answer.startswith("'") and answer.endswith("'")
|
411 |
-
):
|
412 |
-
answer = answer[1:-1].strip()
|
413 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
414 |
return answer
|
|
|
1 |
"""
|
2 |
+
agent.py – Claude-smolagents based solution for GAIA challenge
|
3 |
-----------------------------------------------------------
|
4 |
+
Environment
|
5 |
+
-----------
|
6 |
+
ANTHROPIC_API_KEY – API key from Anthropic (set in Hugging Face space secrets)
|
7 |
+
GAIA_API_URL – (optional) override for the GAIA scoring endpoint
|
8 |
"""
|
9 |
|
10 |
+
from __future__ import annotations
|
11 |
+
|
12 |
import base64
|
13 |
import mimetypes
|
14 |
import os
|
15 |
import re
|
16 |
import tempfile
|
|
|
|
|
17 |
from typing import List, Dict, Any, Optional
|
18 |
+
import json
|
19 |
import requests
|
20 |
from urllib.parse import urlparse
|
21 |
|
22 |
+
from smolagents import (
|
23 |
+
CodeAgent,
|
24 |
+
DuckDuckGoSearchTool,
|
25 |
+
PythonInterpreterTool,
|
26 |
+
LiteLLMModel,
|
27 |
+
tool,
|
28 |
+
)
|
29 |
|
30 |
# --------------------------------------------------------------------------- #
|
31 |
+
# constants & helpers
|
32 |
# --------------------------------------------------------------------------- #
|
33 |
DEFAULT_API_URL = os.getenv(
|
34 |
"GAIA_API_URL", "https://agents-course-unit4-scoring.hf.space"
|
|
|
43 |
return resp.content
|
44 |
|
45 |
# --------------------------------------------------------------------------- #
|
46 |
+
# custom tool: fetch GAIA attachments
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
47 |
# --------------------------------------------------------------------------- #
|
48 |
@tool
|
49 |
def gaia_file_reader(file_id: str) -> str:
|
50 |
"""
|
51 |
Download a GAIA attachment and return its contents.
|
|
|
52 |
Args:
|
53 |
+
file_id: identifier that appears inside a <file:...> placeholder.
|
|
|
54 |
Returns:
|
55 |
+
base64-encoded string for binary files (images, PDFs, …) or decoded
|
56 |
+
UTF-8 text for textual files.
|
57 |
"""
|
58 |
try:
|
59 |
raw = _download_file(file_id)
|
|
|
64 |
except Exception as exc:
|
65 |
return f"ERROR downloading {file_id}: {exc}"
|
66 |
|
67 |
+
# --------------------------------------------------------------------------- #
|
68 |
+
# additional tool functions
|
69 |
+
# --------------------------------------------------------------------------- #
|
70 |
@tool
|
71 |
def save_and_read_file(content: str, filename: Optional[str] = None) -> str:
|
72 |
"""
|
73 |
Save content to a temporary file and return the path.
|
74 |
+
Useful for processing files from the GAIA API.
|
75 |
|
76 |
Args:
|
77 |
+
content: The content to save to the file
|
78 |
+
filename: Optional filename, will generate a random name if not provided
|
79 |
|
80 |
Returns:
|
81 |
+
Path to the saved file
|
82 |
"""
|
83 |
temp_dir = tempfile.gettempdir()
|
84 |
if filename is None:
|
|
|
87 |
else:
|
88 |
filepath = os.path.join(temp_dir, filename)
|
89 |
|
90 |
+
# Write content to the file
|
91 |
with open(filepath, 'w') as f:
|
92 |
f.write(content)
|
93 |
|
94 |
+
return f"File saved to {filepath}. You can read this file to process its contents."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
95 |
|
96 |
@tool
|
97 |
def download_file_from_url(url: str, filename: Optional[str] = None) -> str:
|
|
|
99 |
Download a file from a URL and save it to a temporary location.
|
100 |
|
101 |
Args:
|
102 |
+
url: The URL to download from
|
103 |
+
filename: Optional filename, will generate one based on URL if not provided
|
104 |
|
105 |
Returns:
|
106 |
+
Path to the downloaded file
|
107 |
"""
|
108 |
try:
|
109 |
# Parse URL to get filename if not provided
|
|
|
138 |
Extract text from an image using pytesseract (if available).
|
139 |
|
140 |
Args:
|
141 |
+
image_path: Path to the image file
|
142 |
|
143 |
Returns:
|
144 |
+
Extracted text or error message
|
145 |
"""
|
146 |
try:
|
147 |
# Try to import pytesseract
|
|
|
160 |
except Exception as e:
|
161 |
return f"Error extracting text from image: {str(e)}"
|
162 |
|
163 |
+
@tool
|
164 |
+
def analyze_csv_file(file_path: str, query: str) -> str:
|
165 |
+
"""
|
166 |
+
Analyze a CSV file using pandas and answer a question about it.
|
167 |
+
|
168 |
+
Args:
|
169 |
+
file_path: Path to the CSV file
|
170 |
+
query: Question about the data
|
171 |
+
|
172 |
+
Returns:
|
173 |
+
Analysis result or error message
|
174 |
+
"""
|
175 |
+
try:
|
176 |
+
import pandas as pd
|
177 |
+
|
178 |
+
# Read the CSV file
|
179 |
+
df = pd.read_csv(file_path)
|
180 |
+
|
181 |
+
# Run various analyses based on the query
|
182 |
+
result = f"CSV file loaded with {len(df)} rows and {len(df.columns)} columns.\n"
|
183 |
+
result += f"Columns: {', '.join(df.columns)}\n\n"
|
184 |
+
|
185 |
+
# Add summary statistics
|
186 |
+
result += "Summary statistics:\n"
|
187 |
+
result += str(df.describe())
|
188 |
+
|
189 |
+
return result
|
190 |
+
except ImportError:
|
191 |
+
return "Error: pandas is not installed. Please install it with 'pip install pandas'."
|
192 |
+
except Exception as e:
|
193 |
+
return f"Error analyzing CSV file: {str(e)}"
|
194 |
+
|
195 |
+
@tool
|
196 |
+
def analyze_excel_file(file_path: str, query: str) -> str:
|
197 |
+
"""
|
198 |
+
Analyze an Excel file using pandas and answer a question about it.
|
199 |
+
|
200 |
+
Args:
|
201 |
+
file_path: Path to the Excel file
|
202 |
+
query: Question about the data
|
203 |
+
|
204 |
+
Returns:
|
205 |
+
Analysis result or error message
|
206 |
+
"""
|
207 |
+
try:
|
208 |
+
import pandas as pd
|
209 |
+
|
210 |
+
# Read the Excel file
|
211 |
+
df = pd.read_excel(file_path)
|
212 |
+
|
213 |
+
# Run various analyses based on the query
|
214 |
+
result = f"Excel file loaded with {len(df)} rows and {len(df.columns)} columns.\n"
|
215 |
+
result += f"Columns: {', '.join(df.columns)}\n\n"
|
216 |
+
|
217 |
+
# Add summary statistics
|
218 |
+
result += "Summary statistics:\n"
|
219 |
+
result += str(df.describe())
|
220 |
+
|
221 |
+
return result
|
222 |
+
except ImportError:
|
223 |
+
return "Error: pandas and openpyxl are not installed. Please install them with 'pip install pandas openpyxl'."
|
224 |
+
except Exception as e:
|
225 |
+
return f"Error analyzing Excel file: {str(e)}"
|
226 |
+
|
227 |
# --------------------------------------------------------------------------- #
|
228 |
+
# GAIAAgent class
|
229 |
+
# --------------------------------------------------------------------------- #
|
230 |
+
class GAIAAgent:
|
231 |
+
def __init__(
|
232 |
+
self,
|
233 |
+
api_key: Optional[str] = None,
|
234 |
+
temperature: float = 0.1,
|
235 |
+
verbose: bool = False,
|
236 |
+
system_prompt: Optional[str] = None
|
237 |
+
):
|
238 |
+
"""
|
239 |
+
Initialize a GAIAAgent with Claude model
|
240 |
+
|
241 |
+
Args:
|
242 |
+
api_key: Anthropic API key (fetched from environment if not provided)
|
243 |
+
temperature: Temperature for text generation
|
244 |
+
verbose: Enable verbose logging
|
245 |
+
system_prompt: Custom system prompt (optional)
|
246 |
+
"""
|
247 |
+
# Set verbosity
|
248 |
+
self.verbose = verbose
|
249 |
+
self.system_prompt = system_prompt or """You are a concise, highly accurate assistant specialized in solving challenges for the GAIA benchmark.
|
250 |
+
Unless explicitly required, reply with ONE short sentence.
|
251 |
+
Your answers should be precise, direct, and exactly match the expected format.
|
252 |
+
All answers are graded by exact string match, so format carefully!"""
|
253 |
+
|
254 |
+
# Get API key
|
255 |
+
if api_key is None:
|
256 |
+
api_key = os.getenv("ANTHROPIC_API_KEY")
|
257 |
+
if not api_key:
|
258 |
+
raise ValueError("No Anthropic token provided. Please set ANTHROPIC_API_KEY environment variable or pass api_key parameter.")
|
259 |
+
|
260 |
+
if self.verbose:
|
261 |
+
print(f"Using Anthropic token: {api_key[:5]}...")
|
262 |
+
|
263 |
+
# Initialize Claude model
|
264 |
+
self.model = LiteLLMModel(
|
265 |
+
model_id="anthropic/claude-3-5-sonnet-20240620", # Use Claude 3.5 Sonnet
|
266 |
+
api_key=api_key,
|
267 |
+
temperature=temperature
|
268 |
+
)
|
269 |
+
|
270 |
+
if self.verbose:
|
271 |
+
print(f"Initialized model: LiteLLMModel - anthropic/claude-3-5-sonnet-20240620")
|
272 |
+
|
273 |
+
# Initialize default tools
|
274 |
+
self.tools = [
|
275 |
+
DuckDuckGoSearchTool(),
|
276 |
+
PythonInterpreterTool(),
|
277 |
+
save_and_read_file,
|
278 |
+
download_file_from_url,
|
279 |
+
analyze_csv_file,
|
280 |
+
analyze_excel_file,
|
281 |
+
gaia_file_reader
|
282 |
+
]
|
283 |
+
|
284 |
+
# Add extract_text_from_image if PIL and pytesseract are available
|
285 |
+
try:
|
286 |
+
import pytesseract
|
287 |
+
from PIL import Image
|
288 |
+
self.tools.append(extract_text_from_image)
|
289 |
+
if self.verbose:
|
290 |
+
print("Added image processing tool")
|
291 |
+
except ImportError:
|
292 |
+
if self.verbose:
|
293 |
+
print("Image processing libraries not available")
|
294 |
+
|
295 |
+
if self.verbose:
|
296 |
+
print(f"Initialized with {len(self.tools)} tools")
|
297 |
+
|
298 |
+
# Setup imports allowed
|
299 |
+
self.imports = ["pandas", "numpy", "datetime", "json", "re", "math", "os", "requests", "csv", "urllib"]
|
300 |
+
|
301 |
+
# Initialize the CodeAgent
|
302 |
+
self.agent = CodeAgent(
|
303 |
+
tools=self.tools,
|
304 |
+
model=self.model,
|
305 |
+
additional_authorized_imports=self.imports,
|
306 |
+
executor_type="local",
|
307 |
+
verbosity_level=2 if self.verbose else 0
|
308 |
+
)
|
309 |
+
|
310 |
+
if self.verbose:
|
311 |
+
print("Agent initialized and ready")
|
312 |
+
|
313 |
+
def answer_question(self, question: str, task_file_path: Optional[str] = None) -> str:
|
314 |
+
"""
|
315 |
+
Process a GAIA benchmark question and return the answer
|
316 |
+
|
317 |
+
Args:
|
318 |
+
question: The question to answer
|
319 |
+
task_file_path: Optional path to a file associated with the question
|
320 |
+
|
321 |
+
Returns:
|
322 |
+
The answer to the question
|
323 |
+
"""
|
324 |
+
try:
|
325 |
+
if self.verbose:
|
326 |
+
print(f"Processing question: {question}")
|
327 |
+
if task_file_path:
|
328 |
+
print(f"With associated file: {task_file_path}")
|
329 |
+
|
330 |
+
# Create a context with file information if available
|
331 |
+
context = question
|
332 |
+
file_content = None
|
333 |
+
|
334 |
+
# If there's a file, read it and include its content in the context
|
335 |
+
if task_file_path:
|
336 |
+
try:
|
337 |
+
with open(task_file_path, 'r', errors='ignore') as f:
|
338 |
+
file_content = f.read()
|
339 |
+
|
340 |
+
# Determine file type from extension
|
341 |
+
import os
|
342 |
+
file_ext = os.path.splitext(task_file_path)[1].lower()
|
343 |
+
|
344 |
+
context = f"""
|
345 |
+
Question: {question}
|
346 |
+
This question has an associated file. Here is the file content:
|
347 |
+
```{file_ext}
|
348 |
+
{file_content}
|
349 |
+
```
|
350 |
+
Analyze the file content above to answer the question.
|
351 |
+
"""
|
352 |
+
except Exception as file_e:
|
353 |
+
try:
|
354 |
+
# Try to read in binary mode
|
355 |
+
with open(task_file_path, 'rb') as f:
|
356 |
+
binary_content = f.read()
|
357 |
+
|
358 |
+
# For image files
|
359 |
+
if file_ext.lower() in ['.jpg', '.jpeg', '.png', '.gif', '.bmp']:
|
360 |
+
context = f"""
|
361 |
+
Question: {question}
|
362 |
+
This question has an associated image file. Please use the extract_text_from_image tool to process it.
|
363 |
+
File path: {task_file_path}
|
364 |
+
"""
|
365 |
+
else:
|
366 |
+
context = f"""
|
367 |
+
Question: {question}
|
368 |
+
This question has an associated file at path: {task_file_path}
|
369 |
+
This is a binary file. Use appropriate tools to analyze it.
|
370 |
+
"""
|
371 |
+
except Exception as binary_e:
|
372 |
+
context = f"""
|
373 |
+
Question: {question}
|
374 |
+
This question has an associated file at path: {task_file_path}
|
375 |
+
However, there was an error reading the file: {file_e}
|
376 |
+
You can still try to answer the question based on the information provided.
|
377 |
+
"""
|
378 |
+
|
379 |
+
# Check for special cases that need specific formatting
|
380 |
+
# Reversed text questions
|
381 |
+
if question.startswith(".") or ".rewsna eht sa" in question:
|
382 |
+
context = f"""
|
383 |
+
This question appears to be in reversed text. Here's the reversed version:
|
384 |
+
{question[::-1]}
|
385 |
+
Now answer the question above. Remember to format your answer exactly as requested.
|
386 |
+
"""
|
387 |
+
|
388 |
+
# Add a prompt to ensure precise answers
|
389 |
+
full_prompt = f"""{context}
|
390 |
+
When answering, provide ONLY the precise answer requested.
|
391 |
+
Do not include explanations, steps, reasoning, or additional text.
|
392 |
+
Be direct and specific. GAIA benchmark requires exact matching answers.
|
393 |
+
For example, if asked "What is the capital of France?", respond simply with "Paris".
|
394 |
+
"""
|
395 |
+
|
396 |
+
# Run the agent with the question
|
397 |
+
answer = self.agent.run(full_prompt)
|
398 |
+
|
399 |
+
# Clean up the answer to ensure it's in the expected format
|
400 |
+
# Remove common prefixes that models often add
|
401 |
+
answer = self._clean_answer(answer)
|
402 |
+
|
403 |
+
if self.verbose:
|
404 |
+
print(f"Generated answer: {answer}")
|
405 |
+
|
406 |
+
return answer
|
407 |
+
except Exception as e:
|
408 |
+
error_msg = f"Error answering question: {e}"
|
409 |
+
if self.verbose:
|
410 |
+
print(error_msg)
|
411 |
+
return error_msg
|
412 |
+
|
413 |
+
def _clean_answer(self, answer: any) -> str:
|
414 |
+
"""
|
415 |
+
Clean up the answer to remove common prefixes and formatting
|
416 |
+
that models often add but that can cause exact match failures.
|
417 |
+
|
418 |
+
Args:
|
419 |
+
answer: The raw answer from the model
|
420 |
+
|
421 |
+
Returns:
|
422 |
+
The cleaned answer as a string
|
423 |
+
"""
|
424 |
+
# Convert non-string types to strings
|
425 |
+
if not isinstance(answer, str):
|
426 |
+
# Handle numeric types (float, int)
|
427 |
+
if isinstance(answer, float):
|
428 |
+
# Format floating point numbers properly
|
429 |
+
# Check if it's an integer value in float form (e.g., 12.0)
|
430 |
+
if answer.is_integer():
|
431 |
+
formatted_answer = str(int(answer))
|
432 |
+
else:
|
433 |
+
# For currency values that might need formatting
|
434 |
+
if abs(answer) >= 1000:
|
435 |
+
formatted_answer = f"${answer:,.2f}"
|
436 |
+
else:
|
437 |
+
formatted_answer = str(answer)
|
438 |
+
return formatted_answer
|
439 |
+
elif isinstance(answer, int):
|
440 |
+
return str(answer)
|
441 |
+
else:
|
442 |
+
# For any other type
|
443 |
+
return str(answer)
|
444 |
+
|
445 |
+
# Now we know answer is a string, so we can safely use string methods
|
446 |
+
# Normalize whitespace
|
447 |
+
answer = answer.strip()
|
448 |
+
|
449 |
+
# Remove common prefixes and formatting that models add
|
450 |
+
prefixes_to_remove = [
|
451 |
+
"The answer is ",
|
452 |
+
"Answer: ",
|
453 |
+
"Final answer: ",
|
454 |
+
"The result is ",
|
455 |
+
"To answer this question: ",
|
456 |
+
"Based on the information provided, ",
|
457 |
+
"According to the information: ",
|
458 |
+
]
|
459 |
+
|
460 |
+
for prefix in prefixes_to_remove:
|
461 |
+
if answer.startswith(prefix):
|
462 |
+
answer = answer[len(prefix):].strip()
|
463 |
+
|
464 |
+
# Remove quotes if they wrap the entire answer
|
465 |
+
if (answer.startswith('"') and answer.endswith('"')) or (answer.startswith("'") and answer.endswith("'")):
|
466 |
+
answer = answer[1:-1].strip()
|
467 |
+
|
468 |
+
return answer
|
469 |
+
|
470 |
+
# --------------------------------------------------------------------------- #
|
471 |
+
# GeminiAgent class - Wrapper around GAIAAgent
|
472 |
# --------------------------------------------------------------------------- #
|
473 |
class ClaudeAgent:
|
474 |
+
"""Claude-enhanced agent for GAIA challenge"""
|
475 |
|
476 |
def __init__(self):
|
477 |
+
# Try to initialize GAIAAgent with Claude
|
478 |
try:
|
479 |
# Get API key
|
480 |
api_key = os.getenv("ANTHROPIC_API_KEY")
|
481 |
if not api_key:
|
482 |
raise ValueError("ANTHROPIC_API_KEY environment variable not found")
|
483 |
|
484 |
+
print("✅ Initializing GAIAAgent with Claude")
|
|
|
|
|
|
|
485 |
|
486 |
+
# Create GAIAAgent instance
|
487 |
+
self.agent = GAIAAgent(
|
488 |
+
api_key=api_key,
|
489 |
+
temperature=0.1, # Use low temperature for precise answers
|
490 |
+
verbose=True, # Enable verbose logging
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
491 |
)
|
|
|
|
|
|
|
492 |
except Exception as e:
|
493 |
+
print(f"Error initializing GAIAAgent: {e}")
|
494 |
raise
|
495 |
|
496 |
def __call__(self, question: str) -> str:
|
497 |
+
"""
|
498 |
+
Process a GAIA question and return the answer
|
499 |
+
|
500 |
+
Args:
|
501 |
+
question: The question to answer
|
502 |
+
|
503 |
+
Returns:
|
504 |
+
The answer to the question
|
505 |
+
"""
|
506 |
try:
|
507 |
+
print(f"Received question: {question[:100]}..." if len(question) > 100 else f"Received question: {question}")
|
508 |
|
509 |
+
# Detect reversed text
|
510 |
+
if question.startswith(".") or ".rewsna eht sa" in question:
|
511 |
+
print("Detected reversed text question")
|
512 |
+
# GAIAAgent handles reversed text internally
|
513 |
|
514 |
+
# Detect if there's a file
|
515 |
file_match = re.search(r"<file:([^>]+)>", question)
|
516 |
if file_match:
|
517 |
file_id = file_match.group(1)
|
518 |
+
print(f"Detected file reference: {file_id}")
|
519 |
|
520 |
+
# Download the file
|
521 |
try:
|
522 |
file_content = _download_file(file_id)
|
523 |
+
|
524 |
+
# Create temporary file for the file
|
525 |
temp_dir = tempfile.gettempdir()
|
526 |
file_path = os.path.join(temp_dir, file_id)
|
527 |
|
528 |
+
# Save file content
|
529 |
with open(file_path, 'wb') as f:
|
530 |
f.write(file_content)
|
531 |
|
532 |
+
print(f"File downloaded to: {file_path}")
|
533 |
+
|
534 |
# Remove file tag from question
|
535 |
clean_question = re.sub(r"<file:[^>]+>", "", question).strip()
|
536 |
|
537 |
+
# Process question with file path
|
538 |
+
answer = self.agent.answer_question(clean_question, file_path)
|
539 |
+
return self._clean_answer(answer)
|
|
|
|
|
|
|
|
|
540 |
except Exception as e:
|
541 |
+
print(f"Error processing file: {e}")
|
542 |
+
# Fall back to processing without file
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
543 |
|
544 |
+
# Process standard question
|
545 |
+
answer = self.agent.answer_question(question)
|
546 |
+
return self._clean_answer(answer)
|
547 |
except Exception as e:
|
548 |
+
print(f"Error processing question: {e}")
|
549 |
+
error_msg = f"Unable to process question: {str(e)}"
|
550 |
+
return error_msg
|
551 |
|
552 |
+
def _clean_answer(self, answer: str) -> str:
|
553 |
+
"""
|
554 |
+
Final cleanup of answer to ensure correct format
|
555 |
+
Reuses GAIAAgent's cleaning method
|
556 |
+
"""
|
557 |
+
# Already cleaned in GAIAAgent, but do additional checks
|
558 |
+
if isinstance(answer, str):
|
559 |
+
# Remove any trailing periods and whitespace
|
560 |
+
answer = answer.rstrip(". \t\n\r")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
561 |
|
562 |
+
# Ensure it's not too long an answer - GAIA usually needs concise responses
|
563 |
+
if len(answer) > 1000:
|
564 |
+
# Try to find the first sentence or statement of the answer
|
565 |
+
sentences = answer.split('. ')
|
566 |
+
if len(sentences) > 1:
|
567 |
+
return sentences[0].strip()
|
568 |
+
|
569 |
return answer
|