Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files7 unmodified lines89101112131413 unmodified lines28293031323334353637383940414243444546476 unmodified lines545556575859609 unmodified lines707172737475767778798081828384854 unmodified lines909192939495962 unmodified lines991001011021031041051061071081091101111121131141151161171181191203 unmodified lines1241251261271281291301311321331341358 unmodified lines14414514614714814922 unmodified lines17217317417517617717817918018118218318418518618718818919019119219319419519619719819920039 unmodified lines2402412422432442452462472482499 unmodified lines2592602612622632642652662672682692702712722732748 unmodified lines28328428528628728828929029129212 unmodified lines30530630730830931031123 unmodified lines3353363373383393403417 unmodified linesimport pandas as pdimport gradio as grfrom smolagents import CodeAgent, OpenAIModel, DuckDuckGoSearchTool, VisitWebpageTool# Harmless on CPU hardware; avoids "No @spaces.GPU function detected" on ZeroGPU.try:13 unmodified linesGROQ_API_URL = "https://api.groq.com/openai/v1"GAIA_API_URL = "https://agents-course-unit4-scoring.hf.space"# Tried in order. If one hits its Groq limit, the app switches to the next one.MODEL_CANDIDATES = ["llama-3.3-70b-versatile", # most reliable at writing agent code"openai/gpt-oss-20b","llama-3.1-8b-instant",]REQUEST_TIMEOUT = 60SLEEP_BETWEEN_QUESTIONS = 10MAX_RETRIES = 4RATE_LIMIT_WAIT = 65 # Groq limits reset every minuteFALLBACK_ANSWER = "unknown"FILES_DIR = "/tmp/gaia_files"# =========================================================# AGENT6 unmodified linesif not self.api_key:raise RuntimeError("GROQ_API_KEY is missing. Add it in Space Secrets.")# Keep only the candidate models that really exist on this Groq accountr = requests.get(f"{GROQ_API_URL}/models",headers={"Authorization": f"Bearer {self.api_key}"},9 unmodified linesf"None of {MODEL_CANDIDATES} are available. Got: {sorted(available)}")self.model_index = 0self.agent = self._build_agent(self.models[self.model_index])print("GROQ AGENT INITIALIZED SUCCESSFULLY")def _build_agent(self, model_id: str) -> CodeAgent:print(f"Using model: {model_id}")extra = {}if "gpt-oss" in model_id:extra["reasoning_effort"] = "low" # fewer hidden tokens, fewer empty repliesmodel = OpenAIModel(model_id=model_id,4 unmodified lines**extra,)# Short tool outputs = fewer tokens per minutetry:visit = VisitWebpageTool(max_output_length=4000)except TypeError:2 unmodified linessearch = DuckDuckGoSearchTool(max_results=5)except TypeError:search = DuckDuckGoSearchTool()return CodeAgent(tools=[search, visit],model=model,max_steps=6,verbosity_level=1,additional_authorized_imports=["requests", "bs4", "json", "re", "math", "statistics","datetime", "collections", "urllib", "csv", "xml", "pandas",],)def switch_model(self):"""Move to the next Groq model (wraps around)."""self.model_index = (self.model_index + 1) % len(self.models)self.agent = self._build_agent(self.models[self.model_index])def __call__(self, question: str, file_context: str = "") -> str:prompt = f"""3 unmodified lines{question}{file_context}RULES:- Search the web 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 Python (pandas for Excel/CSV).- Use Python for any calculation.- Respect exact wording, spelling, units, dates and the requested format.- Never invent facts.- Call final_answer with ONLY the answer: no explanation, no markdown, no units unless asked."""result = self.agent.run(prompt)answer = str(result).strip()8 unmodified lines# HELPERS# =========================================================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:22 unmodified linesreturn ""def is_rate_limit(error: Exception) -> bool:text = f"{type(error).__name__} {error}".lower()return any(k in text for k in ("429", "413", "rate", "tokens per", "quota", "limit"))def solve_with_retries(agent: BasicAgent, question: str, file_context: str) -> str:last_error = Nonefor attempt in range(1, MAX_RETRIES + 1):try:return agent(question, file_context)except Exception as e:last_error = eprint(f"Attempt {attempt}/{MAX_RETRIES} failed: {type(e).__name__}: {str(e)[:300]}")if is_rate_limit(e):print(f"Rate limit. Waiting {RATE_LIMIT_WAIT}s...")time.sleep(RATE_LIMIT_WAIT)if attempt >= 2:agent.switch_model() # try a model with a fresh quotaelse:time.sleep(5)if attempt >= 2:agent.switch_model() # maybe this model formats badlyraise last_error39 unmodified linesprint(f"Fetched {len(questions)} questions.")# 3. Solve all questions (a failure never stops the run)answers_payload = []results_log = []failed = 0for index, item in enumerate(questions):task_id = item.get("task_id")9 unmodified linesdesc=f"Solving question {index + 1}/{len(questions)}",)file_context = get_file_context(task_id, file_name)try:answer = solve_with_retries(agent, question, file_context)status = "Answered"except Exception as error:traceback.print_exc()answer = FALLBACK_ANSWERstatus = f"FAILED: {type(error).__name__}: {str(error)[:200]}"failed += 1answers_payload.append({"task_id": task_id, "submitted_answer": answer})results_log.append({8 unmodified linesresults_df = pd.DataFrame(results_log)if not answers_payload:return "No answers were generated. Nothing submitted.", results_df# 4. Submitsubmission_data = {"username": username,"agent_code": agent_code,12 unmodified linesf"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"Questions that failed (fallback answer): {failed}\n"f"Message: {result.get('message', 'Evaluation completed.')}")print(message)23 unmodified lines**Before running:**- Log in with your Hugging Face account.- Make sure `GROQ_API_KEY` is set in Space Secrets.- The run can take 30–60 minutes because of Groq rate limits. Keep this tab open.""")7 unmodified lines89101112131415161718192013 unmodified lines34353637383940414243444546474849505152535455565758596061626 unmodified lines6970717273749 unmodified lines848586878889909192939495969798991001011021031044 unmodified lines1091101111121131142 unmodified lines1171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511523 unmodified lines1561571581591601611621631641651661678 unmodified lines17617717817918018118218318418518618718818919022 unmodified lines21321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624739 unmodified lines2872882892902912922932942952962972989 unmodified lines3083093103113123133143153163173183193203213223233243253263273283293308 unmodified lines33934034134234334434534634734834935035135235335435535635735812 unmodified lines37137237337437537637737823 unmodified lines4024034044054064074087 unmodified linesimport 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.try:13 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","openai/gpt-oss-20b",]REQUEST_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# =========================================================# AGENT6 unmodified linesif 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}"},9 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")@propertydef 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,4 unmodified lines**extra,)try:visit = VisitWebpageTool(max_output_length=4000)except TypeError:2 unmodified linessearch = DuckDuckGoSearchTool(max_results=5)except TypeError:search = DuckDuckGoSearchTool()try:python_tool = PythonInterpreterTool(authorized_imports=["math", "statistics", "datetime", "collections", "re","json", "csv", "itertools", "pandas", "numpy",])except TypeError:python_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:self.agent = self._build_agent(self.current_model)returnraise 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"""3 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."""result = self.agent.run(prompt)answer = str(result).strip()8 unmodified lines# HELPERS# =========================================================def should_skip(question: str, file_name: str) -> bool:q = question.lower()if any(p in q for p in UNSOLVABLE_PATTERNS):return Trueif file_name and file_name.lower().endswith(UNSOLVABLE_EXTENSIONS):return Truereturn Falsedef 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:22 unmodified linesreturn ""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 = Nonefor attempt in range(1, MAX_ATTEMPTS + 1):try:return agent(question, file_context)except AllModelsExhausted:raiseexcept Exception as e:last_error = ekind = 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() # 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_error39 unmodified linesprint(f"Fetched {len(questions)} questions.")# 3. Solve questionsanswers_payload = []results_log = []failed = 0skipped = 0stopped_early = Falsefor index, item in enumerate(questions):task_id = item.get("task_id")9 unmodified linesdesc=f"Solving question {index + 1}/{len(questions)}",)if should_skip(question, file_name):answer = FALLBACK_ANSWERstatus = "Skipped (needs video/audio/image)"skipped += 1else: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 = Truebreakexcept Exception as error:traceback.print_exc()answer = FALLBACK_ANSWERstatus = f"FAILED: {type(error).__name__}: {str(error)[:200]}"failed += 1answers_payload.append({"task_id": task_id, "submitted_answer": answer})results_log.append({8 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"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# 5. Submitsubmission_data = {"username": username,"agent_code": agent_code,12 unmodified linesf"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)23 unmodified lines**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.""")
app.py+117-50