ficarbs's picture
Update app.py
a54ce93 verified
Raw History Blame Contribute Delete
15.2 kB
import os
import re
import json
import time
import base64
import threading
import gradio as gr
import requests
import pandas as pd
from smolagents import CodeAgent, OpenAIServerModel, VisitWebpageTool, tool
try: # ZeroGPU Spaces require at least one @spaces.GPU function to start
import spaces
@spaces.GPU
def _gpu_placeholder():
return None
except Exception:
pass
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
GEMINI_BASE = "https://generativelanguage.googleapis.com/v1beta/openai/"
GEMINI_NATIVE = "https://generativelanguage.googleapis.com/v1beta/models"
MODEL_ID = os.getenv("MODEL_ID", "gemini-flash-lite-latest")
MIN_SECONDS_BETWEEN_CALLS = float(os.getenv("MIN_SECONDS_BETWEEN_CALLS", "6")) # free tier: 15 RPM
FILES_DIR = "/tmp/task_files"
CACHE_PATH = "/tmp/answers_cache.json"
os.makedirs(FILES_DIR, exist_ok=True)
# ---------------------------------------------------------------- rate limiting
_lock = threading.Lock()
_last_call = [0.0]
def _throttle():
with _lock:
wait = MIN_SECONDS_BETWEEN_CALLS - (time.time() - _last_call[0])
if wait > 0:
time.sleep(wait)
_last_call[0] = time.time()
def _is_rate_limit(e: Exception) -> bool:
s = str(e).lower()
return "429" in s or "rate" in s or "quota" in s or "resource_exhausted" in s
class ThrottledGeminiModel(OpenAIServerModel):
"""Gemini via its OpenAI-compatible endpoint, spaced out and retried to fit the free tier."""
def generate(self, *args, **kwargs):
for attempt in range(8):
_throttle()
try:
out = super().generate(*args, **kwargs)
if not (out.content or "").strip() and attempt < 7:
continue # empty reply: ask again
return out
except Exception as e:
if not _is_rate_limit(e) or attempt == 7:
raise
time.sleep(20 * (attempt + 1))
def _gemini_native(parts: list, tools: list | None = None, retries: int = 8) -> str:
"""Calls Gemini's native generateContent API (needed for audio, YouTube and search grounding)."""
body = {"contents": [{"role": "user", "parts": parts}]}
if tools:
body["tools"] = tools
url = f"{GEMINI_NATIVE}/{MODEL_ID}:generateContent"
for attempt in range(retries):
_throttle()
r = requests.post(url, params={"key": os.getenv("GEMINI_API_KEY")}, json=body, timeout=300)
if r.status_code == 429 or r.status_code >= 500:
if attempt < retries - 1:
time.sleep(20 * (attempt + 1))
continue
r.raise_for_status()
cands = r.json().get("candidates") or []
if not cands:
return "No response."
return "".join(p.get("text", "") for p in cands[0].get("content", {}).get("parts", []))
return "Model unavailable (rate limited)."
# ---------------------------------------------------------------- attachments
def fetch_task_file(task_id: str, file_name: str) -> str | None:
"""Downloads a task's attachment. The scoring API's /files route is tried first; it currently
returns 404, so the same attachment is fetched from the gated GAIA dataset (attachment only)."""
if not file_name:
return None
path = os.path.join(FILES_DIR, file_name)
if os.path.exists(path):
return path
try:
r = requests.get(f"{DEFAULT_API_URL}/files/{task_id}", timeout=60)
if r.status_code == 200 and r.content:
open(path, "wb").write(r.content)
return path
except Exception:
pass
try:
from huggingface_hub import hf_hub_download
return hf_hub_download(
repo_id="gaia-benchmark/GAIA",
repo_type="dataset",
filename=f"2023/validation/{file_name}",
token=os.getenv("HF_TOKEN"),
local_dir=FILES_DIR,
)
except Exception as e:
print(f"Could not fetch attachment {file_name}: {e}")
return None
def file_preview(path: str) -> str:
low = path.lower()
try:
if low.endswith((".py", ".txt", ".csv", ".json", ".md")):
return open(path, encoding="utf-8", errors="replace").read()[:6000]
if low.endswith((".xlsx", ".xls")):
sheets = pd.read_excel(path, sheet_name=None)
return "\n\n".join(f"[sheet {k}]\n{v.to_string()}" for k, v in sheets.items())[:8000]
except Exception as e:
return f"(preview failed: {e})"
return ""
_MIME = {".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp",
".mp3": "audio/mp3", ".wav": "audio/wav", ".m4a": "audio/mp4", ".flac": "audio/flac",
".pdf": "application/pdf"}
# ---------------------------------------------------------------- tools
_grounding_ok = [True]
def _wiki_search(query: str) -> str:
r = requests.get(
"https://en.wikipedia.org/w/api.php",
params={"action": "query", "list": "search", "srsearch": query, "srlimit": 6, "format": "json"},
headers={"User-Agent": "gaia-agent-course/1.0"},
timeout=60,
).json()
hits = r.get("query", {}).get("search", [])
return "\n\n".join(
f"Wikipedia: {h['title']}\n{re.sub(r'<[^>]+>', '', h['snippet'])}" for h in hits
)
@tool
def web_search(query: str) -> str:
"""Searches the web and returns results with source URLs (plus matching Wikipedia articles).
Use specific queries. Open the returned URLs with visit_webpage or wikipedia_page to verify details.
Args:
query: The search query.
"""
out = []
if _grounding_ok[0]:
try:
text = _gemini_native(
[{"text": f"Search the web and report the facts relevant to: {query}\n"
"Quote exact numbers, names and dates, and list the source URLs."}],
tools=[{"google_search": {}}],
retries=1,
)
if text and "rate limited" not in text:
out.append(text[:5000])
else:
_grounding_ok[0] = False # quota exhausted: stop trying for this run
except Exception as e:
print(f"grounded search failed: {e}")
_grounding_ok[0] = False
if not out:
try:
from duckduckgo_search import DDGS
res = DDGS().text(query, max_results=6)
out.append("\n\n".join(f"{r['title']}\n{r['href']}\n{r['body']}" for r in res))
except Exception as e:
print(f"ddg failed: {e}")
try:
out.append(_wiki_search(query))
except Exception:
pass
return "\n\n---\n\n".join(o for o in out if o) or "No results."
@tool
def wikipedia_page(title: str, section: str = "") -> str:
"""Returns the wikitext of an English Wikipedia page (tables and lists included). Good for
discographies, rosters and statistics. Long pages are cut, so pass section (a heading such as
'Discography' or 'Studio albums') to get that section in full; the list of headings is always shown.
Args:
title: The exact Wikipedia article title, e.g. 'Mercedes Sosa'.
section: Optional heading to return in full (case-insensitive substring match).
"""
r = requests.get(
"https://en.wikipedia.org/w/api.php",
params={"action": "parse", "page": title, "prop": "wikitext", "format": "json", "redirects": 1},
headers={"User-Agent": "gaia-agent-course/1.0"},
timeout=60,
)
data = r.json()
if "error" in data:
return f"Page not found. Matching articles:\n{_wiki_search(title)}"
text = data["parse"]["wikitext"]["*"]
heads = re.findall(r"^(=+)\s*(.+?)\s*\1\s*$", text, flags=re.M)
toc = "Sections: " + " | ".join(h[1] for h in heads)
if section:
m = None
for lvl, h in heads:
if section.lower() in h.lower():
m = re.search(rf"^{lvl}\s*{re.escape(h)}\s*{lvl}\s*$", text, flags=re.M)
break
if m:
rest = text[m.end():]
nxt = re.search(rf"^={{2,{len(lvl)}}}[^=].*?={{2,{len(lvl)}}}\s*$", rest, flags=re.M)
return toc + "\n\n" + rest[: nxt.start() if nxt else len(rest)][:25000]
return toc + f"\n\n(No section matching '{section}'.)"
return toc + "\n\n" + text[:15000]
@tool
def analyze_file(path: str, question: str) -> str:
"""Asks a multimodal model about a local image, audio or PDF file (e.g. describe a chess
board position square by square, transcribe an audio recording, read a document).
Args:
path: Local path of the file.
question: What to ask about the file.
"""
ext = os.path.splitext(path)[1].lower()
mime = _MIME.get(ext, "application/octet-stream")
data = base64.b64encode(open(path, "rb").read()).decode()
return _gemini_native([{"inline_data": {"mime_type": mime, "data": data}}, {"text": question}])
@tool
def youtube_video(url: str, question: str) -> str:
"""Watches a YouTube video (images and audio) and answers a question about it.
Args:
url: The YouTube video URL.
question: What to find out from the video.
"""
return _gemini_native([{"file_data": {"file_uri": url}}, {"text": question}])
INSTRUCTIONS = """You answer GAIA benchmark questions. Work step by step with tools; never guess.
- Facts: web_search, then open the best sources with visit_webpage or wikipedia_page and read the exact data.
For Wikipedia questions prefer wikipedia_page. Count or compute with Python code, not in your head.
- Attachments: the prompt gives the local path. Read .py/.xlsx/.csv with Python (pandas for Excel);
for images, audio and PDFs use analyze_file. For YouTube links use youtube_video.
- Read the question literally (it may be reversed text, a puzzle, or have tricky constraints) and
check your answer against every constraint before finishing.
- Call final_answer with ONLY the answer: a number (no units or thousands separators unless asked),
a few words (no articles or abbreviations unless asked), or a comma-separated list in the requested
order and format. Never include 'FINAL ANSWER', explanations or trailing punctuation."""
class GaiaAgent:
def __init__(self):
model = ThrottledGeminiModel(
model_id=MODEL_ID,
api_base=GEMINI_BASE,
api_key=os.getenv("GEMINI_API_KEY"),
client_kwargs={"max_retries": 2},
)
self.agent = CodeAgent(
tools=[web_search, wikipedia_page, VisitWebpageTool(max_output_length=12000),
analyze_file, youtube_video],
model=model,
additional_authorized_imports=["*"],
max_steps=10,
max_print_outputs_length=6000,
code_block_tags="markdown",
instructions=INSTRUCTIONS,
)
def __call__(self, question: str, task_id: str = "", file_name: str = "") -> str:
prompt = f"Question: {question}"
if file_name:
path = fetch_task_file(task_id, file_name)
if path:
prompt += f"\n\nAttached file '{file_name}' is saved at: {path}"
prev = file_preview(path)
if prev:
prompt += f"\nFile contents preview:\n{prev}"
else:
prompt += f"\n\n(The attached file '{file_name}' could not be downloaded.)"
ans = str(self.agent.run(prompt)).strip()
if not ans or "```" in ans or re.search(r"\w+\(.*\)", ans) and "=" in ans or ans == "None":
ans = str(self.agent.run(prompt)).strip() # answer looked like code: one more attempt
ans = re.sub(r"(?i)^final answer\s*:\s*", "", ans).strip().strip('"').strip()
return ans.rstrip(".")
def _load_cache() -> dict:
try:
return json.load(open(CACHE_PATH))
except Exception:
return {}
def run_and_submit_all(profile: gr.OAuthProfile | None):
space_id = os.getenv("SPACE_ID")
if not profile:
return "Please Login to Hugging Face with the button.", None
username = f"{profile.username}"
if not os.getenv("GEMINI_API_KEY"):
return "GEMINI_API_KEY secret is missing in the Space settings.", None
try:
agent = GaiaAgent()
except Exception as e:
return f"Error initializing agent: {e}", None
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
try:
response = requests.get(f"{DEFAULT_API_URL}/questions", timeout=30)
response.raise_for_status()
questions_data = response.json()
except Exception as e:
return f"Error fetching questions: {e}", None
cache = _load_cache() # answers from an interrupted earlier run in this session are reused
results_log, answers_payload = [], []
for item in questions_data:
task_id, question_text = item.get("task_id"), item.get("question")
if not task_id or question_text is None:
continue
if task_id in cache and not cache[task_id].startswith("AGENT ERROR"):
ans = cache[task_id]
else:
try:
ans = agent(question_text, task_id, item.get("file_name", ""))
except Exception as e:
ans = f"AGENT ERROR: {e}"
cache[task_id] = ans
json.dump(cache, open(CACHE_PATH, "w"))
print(f"[{task_id}] -> {ans}")
answers_payload.append({"task_id": task_id, "submitted_answer": ans})
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": ans})
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
try:
response = requests.post(f"{DEFAULT_API_URL}/submit", json=submission_data, timeout=120)
response.raise_for_status()
r = response.json()
status = (
f"Submission Successful!\nUser: {r.get('username')}\n"
f"Overall Score: {r.get('score', 'N/A')}% "
f"({r.get('correct_count', '?')}/{r.get('total_attempted', '?')} correct)\n"
f"Message: {r.get('message', '')}"
)
return status, pd.DataFrame(results_log)
except Exception as e:
return f"Submission Failed: {e}", pd.DataFrame(results_log)
with gr.Blocks() as demo:
gr.Markdown("# GAIA Agent Evaluation Runner")
gr.Markdown(
"smolagents CodeAgent on Gemini (free tier) with web search, Wikipedia, webpage, file and video tools.\n\n"
"1. Add GEMINI_API_KEY (and HF_TOKEN with gated-repo read access) as Space secrets.\n"
"2. Log in below.\n3. Click run: the agent answers all questions and submits."
)
gr.LoginButton()
run_button = gr.Button("Run Evaluation & Submit All Answers")
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
if __name__ == "__main__":
demo.launch(debug=True, share=False)