itispourya commited on
Commit
b97209a
·
verified ·
1 Parent(s): 81917a3

Create agent.py

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