File size: 11,644 Bytes
843e76f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 | import ast
import csv
import io
import os
import re
import tempfile
from pathlib import Path
from typing import Any
import requests
from smolagents import (
CodeAgent,
DuckDuckGoSearchTool,
InferenceClientModel,
PythonInterpreterTool,
Tool,
)
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
DEFAULT_MODEL_ID = os.getenv(
"HF_MODEL_ID",
"Qwen/Qwen2.5-72B-Instruct",
)
REQUEST_TIMEOUT = 45
MAX_FILE_SIZE = 15 * 1024 * 1024
MAX_EXTRACTED_TEXT = 18000
GAIA_INSTRUCTIONS = """
You are a capable research and problem-solving agent working on GAIA
Level 1 benchmark questions.
Your objective is to find the correct answer, not merely describe a plan.
Rules:
1. Understand the question and identify exactly what is being requested.
2. Use web search when current or external information is required.
3. Open and inspect relevant web pages before relying on search snippets.
4. Use Python for calculations, data processing, and structured reasoning.
5. If a task has an attached file, use the task_file tool to retrieve it.
6. Verify important facts using reliable sources whenever possible.
7. Do not invent facts, sources, or file contents.
8. Continue working until you have a supported answer or have exhausted
the available tools.
9. Return only the answer requested by the question.
10. Do not include explanations, reasoning, citations, markdown,
or the words FINAL ANSWER in the final response.
GAIA answer formatting:
- For numerical answers, return the number without commas or units
unless the question explicitly requests them.
- For names, use the shortest unambiguous form.
- For lists, use comma-separated values.
- Preserve spelling, capitalization, and requested formatting.
- Do not add introductory or concluding text.
"""
def _safe_number(value: Any) -> float:
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise ValueError("Invalid numeric value.")
return float(value)
class _ArithmeticEvaluator(ast.NodeVisitor):
"""Evaluate basic arithmetic without using eval()."""
OPERATORS = {
ast.Add: lambda a, b: a + b,
ast.Sub: lambda a, b: a - b,
ast.Mult: lambda a, b: a * b,
ast.Div: lambda a, b: a / b,
ast.FloorDiv: lambda a, b: a // b,
ast.Mod: lambda a, b: a % b,
ast.Pow: lambda a, b: a ** b,
}
UNARY_OPERATORS = {
ast.UAdd: lambda a: +a,
ast.USub: lambda a: -a,
}
def visit_Expression(self, node):
return self.visit(node.body)
def visit_Constant(self, node):
if isinstance(node.value, bool) or not isinstance(
node.value, (int, float)
):
raise ValueError("Only numeric constants are allowed.")
return node.value
def visit_BinOp(self, node):
operator = self.OPERATORS.get(type(node.op))
if operator is None:
raise ValueError("Unsupported arithmetic operator.")
left = _safe_number(self.visit(node.left))
right = _safe_number(self.visit(node.right))
if isinstance(node.op, ast.Pow) and abs(right) > 100:
raise ValueError("Exponent is too large.")
result = operator(left, right)
if abs(result) > 1e100:
raise ValueError("Result is too large.")
return result
def visit_UnaryOp(self, node):
operator = self.UNARY_OPERATORS.get(type(node.op))
if operator is None:
raise ValueError("Unsupported unary operator.")
return operator(self.visit(node.operand))
def generic_visit(self, node):
raise ValueError("Unsupported expression.")
class CalculatorTool(Tool):
name = "calculator"
description = (
"Calculates mathematical expressions accurately. "
"Use for arithmetic, percentages, powers, and basic calculations."
)
inputs = {
"expression": {
"type": "string",
"description": "A mathematical expression, for example (125*8)/4.",
}
}
output_type = "string"
def forward(self, expression: str) -> str:
try:
if len(expression) > 300:
return "Error: expression is too long."
tree = ast.parse(expression, mode="eval")
result = _ArithmeticEvaluator().visit(tree)
return str(result)
except Exception as exc:
return f"Calculation error: {exc}"
class TaskFileTool(Tool):
name = "task_file"
description = (
"Downloads and extracts text from the file attached to the current "
"GAIA task. Supports TXT, CSV, JSON, PDF, DOCX, XLSX, and XLSM. "
"Use this tool whenever the question refers to an attached file."
)
inputs = {
"task_id": {
"type": "string",
"description": "The task_id of the current GAIA question.",
}
}
output_type = "string"
def forward(self, task_id: str) -> str:
if not task_id or not re.fullmatch(r"[A-Za-z0-9_-]+", task_id):
return "Invalid task ID."
url = f"{DEFAULT_API_URL}/files/{task_id}"
try:
response = requests.get(
url,
timeout=REQUEST_TIMEOUT,
stream=True,
)
response.raise_for_status()
content = bytearray()
for chunk in response.iter_content(chunk_size=65536):
if not chunk:
continue
content.extend(chunk)
if len(content) > MAX_FILE_SIZE:
return "File is too large to process."
if not content:
return "The task file is empty."
content_type = response.headers.get(
"Content-Type", ""
).lower()
filename = self._filename(response)
suffix = Path(filename).suffix.lower()
return self._extract(
bytes(content),
suffix,
content_type,
)
except requests.RequestException as exc:
return f"Could not download task file: {exc}"
except Exception as exc:
return f"Could not process task file: {exc}"
@staticmethod
def _filename(response: requests.Response) -> str:
disposition = response.headers.get(
"Content-Disposition", ""
)
match = re.search(
r'filename\*?=(?:UTF-8\'\')?["\']?([^"\';]+)',
disposition,
flags=re.IGNORECASE,
)
if match:
return Path(match.group(1)).name
return "task_file"
@staticmethod
def _limit(text: str) -> str:
text = text.strip()
if len(text) > MAX_EXTRACTED_TEXT:
text = text[:MAX_EXTRACTED_TEXT]
text += "\n[Text truncated due to length limit.]"
return text or "No readable text was extracted."
def _extract(
self,
content: bytes,
suffix: str,
content_type: str,
) -> str:
if suffix in {".txt", ".md", ".json", ".xml", ".html"}:
return self._limit(
content.decode("utf-8", errors="replace")
)
if suffix == ".csv" or "csv" in content_type:
text = content.decode("utf-8-sig", errors="replace")
rows = list(csv.reader(io.StringIO(text)))
output = "\n".join(
" | ".join(row) for row in rows[:300]
)
return self._limit(output)
if suffix == ".pdf" or "pdf" in content_type:
from pypdf import PdfReader
reader = PdfReader(io.BytesIO(content))
pages = []
for index, page in enumerate(reader.pages[:30]):
page_text = page.extract_text() or ""
pages.append(
f"Page {index + 1}:\n{page_text}"
)
return self._limit("\n\n".join(pages))
if suffix == ".docx":
from docx import Document
document = Document(io.BytesIO(content))
paragraphs = [
paragraph.text
for paragraph in document.paragraphs
if paragraph.text.strip()
]
return self._limit("\n".join(paragraphs))
if suffix in {".xlsx", ".xlsm"}:
from openpyxl import load_workbook
workbook = load_workbook(
io.BytesIO(content),
read_only=True,
data_only=True,
)
output = []
for sheet in workbook.worksheets:
output.append(f"Sheet: {sheet.title}")
for row in sheet.iter_rows(
max_row=300,
values_only=True,
):
values = [
str(value) if value is not None else ""
for value in row
]
if any(values):
output.append(" | ".join(values))
workbook.close()
return self._limit("\n".join(output))
return (
"The file was downloaded, but its format is not supported "
f"for text extraction. Detected extension: {suffix or 'unknown'}."
)
class BasicAgent:
"""GAIA agent using Hugging Face Inference and smolagents."""
def __init__(self):
token = (
os.getenv("HF_TOKEN")
or os.getenv("HUGGINGFACEHUB_API_TOKEN")
or os.getenv("HUGGINGFACE_TOKEN")
)
if not token:
raise RuntimeError(
"HF_TOKEN is missing. Add it as a Space Secret "
"with Inference permission."
)
self.token = token
self.model_id = DEFAULT_MODEL_ID
self.model = InferenceClientModel(
model_id=self.model_id,
token=self.token,
)
@staticmethod
def clean_answer(result: Any) -> str:
if result is None:
return ""
text = str(result).strip()
text = re.sub(
r"^\s*(FINAL ANSWER|Final Answer|Answer)\s*:\s*",
"",
text,
flags=re.IGNORECASE,
)
text = text.strip().strip('"').strip("'")
text = re.sub(r"\s+", " ", text)
return text
def __call__(
self,
question: str,
task_id: str = "",
) -> str:
if not question or not question.strip():
return ""
tools = [
DuckDuckGoSearchTool(),
PythonInterpreterTool(),
CalculatorTool(),
TaskFileTool(),
]
agent = CodeAgent(
tools=tools,
model=self.model,
max_steps=10,
add_base_tools=False,
)
prompt = (
f"{GAIA_INSTRUCTIONS}\n\n"
f"Task ID: {task_id or 'Not provided'}\n\n"
f"Question:\n{question.strip()}\n\n"
"Solve the task and return only the concise final answer."
)
result = agent.run(prompt)
return self.clean_answer(result) |