Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files6 unmodified lines78910111213141415161718192014 unmodified lines353637373839403 unmodified lines444546474748495051525152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619720 unmodified lines2182192208722122222322422 unmodified lines2472482491161171181192502512525 unmodified lines25825926013126126213326326426526626713826826927014 unmodified lines28528628715928828929016129129229329421 unmodified lines31631731818931932032143 unmodified lines36536636723936836937037137224437337437537615 unmodified lines3923933942663953963974 unmodified lines4024034042774054064076 unmodified lines41441541629041741841945 unmodified lines4654664673424684694706 unmodified lines47747847935548048148238 unmodified lines5215225234005245255265275285295305315326 unmodified linesimport requestsimport pandas as pdimport gradio as grfrom bs4 import BeautifulSoup
from smolagents import ( ToolCallingAgent, OpenAIModel, DuckDuckGoSearchTool, VisitWebpageTool, PythonInterpreterTool, tool,)
# Harmless on CPU hardware; avoids "No @spaces.GPU function detected" on ZeroGPU.14 unmodified linesGROQ_API_URL = "https://api.groq.com/openai/v1"GAIA_API_URL = "https://agents-course-unit4-scoring.hf.space"
# Tried in order; each model has its own daily quota on Groq.MODEL_CANDIDATES = [ "openai/gpt-oss-120b", "qwen/qwen3.8-27b",3 unmodified linesREQUEST_TIMEOUT = 60SLEEP_BETWEEN_QUESTIONS = 5MAX_ATTEMPTS = 6RATE_LIMIT_WAIT = 65 # per-minute limits reset after about a minuteRATE_LIMIT_WAIT = 65FALLBACK_ANSWER = "unknown"FILES_DIR = "/tmp/gaia_files"
# Questions that need video/audio/image understanding cannot be solved# with text tools; skipping them saves your daily token quota.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# =========================================================
@tooldef 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}"
@tooldef 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."
@tooldef 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# =========================================================20 unmodified lines f"None of {MODEL_CANDIDATES} are available. Got: {sorted(available)}" )
self.exhausted = set() # models whose daily quota is used up self.exhausted = set() self.model_index = 0 self.agent = self._build_agent(self.models[0]) print("GROQ AGENT INITIALIZED SUCCESSFULLY")22 unmodified lines visit = VisitWebpageTool(max_output_length=4000) except TypeError: visit = VisitWebpageTool() try: search = DuckDuckGoSearchTool(max_results=5) except TypeError: search = DuckDuckGoSearchTool() try: python_tool = PythonInterpreterTool( authorized_imports=[5 unmodified lines python_tool = PythonInterpreterTool()
return ToolCallingAgent( tools=[search, visit, python_tool], tools=[wikipedia_search, wikipedia_page, web_search, visit, python_tool], model=model, max_steps=6, max_steps=8, verbosity_level=1, )
def switch_model(self): """Move to the next model that is not exhausted.""" for _ in range(len(self.models)): self.model_index = (self.model_index + 1) % len(self.models) if self.current_model not in self.exhausted:14 unmodified lines{question}{file_context}RULES:- Use web search only when external facts are needed; open a page only if the snippet is not enough.- 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.- 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.21 unmodified lines
def get_file_context(task_id: str, file_name: str) -> str: """Download the task attachment (if any) and describe it for the agent.""" if not file_name: return "" try:43 unmodified lines f"{type(e).__name__}: {str(e)[:250]}")
if kind == "daily_limit": agent.mark_exhausted_and_switch() # may raise AllModelsExhausted 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() # model/format problem: try another agent.switch_model() raise last_error
15 unmodified lines
print(f"Logged in as: {username}")
# 1. Initialize agent try: agent = BasicAgent() except Exception as error:4 unmodified lines pd.DataFrame(), )
# 2. Fetch questions try: response = requests.get(questions_url, timeout=REQUEST_TIMEOUT) response.raise_for_status()6 unmodified lines
print(f"Fetched {len(questions)} questions.")
# 3. Solve questions answers_payload = [] results_log = [] failed = 045 unmodified lines
results_df = pd.DataFrame(results_log)
# 4. If every model hit its daily limit, do not submit an incomplete run if stopped_early: return ( "STOPPED: all Groq models reached their daily token limit.\n\n"6 unmodified lines if not answers_payload: return "No answers were generated. Nothing submitted.", results_df
# 5. Submit submission_data = { "username": username, "agent_code": agent_code,38 unmodified lines """ # GAIA Final Assignment — Research Agent
Powered by Groq (automatic model switching) and web search. 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. """ )app.py+149-24