itispourya's picture
Create agent.py
36de3aa verified
Raw History Blame
11.2 kB
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)