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