import os import re import time import traceback from typing import Optional import requests import pandas as pd import gradio as gr from bs4 import BeautifulSoup from smolagents import ( ToolCallingAgent, OpenAIModel, VisitWebpageTool, PythonInterpreterTool, tool, ) # Harmless on CPU hardware; avoids "No @spaces.GPU function detected" on ZeroGPU. try: import spaces @spaces.GPU def _gpu_placeholder(): return None except Exception: pass # ========================================================= # CONFIGURATION (GROQ ONLY) # ========================================================= GROQ_API_URL = "https://api.groq.com/openai/v1" GAIA_API_URL = "https://agents-course-unit4-scoring.hf.space" MODEL_CANDIDATES = [ "openai/gpt-oss-120b", "qwen/qwen3.8-27b", "openai/gpt-oss-20b", ] REQUEST_TIMEOUT = 60 SLEEP_BETWEEN_QUESTIONS = 5 MAX_ATTEMPTS = 6 RATE_LIMIT_WAIT = 65 FALLBACK_ANSWER = "unknown" FILES_DIR = "/tmp/gaia_files" UNSOLVABLE_EXTENSIONS = (".mp3", ".wav", ".png", ".jpg", ".jpeg", ".gif", ".mp4") UNSOLVABLE_PATTERNS = ("youtube.com", "youtu.be") HTTP_HEADERS = { "User-Agent": "GAIA-Agent-Course/1.0 (educational project; contact: huggingface.co)" } class AllModelsExhausted(Exception): pass # ========================================================= # TOOLS # ========================================================= @tool def wikipedia_search(query: str) -> str: """Search English Wikipedia and return the best matching page titles with short snippets. Args: query: The search terms, for example "Mercedes Sosa discography". """ try: r = requests.get( "https://en.wikipedia.org/w/api.php", params={ "action": "query", "list": "search", "srsearch": query, "format": "json", "srlimit": 6, }, headers=HTTP_HEADERS, timeout=30, ) r.raise_for_status() hits = r.json().get("query", {}).get("search", []) if not hits: return "No Wikipedia results. Try different search terms." lines = [] for h in hits: snippet = re.sub(r"<[^>]+>", "", h.get("snippet", "")) lines.append(f"- {h['title']}: {snippet}") return "\n".join(lines) except Exception as e: return f"Wikipedia search error: {e}" @tool def wikipedia_page(title: str, start: int = 0) -> str: """Read an English Wikipedia page as plain text, including tables (rows shown with | separators). Returns up to 7000 characters. If the page is longer, call again with a larger start value. Args: title: The exact Wikipedia page title, for example "Mercedes Sosa". start: Character offset to start reading from. Use 0 first. """ try: r = requests.get( "https://en.wikipedia.org/w/index.php", params={"title": title, "action": "render"}, headers=HTTP_HEADERS, timeout=30, ) r.raise_for_status() soup = BeautifulSoup(r.text, "html.parser") for el in soup.select("sup, style, script, .reference, .mw-editsection, .navbox, .hatnote, .noprint"): el.decompose() # Turn tables into "cell | cell | cell" rows for table in soup.find_all("table"): rows = [] for tr in table.find_all("tr"): cells = [c.get_text(" ", strip=True) for c in tr.find_all(["th", "td"])] if cells: rows.append(" | ".join(cells)) table.replace_with(soup.new_string("\n" + "\n".join(rows) + "\n")) text = soup.get_text("\n") text = re.sub(r"\n\s*\n+", "\n", text).strip() if not text: return "Page is empty or not found. Use wikipedia_search to find the exact title." start = max(int(start or 0), 0) chunk = text[start:start + 7000] more = "" if start + 7000 >= len(text) else f"\n[... more text; call again with start={start + 7000}]" return chunk + more except Exception as e: return f"Wikipedia page error: {e}. Use wikipedia_search to find the exact title." @tool def web_search(query: str) -> str: """Search the web and return titles, links and snippets of the top results. Args: query: The search query. """ # 1. Tavily (optional, set TAVILY_API_KEY in Space Secrets; free tier available) tavily_key = os.environ.get("TAVILY_API_KEY") if tavily_key: try: r = requests.post( "https://api.tavily.com/search", json={"api_key": tavily_key, "query": query, "max_results": 5}, timeout=30, ) r.raise_for_status() results = r.json().get("results", []) if results: return "\n\n".join( f"{x.get('title', '')}\n{x.get('url', '')}\n{x.get('content', '')[:500]}" for x in results ) except Exception as e: print(f"Tavily failed: {e}") # 2. DuckDuckGo with several backends try: try: from ddgs import DDGS except ImportError: from duckduckgo_search import DDGS except ImportError: return "Search library not installed. Use wikipedia_search or visit_webpage instead." for backend in ("auto", "html", "lite"): try: results = DDGS().text(query, max_results=5, backend=backend) if results: return "\n\n".join( f"{x.get('title', '')}\n{x.get('href', '')}\n{x.get('body', '')[:500]}" for x in results ) except Exception as e: print(f"DDG backend {backend} failed: {type(e).__name__}: {str(e)[:100]}") time.sleep(1) return ("Web search returned nothing. Do NOT repeat the same search. " "Use wikipedia_search / wikipedia_page, or visit_webpage on a known URL.") # ========================================================= # AGENT # ========================================================= class BasicAgent: def __init__(self): self.api_key = os.environ.get("GROQ_API_KEY") if not self.api_key: raise RuntimeError("GROQ_API_KEY is missing. Add it in Space Secrets.") r = requests.get( f"{GROQ_API_URL}/models", headers={"Authorization": f"Bearer {self.api_key}"}, timeout=REQUEST_TIMEOUT, ) r.raise_for_status() available = {m["id"] for m in r.json().get("data", [])} print("Groq models available:", sorted(available)) self.models = [m for m in MODEL_CANDIDATES if m in available] if not self.models: raise RuntimeError( f"None of {MODEL_CANDIDATES} are available. Got: {sorted(available)}" ) self.exhausted = set() self.model_index = 0 self.agent = self._build_agent(self.models[0]) print("GROQ AGENT INITIALIZED SUCCESSFULLY") @property def current_model(self) -> str: return self.models[self.model_index] def _build_agent(self, model_id: str) -> ToolCallingAgent: print(f"Using model: {model_id}") extra = {} if "gpt-oss" in model_id: extra["reasoning_effort"] = "low" model = OpenAIModel( model_id=model_id, api_base=GROQ_API_URL, api_key=self.api_key, max_tokens=3000, client_kwargs={"timeout": 120, "max_retries": 1}, **extra, ) try: visit = VisitWebpageTool(max_output_length=4000) except TypeError: visit = VisitWebpageTool() try: python_tool = PythonInterpreterTool( authorized_imports=[ "math", "statistics", "datetime", "collections", "re", "json", "csv", "itertools", "pandas", "numpy", ] ) except TypeError: python_tool = PythonInterpreterTool() return ToolCallingAgent( tools=[wikipedia_search, wikipedia_page, web_search, visit, python_tool], model=model, max_steps=8, verbosity_level=1, ) def switch_model(self): for _ in range(len(self.models)): self.model_index = (self.model_index + 1) % len(self.models) if self.current_model not in self.exhausted: self.agent = self._build_agent(self.current_model) return raise AllModelsExhausted("All Groq models reached their daily token limit.") def mark_exhausted_and_switch(self): self.exhausted.add(self.current_model) print(f"Daily limit reached for {self.current_model}. Exhausted: {self.exhausted}") self.switch_model() def __call__(self, question: str, file_context: str = "") -> str: prompt = f""" You are solving a GAIA benchmark question. Be efficient: use as few steps as possible. QUESTION: {question} {file_context} RULES: - For anything that Wikipedia can answer, use wikipedia_search then wikipedia_page (it also shows tables). Use the exact page title. - Use web_search for other facts. If a search fails, never repeat the same query: change tool or wording. - If a file path is given above, read it with the python tool (pandas for Excel/CSV). - Use the python tool for any calculation, counting, sorting or text manipulation. - Respect exact wording, spelling, units, dates and the requested format. - Never invent facts. - Finish by calling final_answer with ONLY the answer: no explanation, no markdown, no units unless asked. """ result = self.agent.run(prompt) answer = str(result).strip() answer = re.sub(r"^(final answer|answer)\s*:\s*", "", answer, flags=re.IGNORECASE) if not answer: raise RuntimeError("Agent returned an empty answer.") return answer # ========================================================= # HELPERS # ========================================================= def should_skip(question: str, file_name: str) -> bool: q = question.lower() if any(p in q for p in UNSOLVABLE_PATTERNS): return True if file_name and file_name.lower().endswith(UNSOLVABLE_EXTENSIONS): return True return False def get_file_context(task_id: str, file_name: str) -> str: if not file_name: return "" try: os.makedirs(FILES_DIR, exist_ok=True) path = os.path.join(FILES_DIR, f"{task_id}_{file_name}") r = requests.get(f"{GAIA_API_URL}/files/{task_id}", timeout=REQUEST_TIMEOUT) r.raise_for_status() with open(path, "wb") as f: f.write(r.content) ext = os.path.splitext(file_name)[1].lower() if ext in (".txt", ".csv", ".json", ".py", ".md", ".xml", ".html"): text = r.content.decode("utf-8", errors="replace")[:3000] return f"\nATTACHED FILE saved at {path}. Start of content:\n{text}\n" if ext in (".xlsx", ".xls"): df = pd.read_excel(path) return ( f"\nATTACHED FILE saved at {path}. First rows:\n" f"{df.head(15).to_string()}\n" ) return f"\nATTACHED FILE saved at {path} (type {ext}).\n" except Exception as e: print(f"Could not fetch file for {task_id}: {e}") return "" def classify_error(error: Exception) -> str: text = f"{type(error).__name__} {error}".lower() if "tokens per day" in text or "(tpd)" in text: return "daily_limit" if "429" in text or "rate limit" in text or "413" in text or "tokens per minute" in text: return "minute_limit" return "other" def solve_with_retries(agent: BasicAgent, question: str, file_context: str) -> str: last_error = None for attempt in range(1, MAX_ATTEMPTS + 1): try: return agent(question, file_context) except AllModelsExhausted: raise except Exception as e: last_error = e kind = classify_error(e) print(f"Attempt {attempt}/{MAX_ATTEMPTS} failed ({kind}): " f"{type(e).__name__}: {str(e)[:250]}") if kind == "daily_limit": agent.mark_exhausted_and_switch() elif kind == "minute_limit": print(f"Per-minute limit. Waiting {RATE_LIMIT_WAIT}s...") time.sleep(RATE_LIMIT_WAIT) else: agent.switch_model() raise last_error # ========================================================= # GAIA EVALUATION # ========================================================= def run_and_submit_all(profile: Optional[gr.OAuthProfile], progress=gr.Progress()): if profile is None: return "Please log in to Hugging Face first.", pd.DataFrame() username = profile.username space_id = os.getenv("SPACE_ID", "mohamedazelmad/Final_Assignment_Template") agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" questions_url = f"{GAIA_API_URL}/questions" submit_url = f"{GAIA_API_URL}/submit" print(f"Logged in as: {username}") try: agent = BasicAgent() except Exception as error: traceback.print_exc() return ( f"MODEL INITIALIZATION FAILED:\n{type(error).__name__}: {error}\n\n" f"No answers were submitted.", pd.DataFrame(), ) try: response = requests.get(questions_url, timeout=REQUEST_TIMEOUT) response.raise_for_status() questions = response.json() if not isinstance(questions, list) or not questions: raise RuntimeError("GAIA returned an empty or invalid question list.") except Exception as error: traceback.print_exc() return f"QUESTION FETCH FAILED:\n{type(error).__name__}: {error}", pd.DataFrame() print(f"Fetched {len(questions)} questions.") answers_payload = [] results_log = [] failed = 0 skipped = 0 stopped_early = False for index, item in enumerate(questions): task_id = item.get("task_id") question = item.get("question") file_name = item.get("file_name", "") if not task_id or not question: continue print(f"\nSolving question {index + 1}/{len(questions)} | {task_id}") progress( (index + 1) / len(questions), desc=f"Solving question {index + 1}/{len(questions)}", ) if should_skip(question, file_name): answer = FALLBACK_ANSWER status = "Skipped (needs video/audio/image)" skipped += 1 else: file_context = get_file_context(task_id, file_name) try: answer = solve_with_retries(agent, question, file_context) status = f"Answered ({agent.current_model})" except AllModelsExhausted: stopped_early = True break except Exception as error: traceback.print_exc() answer = FALLBACK_ANSWER status = f"FAILED: {type(error).__name__}: {str(error)[:200]}" failed += 1 answers_payload.append({"task_id": task_id, "submitted_answer": answer}) results_log.append({ "Task ID": task_id, "Question": question, "Submitted Answer": answer, "Status": status, }) print(f"Answer: {answer[:250]}") time.sleep(SLEEP_BETWEEN_QUESTIONS) results_df = pd.DataFrame(results_log) if stopped_early: return ( "STOPPED: all Groq models reached their daily token limit.\n\n" f"Answered so far: {len(answers_payload)}/{len(questions)}\n" "Nothing was submitted. Wait for the quota to reset (check " "console.groq.com) and run again.", results_df, ) if not answers_payload: return "No answers were generated. Nothing submitted.", results_df submission_data = { "username": username, "agent_code": agent_code, "answers": answers_payload, } try: progress(1.0, desc="Submitting answers to GAIA...") response = requests.post(submit_url, json=submission_data, timeout=120) response.raise_for_status() result = response.json() message = ( "SUBMISSION SUCCESSFUL!\n\n" f"Username: {result.get('username', username)}\n" f"Score: {result.get('score', 'N/A')}%\n" f"Correct answers: {result.get('correct_count', 'N/A')}/" f"{result.get('total_attempted', len(answers_payload))}\n" f"Skipped (video/audio/image): {skipped}\n" f"Failed (fallback answer): {failed}\n" f"Message: {result.get('message', 'Evaluation completed.')}" ) print(message) return message, results_df except Exception as error: traceback.print_exc() return ( f"SUBMISSION FAILED:\n{type(error).__name__}: {error}\n\n" "The answers were generated, but submission was not confirmed.", results_df, ) # ========================================================= # GRADIO INTERFACE # ========================================================= with gr.Blocks(title="GAIA Agent Evaluation") as demo: gr.Markdown( """ # GAIA Final Assignment — Research Agent Powered by Groq (automatic model switching), Wikipedia and web search. **Before running:** - Log in with your Hugging Face account. - Make sure `GROQ_API_KEY` is set in Space Secrets. - Optional: add `TAVILY_API_KEY` for more reliable web search. - The run can take 20–40 minutes. Keep this tab open. """ ) gr.LoginButton() run_button = gr.Button("Run Evaluation & Submit All Answers", variant="primary") status_output = gr.Textbox(label="Evaluation Status", lines=8, interactive=False) results_table = gr.DataFrame(label="GAIA Questions and Answers", wrap=True) run_button.click( fn=run_and_submit_all, outputs=[status_output, results_table], concurrency_limit=1, ) if __name__ == "__main__": print("=" * 50) print("GAIA RESEARCH AGENT STARTING") print("=" * 50) print(f"Space ID: {os.getenv('SPACE_ID', 'Unknown')}") demo.queue().launch( server_name="0.0.0.0", server_port=7860, ssr_mode=False, )