Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files1173 unmodified lines1174117511761177117711781179118015 unmodified lines1196119711981199119912001201120212032 unmodified lines120612071208120812091210121112121213343 unmodified lines155715581559155815601561156215621563156415651566144 unmodified lines1711171217131713171417151716171717181719171417151716172117221717171817241725172617271719172017211722172317241725172617271729173017281729173217331734173517361730173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317311732173317341735173617371738173917401741174217431744174517461747174817491785178617871788175017901791179217511752175317941795179617971798179918001801180218031804180518061807180818091810181118121754175517561757175817591760176117621814181518161817181818191820182118221823182418251826182718281829183017631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918331834182018361837183818391840184118421843184418451821182218231824182518261827182818291830183118471832183318341835116 unmodified lines19521953195419551956195719711972197319581959196019611962196319641965196619671968196985 unmodified lines205520562057207120582073205920602061206220772063206420652066206720682069207020712072207320742075208120762077207820791173 unmodified lines name, ), ) self.gemini_flash_models = discovered_flash or sorted(available_api_models)[:4] self.gemini_flash_models = (discovered_flash or sorted(available_api_models))[:3] candidate_models.extend(self.gemini_flash_models) else: self.gemini_flash_models = [15 unmodified lines for item in groq_resp.json().get("data", []): g_id = str(item.get("id", "")).strip() if g_id and not any( bad in g_id.lower() for bad in ("whisper", "tts", "guard", "safeguard", "embed") bad in g_id.lower() for bad in ("whisper", "tts", "orpheus", "guard", "safeguard", "embed", "compound") ): live_groq.append(f"groq/{g_id}") except Exception as groq_exc:2 unmodified lines if live_groq: live_groq.sort( key=lambda name: ( 0 if "70b" in name.lower() or "120b" in name.lower() else 1, 0 if ("llama-3.3-70b" in name.lower() or "gpt-oss-120b" in name.lower()) else 1, 0 if ("70b" in name.lower() or "32b" in name.lower() or "120b" in name.lower()) else 1, name, ) )343 unmodified lines "timeout": 45, } else: is_openrouter = model_name.startswith("openrouter/") kwargs = { "model_id": model_name, "api_key": api_key, "max_tokens": 4096 if is_openrouter else 8192, "max_tokens": 4096, "num_retries": 0, "timeout": 45, }144 unmodified lines def __call__(self, question: str, task_id: str = "") -> str: import time
prompt = question.strip() self._prefer_2022_wiki = "2022" in prompt.lower() if task_id: prompt += ( f"\n\nTask ID: {task_id}. If the question references an attached file " f"or image, use download_task_file(task_id='{task_id}') to inspect it." ) if not hasattr(self, "_call_lock"): import threading
blocked_models = set() blocked_providers = set() self._call_lock = threading.Lock()
blocked_models = getattr(self, "_blocked_models", None) if blocked_models is None: blocked_models = set() self._blocked_models = blocked_models with self._call_lock: prompt = question.strip() self._prefer_2022_wiki = "2022" in prompt.lower() if task_id: prompt += ( f"\n\nTask ID: {task_id}. If the question references an attached file " f"or image, use download_task_file(task_id='{task_id}') to inspect it." )
blocked_providers = getattr(self, "_blocked_providers", None) if blocked_providers is None: blocked_models = set() blocked_providers = set() self._blocked_providers = blocked_providers
models_to_try = list(getattr(self, "working_models", []) or [self.model_id]) if self.model_id and self.model_id not in models_to_try: models_to_try.append(self.model_id)
while True: rate_limited_models = set() rate_limited_providers = set()
for model_name in models_to_try: if not hasattr(self, "_build_model") or not hasattr(self, "agent"): return "AGENT ERROR: Agent not initialized." provider = model_name.split("/", 1)[0].lower() if "/" in model_name else "gemini" transient_retries = 0 while True: if ( model_name in blocked_models or model_name in rate_limited_models or provider in blocked_providers ): break if not self._get_api_key(model_name): blocked_providers.add(provider) break try: self.model_id = model_name self.agent.model = self._build_model(model_name) result = self.agent.run(prompt) cleaned = self._clean_exact_match_answer("" if result is None else str(result).strip()) if cleaned and not cleaned.startswith("AGENT ERROR:"): return cleaned blocked_models.add(model_name) break except Exception as exc: err_text = str(exc) err_lower = err_text.lower() print(f"[AGENT ERROR] task_id={task_id} model={model_name}: {err_text}") if any( marker in err_lower for marker in ( "401", "402", "403", "authentication", "missing authentication header", "insufficient permissions", "does not have sufficient permissions", "free-models-per-day", "quota", "resource_exhausted", ) models_to_try = list(getattr(self, "working_models", []) or [self.model_id]) if self.model_id and self.model_id not in models_to_try: models_to_try.append(self.model_id)
while True: rate_limited_models = set() rate_limited_providers = set()
for model_name in models_to_try: if not hasattr(self, "_build_model") or not hasattr(self, "agent"): return "AGENT ERROR: Agent not initialized." provider = model_name.split("/", 1)[0].lower() if "/" in model_name else "gemini" transient_retries = 0 while True: if ( model_name in blocked_models or model_name in rate_limited_models or provider in blocked_providers ): if hasattr(self, "_rotate_api_key") and self._rotate_api_key(provider): continue blocked_providers.add(provider) blocked_models.add(model_name) break if any(marker in err_lower for marker in ("429", "rate limit exceeded")): rate_limited_models.add(model_name) rate_limited_providers.add(provider) if not self._get_api_key(model_name): blocked_providers.add(provider) break if any( marker in err_lower for marker in ( "502", "503", "504", "unavailable", "high demand", "overloaded", "timeout", "timed out", "connection error", ) ): if transient_retries < 1: transient_retries += 1 time.sleep(2) continue rate_limited_models.add(model_name) try: self.model_id = model_name self.agent.model = self._build_model(model_name) result = self.agent.run(prompt) cleaned = self._clean_exact_match_answer("" if result is None else str(result).strip()) if cleaned and not cleaned.startswith("AGENT ERROR:"): return cleaned blocked_models.add(model_name) break if any( marker in err_lower for marker in ( "400", "404", "410", "not a valid model id", "no endpoints found", "provider returned error", "provider list", "not supported", "no longer available", "context length", "empty model response", "unavailable for free", ) ): except Exception as exc: err_text = str(exc) err_lower = err_text.lower() print(f"[AGENT ERROR] task_id={task_id} model={model_name}: {err_text}") if any( marker in err_lower for marker in ( "401", "402", "403", "authentication", "missing authentication header", "insufficient permissions", "does not have sufficient permissions", "free-models-per-day", "quota", "resource_exhausted", ) ): if hasattr(self, "_rotate_api_key") and self._rotate_api_key(provider): continue blocked_providers.add(provider) blocked_models.add(model_name) break if any(marker in err_lower for marker in ("429", "rate limit exceeded")): rate_limited_models.add(model_name) rate_limited_providers.add(provider) break if any( marker in err_lower for marker in ( "502", "503", "504", "unavailable", "high demand", "overloaded", ) ): rate_limited_models.add(model_name) break if any( marker in err_lower for marker in ( "timeout", "timed out", "connection error", ) ): if transient_retries < 1: transient_retries += 1 time.sleep(1) continue rate_limited_models.add(model_name) break blocked_models.add(model_name) break blocked_models.add(model_name) break
rotated_any = False if hasattr(self, "_rotate_api_key"): for prov in rate_limited_providers: if prov not in blocked_providers: pool = self.provider_key_pools.get(prov) or [] if self._provider_key_idx.get(prov, 0) + 1 < len(pool): if self._rotate_api_key(prov): rotated_any = True if not rotated_any: break rotated_any = False if hasattr(self, "_rotate_api_key"): for prov in rate_limited_providers: if prov not in blocked_providers: pool = self.provider_key_pools.get(prov) or [] if self._provider_key_idx.get(prov, 0) + 1 < len(pool): if self._rotate_api_key(prov): rotated_any = True if not rotated_any: break
return "AGENT ERROR: All candidate models failed." return "AGENT ERROR: All candidate models failed."
def _trim_tool_output(text: str, max_chars: int = 4000) -> str:116 unmodified lines if ran_fresh_query: time.sleep(3) ran_fresh_query = True executor = ThreadPoolExecutor(max_workers=1) future = executor.submit(agent, question_text, task_id=task_id) try: with ThreadPoolExecutor(max_workers=1) as executor: future = executor.submit(agent, question_text, task_id=task_id) submitted_answer = future.result(timeout=120) submitted_answer = future.result(timeout=120) except FutureTimeoutError: print(f"Timeout running agent on task {task_id} after 120s.") submitted_answer = "AGENT ERROR: Task timed out after 120s." except Exception as e: print(f"Error running agent on task {task_id}: {e}") submitted_answer = f"AGENT ERROR: {e}" finally: executor.shutdown(wait=False, cancel_futures=True)
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer}) results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})85 unmodified lines
if __name__ == "__main__": print("\n" + "-" * 30 + " App Starting " + "-" * 30) # Check for SPACE_HOST and SPACE_ID at startup for information space_host_startup = os.getenv("SPACE_HOST") space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup space_id_startup = os.getenv("SPACE_ID")
if space_host_startup: print(f"✅ SPACE_HOST found: {space_host_startup}") print(f" Runtime URL should be: https://{space_host_startup}.hf.space") runtime_url = ( space_host_startup if space_host_startup.startswith("http") else ( f"https://{space_host_startup}" if space_host_startup.endswith(".hf.space") else f"https://{space_host_startup}.hf.space" ) ) print(f" Runtime URL should be: {runtime_url}") else: print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
if space_id_startup: # Print repo URLs if SPACE_ID is found if space_id_startup: print(f"✅ SPACE_ID found: {space_id_startup}") print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}") print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")app.py+129-134