Update agent.py
Browse files
agent.py
CHANGED
|
@@ -1,9 +1,9 @@
|
|
| 1 |
"""
|
| 2 |
-
agent.py β
|
| 3 |
-----------------------------------------------------------
|
| 4 |
Environment
|
| 5 |
-----------
|
| 6 |
-
|
| 7 |
GAIA_API_URL β (optional) override for the GAIA scoring endpoint
|
| 8 |
"""
|
| 9 |
|
|
@@ -13,15 +13,17 @@ import base64
|
|
| 13 |
import mimetypes
|
| 14 |
import os
|
| 15 |
import re
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
import
|
| 19 |
import requests
|
| 20 |
-
from
|
|
|
|
| 21 |
from smolagents import (
|
| 22 |
-
CodeAgent,
|
| 23 |
-
DuckDuckGoSearchTool,
|
| 24 |
PythonInterpreterTool,
|
|
|
|
| 25 |
tool,
|
| 26 |
)
|
| 27 |
|
|
@@ -40,61 +42,6 @@ def _download_file(file_id: str) -> bytes:
|
|
| 40 |
resp.raise_for_status()
|
| 41 |
return resp.content
|
| 42 |
|
| 43 |
-
# --------------------------------------------------------------------------- #
|
| 44 |
-
# model wrapper
|
| 45 |
-
# --------------------------------------------------------------------------- #
|
| 46 |
-
class GeminiModel:
|
| 47 |
-
"""
|
| 48 |
-
Minimal adapter around google-genai.Client so the instance itself is
|
| 49 |
-
callable (required by smolagents).
|
| 50 |
-
"""
|
| 51 |
-
|
| 52 |
-
def __init__(
|
| 53 |
-
self,
|
| 54 |
-
model_name: str = "gemini-2.0-flash",
|
| 55 |
-
temperature: float = 0.1,
|
| 56 |
-
max_tokens: int = 128,
|
| 57 |
-
):
|
| 58 |
-
api_key = os.getenv("GOOGLE_API_KEY")
|
| 59 |
-
if not api_key:
|
| 60 |
-
raise EnvironmentError("GOOGLE_API_KEY is not set.")
|
| 61 |
-
self.client = genai.Client(api_key=api_key)
|
| 62 |
-
|
| 63 |
-
self.model_name = model_name
|
| 64 |
-
self.temperature = temperature
|
| 65 |
-
self.max_tokens = max_tokens
|
| 66 |
-
|
| 67 |
-
# internal helper -------------------------------------------------------- #
|
| 68 |
-
def _genai_call(
|
| 69 |
-
self,
|
| 70 |
-
contents,
|
| 71 |
-
system_instruction: str,
|
| 72 |
-
) -> str:
|
| 73 |
-
resp = self.client.models.generate_content(
|
| 74 |
-
model=self.model_name,
|
| 75 |
-
contents=contents,
|
| 76 |
-
config=gtypes.GenerateContentConfig(
|
| 77 |
-
system_instruction=system_instruction,
|
| 78 |
-
temperature=self.temperature,
|
| 79 |
-
max_output_tokens=self.max_tokens,
|
| 80 |
-
),
|
| 81 |
-
)
|
| 82 |
-
return resp.text.strip()
|
| 83 |
-
|
| 84 |
-
# public helpers --------------------------------------------------------- #
|
| 85 |
-
def __call__(self, prompt: str, system_instruction: str, **__) -> str:
|
| 86 |
-
"""Used by CodeAgent for plain-text questions."""
|
| 87 |
-
return self._genai_call(prompt, system_instruction)
|
| 88 |
-
|
| 89 |
-
def call_parts(
|
| 90 |
-
self,
|
| 91 |
-
parts: List[gtypes.Part],
|
| 92 |
-
system_instruction: str,
|
| 93 |
-
) -> str:
|
| 94 |
-
"""Multimodal path used by GeminiAgent for <file:β¦> questions."""
|
| 95 |
-
user_content = gtypes.Content(role="user", parts=parts)
|
| 96 |
-
return self._genai_call([user_content], system_instruction)
|
| 97 |
-
|
| 98 |
# --------------------------------------------------------------------------- #
|
| 99 |
# custom tool: fetch GAIA attachments
|
| 100 |
# --------------------------------------------------------------------------- #
|
|
@@ -102,10 +49,8 @@ class GeminiModel:
|
|
| 102 |
def gaia_file_reader(file_id: str) -> str:
|
| 103 |
"""
|
| 104 |
Download a GAIA attachment and return its contents.
|
| 105 |
-
|
| 106 |
Args:
|
| 107 |
file_id: identifier that appears inside a <file:...> placeholder.
|
| 108 |
-
|
| 109 |
Returns:
|
| 110 |
base64-encoded string for binary files (images, PDFs, β¦) or decoded
|
| 111 |
UTF-8 text for textual files.
|
|
@@ -116,65 +61,509 @@ def gaia_file_reader(file_id: str) -> str:
|
|
| 116 |
if mime.startswith("text") or mime in ("application/json",):
|
| 117 |
return raw.decode(errors="ignore")
|
| 118 |
return base64.b64encode(raw).decode()
|
| 119 |
-
except Exception as exc:
|
| 120 |
return f"ERROR downloading {file_id}: {exc}"
|
| 121 |
|
| 122 |
# --------------------------------------------------------------------------- #
|
| 123 |
-
#
|
| 124 |
# --------------------------------------------------------------------------- #
|
| 125 |
-
|
| 126 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
-
|
| 136 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
| 163 |
try:
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
)
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
|
|
|
|
| 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 |
|
|
|
|
| 42 |
resp.raise_for_status()
|
| 43 |
return resp.content
|
| 44 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
# --------------------------------------------------------------------------- #
|
| 46 |
# custom tool: fetch GAIA attachments
|
| 47 |
# --------------------------------------------------------------------------- #
|
|
|
|
| 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.
|
|
|
|
| 61 |
if mime.startswith("text") or mime in ("application/json",):
|
| 62 |
return raw.decode(errors="ignore")
|
| 63 |
return base64.b64encode(raw).decode()
|
| 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:
|
| 85 |
+
temp_file = tempfile.NamedTemporaryFile(delete=False)
|
| 86 |
+
filepath = temp_file.name
|
| 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:
|
| 98 |
+
"""
|
| 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
|
| 110 |
+
if not filename:
|
| 111 |
+
path = urlparse(url).path
|
| 112 |
+
filename = os.path.basename(path)
|
| 113 |
+
if not filename:
|
| 114 |
+
# Generate a random name if we couldn't extract one
|
| 115 |
+
import uuid
|
| 116 |
+
filename = f"downloaded_{uuid.uuid4().hex[:8]}"
|
| 117 |
+
|
| 118 |
+
# Create temporary file
|
| 119 |
+
temp_dir = tempfile.gettempdir()
|
| 120 |
+
filepath = os.path.join(temp_dir, filename)
|
| 121 |
+
|
| 122 |
+
# Download the file
|
| 123 |
+
response = requests.get(url, stream=True)
|
| 124 |
+
response.raise_for_status()
|
| 125 |
+
|
| 126 |
+
# Save the file
|
| 127 |
+
with open(filepath, 'wb') as f:
|
| 128 |
+
for chunk in response.iter_content(chunk_size=8192):
|
| 129 |
+
f.write(chunk)
|
| 130 |
+
|
| 131 |
+
return f"File downloaded to {filepath}. You can now process this file."
|
| 132 |
+
except Exception as e:
|
| 133 |
+
return f"Error downloading file: {str(e)}"
|
| 134 |
|
| 135 |
+
@tool
|
| 136 |
+
def extract_text_from_image(image_path: str) -> str:
|
| 137 |
+
"""
|
| 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
|
| 148 |
+
import pytesseract
|
| 149 |
+
from PIL import Image
|
| 150 |
+
|
| 151 |
+
# Open the image
|
| 152 |
+
image = Image.open(image_path)
|
| 153 |
+
|
| 154 |
+
# Extract text
|
| 155 |
+
text = pytesseract.image_to_string(image)
|
| 156 |
+
|
| 157 |
+
return f"Extracted text from image:\n\n{text}"
|
| 158 |
+
except ImportError:
|
| 159 |
+
return "Error: pytesseract is not installed. Please install it with 'pip install pytesseract' and ensure Tesseract OCR is installed on your system."
|
| 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
|