Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567896789101112101112136 unmodified lines20212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101112829112311131141151161171181191201211221231241253435126127128129130131132394041133134135136137441381394647484950515253545556140585960616214114214314414514614714814915015115215315415564651561571581596970160161162163164737416516676777879808182838485167168169170171172871731741751761771781791801811821831841859192186187188189190951911921939798991001011021031041051061071081941951961971981992001121132012022032042052062071181191201211221231241251261271282082092101311321331341351362112122132142152162172182192202212222232241412252262272281452292302311481491501511521531541552322332341571581591602352362372382392401651662412422432442452462472482492502512521681692532542552562572582592602612622632644 unmodified lines2692702711801812722732741 unmodified line27627727818927928028119219328228328428528628719920028828929029129229320320420520629429529629729829930030130230321021121230430521530630730830910 unmodified lines320321322323324232325326327328import osimport reimport jsonimport timeimport base64import threadingimport gradio as grimport requestsimport pandas as pdfrom smolagents import ( CodeAgent, OpenAIServerModel, DuckDuckGoSearchTool, VisitWebpageTool, tool,)from smolagents import CodeAgent, OpenAIServerModel, VisitWebpageTool, tool
try: # ZeroGPU Spaces require at least one @spaces.GPU function to start import spaces6 unmodified lines
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 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 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: return super().generate(*args, **kwargs) 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) -> 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(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)) 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)."
# ---------------------------------------------------------------- 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 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 _gemini_client(): from openai import OpenAI
return OpenAI(base_url=GEMINI_BASE, api_key=os.getenv("GEMINI_API_KEY"), max_retries=6)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 ""
FILES_DIR = "/tmp/task_files"os.makedirs(FILES_DIR, exist_ok=True)_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 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).def 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: task_id: The task_id of the question. query: The search query. """ 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_id path = 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] 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 DDGS
res = 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: preview = f"(preview failed: {e})" return f"Saved to {path}\n{preview}" return f"Search failed: {e}"
@tooldef describe_image(path: str, question: str) -> str: """Asks a vision model a question about a local image file.def wikipedia_page(title: str) -> str: """Returns the wikitext of an English Wikipedia page (tables and lists included). Good for discographies, rosters and statistics. Use the exact article title, e.g. 'Mercedes Sosa'.
Args: path: Local path of the image (from download_task_file). question: What to ask about the image. title: The Wikipedia article title. """ import base64
ext = 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}, ]}], 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, ) return out.choices[0].message.content 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 transcribe_audio(path: str) -> str: """Transcribes a local audio file (mp3/wav) to text.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 audio file (from download_task_file). path: Local path of the file. question: What to ask about the file. """ import base64
fmt = "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 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_transcript(url: str) -> str: """Returns the transcript of a YouTube video.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. """ from youtube_transcript_api import YouTubeTranscriptApi
m = 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}" return _gemini_native([{"file_data": {"file_uri": url}}, {"text": question}])
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."""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 = OpenAIServerModel( model = ThrottledGeminiModel( model_id=MODEL_ID, api_base=GEMINI_BASE, api_key=os.getenv("GEMINI_API_KEY"), client_kwargs={"max_retries": 8}, client_kwargs={"max_retries": 2}, ) self.agent = CodeAgent( tools=[ DuckDuckGoSearchTool(), VisitWebpageTool(), download_task_file, describe_image, transcribe_audio, youtube_transcript, ], tools=[web_search, wikipedia_page, VisitWebpageTool(max_output_length=12000), analyze_file, youtube_video], model=model, additional_authorized_imports=[ "pandas", "numpy", "requests", "bs4", "re", "json", "datetime", "math", "statistics", "openpyxl", "collections", "itertools", "unicodedata", ], additional_authorized_imports=["*"], max_steps=10, max_print_outputs_length=6000, instructions=INSTRUCTIONS, )
def __call__(self, question: str, task_id: str = "") -> str: prompt = f"task_id: {task_id}\n\nQuestion: {question}" 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*", "", ans).strip() return ans 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 lines if not os.getenv("GEMINI_API_KEY"): return "GEMINI_API_KEY secret is missing in the Space settings.", None
questions_url = f"{DEFAULT_API_URL}/questions" submit_url = f"{DEFAULT_API_URL}/submit" try: agent = GaiaAgent() except Exception as e:1 unmodified line agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
try: response = requests.get(questions_url, timeout=15) response = requests.get(f"{DEFAULT_API_URL}/questions", timeout=30) response.raise_for_status() questions_data = response.json() if not questions_data: return "Fetched questions list is empty.", None 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 = item.get("task_id") question_text = item.get("question") 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) except Exception as e: ans = f"AGENT ERROR: {e}" 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})
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 = 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" "1. Add GEMINI_API_KEY as a Space secret.\n2. Log in below.\n3. Click run: the agent answers all questions and submits." "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