Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011121314156 unmodified lines2223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711724 unmodified lines1771781791801811821831841 unmodified line18618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721810 unmodified lines229230231232233234235import osimport reimport gradio as grimport requestsimport pandas as pdfrom smolagents import (CodeAgent,OpenAIServerModel,DuckDuckGoSearchTool,VisitWebpageTool,tool,)try: # ZeroGPU Spaces require at least one @spaces.GPU function to startimport spaces6 unmodified linesDEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"GEMINI_BASE = "https://generativelanguage.googleapis.com/v1beta/openai/"MODEL_ID = os.getenv("MODEL_ID", "gemini-flash-lite-latest")def _gemini_client():from openai import OpenAIreturn OpenAI(base_url=GEMINI_BASE, api_key=os.getenv("GEMINI_API_KEY"), max_retries=6)FILES_DIR = "/tmp/task_files"os.makedirs(FILES_DIR, exist_ok=True)@tooldef download_task_file(task_id: str) -> str:"""Downloads the file attached to a task and returns its local path plus a preview.Use it when the question mentions an attached file (excel, csv, python, image, audio, pdf, text).Args:task_id: The task_id of the question."""r = requests.get(f"{DEFAULT_API_URL}/files/{task_id}", timeout=60)if r.status_code != 200:return f"No file available (HTTP {r.status_code})."cd = r.headers.get("content-disposition", "")m = re.search(r'filename="?([^";]+)"?', cd)name = m.group(1) if m else task_idpath = os.path.join(FILES_DIR, f"{task_id}_{name}")with open(path, "wb") as f:f.write(r.content)low = name.lower()preview = ""try:if low.endswith((".txt", ".py", ".csv", ".json", ".md")):preview = r.content.decode("utf-8", errors="replace")[:6000]elif low.endswith((".xlsx", ".xls")):sheets = pd.read_excel(path, sheet_name=None, header=None)preview = "\n\n".join(f"[{k}]\n{v.head(60).to_string()}" for k, v in sheets.items())[:6000]except Exception as e:preview = f"(preview failed: {e})"return f"Saved to {path}\n{preview}"@tooldef describe_image(path: str, question: str) -> str:"""Asks a vision model a question about a local image file.Args:path: Local path of the image (from download_task_file).question: What to ask about the image."""import base64ext = os.path.splitext(path)[1].lstrip(".").lower() or "png"b64 = base64.b64encode(open(path, "rb").read()).decode()out = _gemini_client().chat.completions.create(model=MODEL_ID,messages=[{"role": "user", "content": [{"type": "image_url", "image_url": {"url": f"data:image/{ext};base64,{b64}"}},{"type": "text", "text": question},]}],)return out.choices[0].message.content@tooldef transcribe_audio(path: str) -> str:"""Transcribes a local audio file (mp3/wav) to text.Args:path: Local path of the audio file (from download_task_file)."""import base64fmt = "mp3" if path.lower().endswith("mp3") else "wav"b64 = base64.b64encode(open(path, "rb").read()).decode()out = _gemini_client().chat.completions.create(model=MODEL_ID,messages=[{"role": "user", "content": [{"type": "text", "text": "Transcribe this audio verbatim."},{"type": "input_audio", "input_audio": {"data": b64, "format": fmt}},]}],)return out.choices[0].message.content@tooldef youtube_transcript(url: str) -> str:"""Returns the transcript of a YouTube video.Args:url: The YouTube video URL."""from youtube_transcript_api import YouTubeTranscriptApim = re.search(r"(?:v=|youtu\.be/)([\w-]{11})", url)if not m:return "Could not parse video id."try:api = YouTubeTranscriptApi()parts = api.fetch(m.group(1))return " ".join(p.text for p in parts)[:12000]except Exception as e:return f"Transcript unavailable: {e}"INSTRUCTIONS = """You answer GAIA benchmark questions. Be rigorous: search, open pages, and compute with coderather than guessing. If the question mentions an attached file, call download_task_file(task_id) first(the task_id is given in the prompt). Verify facts with at least two sources when possible.Your final_answer must be ONLY the answer, matching exactly what was asked: a number without unitsor commas unless asked, a string without articles or abbreviations, or a comma-separated list in therequested order. Never write 'FINAL ANSWER' or any explanation inside final_answer."""class GaiaAgent:def __init__(self):model = OpenAIServerModel(model_id=MODEL_ID,api_base=GEMINI_BASE,api_key=os.getenv("GEMINI_API_KEY"),client_kwargs={"max_retries": 8},)self.agent = CodeAgent(tools=[DuckDuckGoSearchTool(),VisitWebpageTool(),download_task_file,describe_image,transcribe_audio,youtube_transcript,],model=model,additional_authorized_imports=["pandas", "numpy", "requests", "bs4", "re", "json", "datetime", "math","statistics", "openpyxl", "collections", "itertools", "unicodedata",],max_steps=10,instructions=INSTRUCTIONS,)def __call__(self, question: str, task_id: str = "") -> str:prompt = f"task_id: {task_id}\n\nQuestion: {question}"ans = str(self.agent.run(prompt)).strip()ans = re.sub(r"(?i)^final answer:\s*", "", ans).strip()return ansdef run_and_submit_all(profile: gr.OAuthProfile | None):4 unmodified linesif not os.getenv("GEMINI_API_KEY"):return "GEMINI_API_KEY secret is missing in the Space settings.", Nonequestions_url = f"{DEFAULT_API_URL}/questions"submit_url = f"{DEFAULT_API_URL}/submit"try:agent = GaiaAgent()except Exception as e:1 unmodified lineagent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"try:response = requests.get(questions_url, timeout=15)response.raise_for_status()questions_data = response.json()if not questions_data:return "Fetched questions list is empty.", Noneexcept Exception as e:return f"Error fetching questions: {e}", Noneresults_log, answers_payload = [], []for item in questions_data:task_id = item.get("task_id")question_text = item.get("question")if not task_id or question_text is None:continuetry:ans = agent(question_text, task_id)except Exception as e:ans = f"AGENT ERROR: {e}"answers_payload.append({"task_id": task_id, "submitted_answer": ans})results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": ans})if not answers_payload:return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}try:response = requests.post(submit_url, json=submission_data, timeout=60)response.raise_for_status()r = response.json()status = (10 unmodified lineswith gr.Blocks() as demo:gr.Markdown("# GAIA Agent Evaluation Runner")gr.Markdown("1. Add GEMINI_API_KEY as a Space secret.\n2. Log in below.\n3. Click run: the agent answers all questions and submits.")gr.LoginButton()run_button = gr.Button("Run Evaluation & Submit All Answers")123456789101112136 unmodified lines20212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632644 unmodified lines2692702712722732741 unmodified line27627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830910 unmodified lines320321322323324325326327328import osimport reimport jsonimport timeimport base64import threadingimport gradio as grimport requestsimport pandas as pdfrom smolagents import CodeAgent, OpenAIServerModel, VisitWebpageTool, tooltry: # ZeroGPU Spaces require at least one @spaces.GPU function to startimport spaces6 unmodified linesDEFAULT_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 RPMFILES_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 sclass 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:return super().generate(*args, **kwargs)except Exception as e:if not _is_rate_limit(e) or attempt == 7:raisetime.sleep(20 * (attempt + 1))def _gemini_native(parts: list, tools: list | None = None) -> str:"""Calls Gemini's native generateContent API (needed for audio, YouTube and search grounding)."""body = {"contents": [{"role": "user", "parts": parts}]}if tools:body["tools"] = toolsurl = f"{GEMINI_NATIVE}/{MODEL_ID}:generateContent"for attempt in range(8):_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:time.sleep(20 * (attempt + 1))continuer.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)."# ---------------------------------------------------------------- attachmentsdef 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 currentlyreturns 404, so the same attachment is fetched from the gated GAIA dataset (attachment only)."""if not file_name:return Nonepath = os.path.join(FILES_DIR, file_name)if os.path.exists(path):return pathtry: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 pathexcept Exception:passtry:from huggingface_hub import hf_hub_downloadreturn 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 Nonedef 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@tooldef web_search(query: str) -> str:"""Searches the web with Google and returns a summary with source URLs.Use specific queries. Open the returned URLs with visit_webpage to verify details.Args:query: The search query."""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": {}}],)if text and "rate limited" not in text:return text[:6000]except Exception as e:print(f"grounded search failed: {e}")try:from duckduckgo_search import DDGSres = DDGS().text(query, max_results=6)return "\n\n".join(f"{r['title']}\n{r['href']}\n{r['body']}" for r in res) or "No results."except Exception as e:return f"Search failed: {e}"@tooldef wikipedia_page(title: str) -> str:"""Returns the wikitext of an English Wikipedia page (tables and lists included). Good fordiscographies, rosters and statistics. Use the exact article title, e.g. 'Mercedes Sosa'.Args:title: The Wikipedia article title."""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:s = requests.get("https://en.wikipedia.org/w/api.php",params={"action": "opensearch", "search": title, "limit": 5, "format": "json"},headers={"User-Agent": "gaia-agent-course/1.0"},timeout=60,).json()return f"Page not found. Close titles: {s[1] if len(s) > 1 else []}"return data["parse"]["wikitext"]["*"][:20000]@tooldef analyze_file(path: str, question: str) -> str:"""Asks a multimodal model about a local image, audio or PDF file (e.g. describe a chessboard 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}])@tooldef 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) andcheck 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 requestedorder 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,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()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):4 unmodified linesif not os.getenv("GEMINI_API_KEY"):return "GEMINI_API_KEY secret is missing in the Space settings.", Nonetry:agent = GaiaAgent()except Exception as e:1 unmodified lineagent_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}", Nonecache = _load_cache() # answers from an interrupted earlier run in this session are reusedresults_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:continueif 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] = ansjson.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 = (10 unmodified lineswith 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")
app.py+210-117