Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files6 unmodified lines7891011121314151617181914 unmodified lines343536373839403 unmodified lines444546474849505152535455565758596061626320 unmodified lines8485868788899022 unmodified lines1131141151161171181191201211225 unmodified lines12812913013113213313413513613713813914014114 unmodified lines15615715815916016116216316421 unmodified lines18618718818919019119243 unmodified lines23623723823924024124224324424524624715 unmodified lines2632642652662672682694 unmodified lines2742752762772782792806 unmodified lines28728828929029129229345 unmodified lines3393403413423433443456 unmodified lines35235335435535635735838 unmodified lines3973983994004014024034044054064076 unmodified linesimport requestsimport pandas as pdimport gradio as grfrom smolagents import (ToolCallingAgent,OpenAIModel,DuckDuckGoSearchTool,VisitWebpageTool,PythonInterpreterTool,)# 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 minuteFALLBACK_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")class AllModelsExhausted(Exception):pass# =========================================================# AGENT# =========================================================20 unmodified linesf"None of {MODEL_CANDIDATES} are available. Got: {sorted(available)}")self.exhausted = set() # models whose daily quota is used upself.model_index = 0self.agent = self._build_agent(self.models[0])print("GROQ AGENT INITIALIZED SUCCESSFULLY")22 unmodified linesvisit = 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 linespython_tool = PythonInterpreterTool()return ToolCallingAgent(tools=[search, visit, python_tool],model=model,max_steps=6,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.- If a file path is given above, read it with the python tool (pandas for Excel/CSV).- Use the python tool for any calculation.- 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 linesdef 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 linesf"{type(e).__name__}: {str(e)[:250]}")if kind == "daily_limit":agent.mark_exhausted_and_switch() # may raise AllModelsExhaustedelif 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 anotherraise last_error15 unmodified linesprint(f"Logged in as: {username}")# 1. Initialize agenttry:agent = BasicAgent()except Exception as error:4 unmodified linespd.DataFrame(),)# 2. Fetch questionstry:response = requests.get(questions_url, timeout=REQUEST_TIMEOUT)response.raise_for_status()6 unmodified linesprint(f"Fetched {len(questions)} questions.")# 3. Solve questionsanswers_payload = []results_log = []failed = 045 unmodified linesresults_df = pd.DataFrame(results_log)# 4. If every model hit its daily limit, do not submit an incomplete runif stopped_early:return ("STOPPED: all Groq models reached their daily token limit.\n\n"6 unmodified linesif not answers_payload:return "No answers were generated. Nothing submitted.", results_df# 5. Submitsubmission_data = {"username": username,"agent_code": agent_code,38 unmodified lines"""# GAIA Final Assignment — Research AgentPowered by Groq (automatic model switching) and web search.**Before running:**- Log in with your Hugging Face account.- Make sure `GROQ_API_KEY` is set in Space Secrets.- The run can take 20–40 minutes. Keep this tab open.""")6 unmodified lines789101112131415161718192014 unmodified lines3536373839403 unmodified lines444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619720 unmodified lines21821922022122222322422 unmodified lines2472482492502512525 unmodified lines25825926026126226326426526626726826927014 unmodified lines28528628728828929029129229329421 unmodified lines31631731831932032143 unmodified lines36536636736836937037137237337437537615 unmodified lines3923933943953963974 unmodified lines4024034044054064076 unmodified lines41441541641741841945 unmodified lines4654664674684694706 unmodified lines47747847948048148238 unmodified lines5215225235245255265275285295305315326 unmodified linesimport requestsimport pandas as pdimport gradio as grfrom bs4 import BeautifulSoupfrom smolagents import (ToolCallingAgent,OpenAIModel,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"MODEL_CANDIDATES = ["openai/gpt-oss-120b","qwen/qwen3.8-27b",3 unmodified linesREQUEST_TIMEOUT = 60SLEEP_BETWEEN_QUESTIONS = 5MAX_ATTEMPTS = 6RATE_LIMIT_WAIT = 65FALLBACK_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# =========================================================@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" rowsfor 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 + moreexcept 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 backendstry:try:from ddgs import DDGSexcept ImportError:from duckduckgo_search import DDGSexcept 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 linesf"None of {MODEL_CANDIDATES} are available. Got: {sorted(available)}")self.exhausted = set()self.model_index = 0self.agent = self._build_agent(self.models[0])print("GROQ AGENT INITIALIZED SUCCESSFULLY")22 unmodified linesvisit = VisitWebpageTool(max_output_length=4000)except TypeError:visit = VisitWebpageTool()try:python_tool = PythonInterpreterTool(authorized_imports=[5 unmodified linespython_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:14 unmodified lines{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.21 unmodified linesdef get_file_context(task_id: str, file_name: str) -> str:if not file_name:return ""try:43 unmodified linesf"{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_error15 unmodified linesprint(f"Logged in as: {username}")try:agent = BasicAgent()except Exception as error:4 unmodified linespd.DataFrame(),)try:response = requests.get(questions_url, timeout=REQUEST_TIMEOUT)response.raise_for_status()6 unmodified linesprint(f"Fetched {len(questions)} questions.")answers_payload = []results_log = []failed = 045 unmodified linesresults_df = pd.DataFrame(results_log)if stopped_early:return ("STOPPED: all Groq models reached their daily token limit.\n\n"6 unmodified linesif not answers_payload:return "No answers were generated. Nothing submitted.", results_dfsubmission_data = {"username": username,"agent_code": agent_code,38 unmodified lines"""# GAIA Final Assignment — Research AgentPowered 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