2tyoon's picture
Attachment fallback, answer cleanup, timeouts
234def3 verified
Raw History Blame Contribute Delete
6.67 kB
"""GAIA level-1 agent for the Hugging Face Agents Course (Unit 4 final assignment).
Built on smolagents' CodeAgent. The LLM backend goes through LiteLLM, so any
provider works by setting MODEL_ID and that provider's API key env var, e.g.
MODEL_ID=anthropic/claude-sonnet-5-5 + ANTHROPIC_API_KEY
MODEL_ID=gemini/gemini-2.5-flash + GEMINI_API_KEY
MODEL_ID=openai/gpt-4.1 + OPENAI_API_KEY
"""
import base64
import io
import mimetypes
import os
import re
import tempfile
import requests
from dotenv import load_dotenv
from smolagents import (
CodeAgent,
DuckDuckGoSearchTool,
LiteLLMModel,
VisitWebpageTool,
WikipediaSearchTool,
tool,
)
load_dotenv()
API_URL = "https://agents-course-unit4-scoring.hf.space"
MODEL_ID = os.getenv("MODEL_ID", "anthropic/claude-sonnet-5-5")
FILES_DIR = os.path.join(tempfile.gettempdir(), "gaia_files")
def download_task_file(task_id: str, file_name: str) -> str | None:
"""Download the attachment for a task and return its local path."""
if not file_name:
return None
os.makedirs(FILES_DIR, exist_ok=True)
path = os.path.join(FILES_DIR, file_name)
if os.path.exists(path):
return path
resp = requests.get(f"{API_URL}/files/{task_id}", timeout=60)
if resp.ok:
with open(path, "wb") as f:
f.write(resp.content)
return path
# The scoring server sometimes lacks the attachment; fall back to the same
# file in the (gated) GAIA dataset. Only the attachment is fetched.
from huggingface_hub import hf_hub_download
return hf_hub_download(
"gaia-benchmark/GAIA",
f"2023/validation/{file_name}",
repo_type="dataset",
local_dir=FILES_DIR,
)
def _llm_text(messages: list[dict]) -> str:
import litellm
resp = litellm.completion(model=MODEL_ID, messages=messages)
return resp.choices[0].message.content
@tool
def analyze_image(image_path: str, question: str) -> str:
"""Look at a local image file with a vision model and answer a question about it.
Args:
image_path: Local path to the image (png, jpg, ...).
question: What you want to know about the image. Be specific.
"""
mime = mimetypes.guess_type(image_path)[0] or "image/png"
with open(image_path, "rb") as f:
b64 = base64.b64encode(f.read()).decode()
return _llm_text([
{
"role": "user",
"content": [
{"type": "image_url", "image_url": {"url": f"data:{mime};base64,{b64}"}},
{"type": "text", "text": question},
],
}
])
@tool
def transcribe_audio(audio_path: str) -> str:
"""Transcribe a local audio file (mp3, wav, ...) to text with Whisper.
Args:
audio_path: Local path to the audio file.
"""
import whisper # openai-whisper, runs locally on CPU
model = whisper.load_model(os.getenv("WHISPER_MODEL", "small"))
return model.transcribe(audio_path)["text"]
@tool
def youtube_transcript(url: str) -> str:
"""Fetch the spoken transcript (captions) of a YouTube video.
Args:
url: The YouTube video URL.
"""
from youtube_transcript_api import YouTubeTranscriptApi
m = re.search(r"(?:v=|youtu\.be/)([\w-]{11})", url)
if not m:
return "Could not parse a video id from the URL."
try:
fetched = YouTubeTranscriptApi().fetch(m.group(1))
return "\n".join(f"[{s.start:.0f}s] {s.text}" for s in fetched)
except Exception as e:
return f"Transcript unavailable: {e}"
@tool
def read_excel(path: str) -> str:
"""Read every sheet of an Excel/CSV file and return it as text tables.
Args:
path: Local path to the .xlsx / .xls / .csv file.
"""
import pandas as pd
if path.lower().endswith(".csv"):
return pd.read_csv(path).to_string()
sheets = pd.read_excel(path, sheet_name=None)
return "\n\n".join(f"## Sheet: {name}\n{df.to_string()}" for name, df in sheets.items())
@tool
def read_text_file(path: str) -> str:
"""Read a local text/code file and return its content.
Args:
path: Local path to the file.
"""
with open(path, encoding="utf-8", errors="replace") as f:
return f.read()
SYSTEM_HINT = """You are a precise research assistant solving a GAIA benchmark question.
Use the tools to look things up and verify; do not guess when you can check.
Rules for the final answer (it is graded by EXACT MATCH):
- Call final_answer() with ONLY the answer: no explanation, no units unless asked, no "FINAL ANSWER" prefix.
- A number: plain digits, no thousands separators, no $ or % unless asked.
- A string: as few words as possible, no articles, no abbreviations unless asked.
- A list: comma-separated, following any ordering/format the question asks for.
"""
class GaiaAgent:
def __init__(self):
model = LiteLLMModel(model_id=MODEL_ID, timeout=180, num_retries=2)
self.agent = CodeAgent(
model=model,
tools=[
DuckDuckGoSearchTool(max_results=8),
VisitWebpageTool(max_output_length=60000),
WikipediaSearchTool(user_agent="gaia-agent (hf agents course)"),
youtube_transcript,
analyze_image,
transcribe_audio,
read_excel,
read_text_file,
],
additional_authorized_imports=[
"pandas", "numpy", "json", "re", "math", "datetime", "collections",
"itertools", "statistics", "requests", "bs4", "subprocess", "os",
],
max_steps=15,
verbosity_level=1,
)
def __call__(self, question: str, file_path: str | None = None) -> str:
prompt = SYSTEM_HINT + "\nQuestion:\n" + question
if file_path:
prompt += f"\n\nThe attached file is available locally at: {file_path}"
answer = str(self.agent.run(prompt)).strip()
answer = re.sub(r"^\s*FINAL ANSWER:\s*", "", answer, flags=re.I).strip()
if len(answer) > 60 or "\n" in answer or "<" in answer:
answer = self._shorten(question, answer)
return answer
def _shorten(self, question: str, answer: str) -> str:
"""Reduce a wordy agent reply to the bare answer the grader expects."""
return _llm_text([
{
"role": "user",
"content": SYSTEM_HINT
+ f"\nQuestion:\n{question}\n\nDraft reply:\n{answer}\n\n"
"Reply with ONLY the final answer extracted from the draft, nothing else.",
}
]).strip()