Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files1173 unmodified lines117411751176117711781179118015 unmodified lines11961197119811991200120112022 unmodified lines1205120612071208120912101211343 unmodified lines15551556155715581559156015611562156315641565144 unmodified lines171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850116 unmodified lines196719681969197019711972197319741975197619771978197919801981198285 unmodified lines206820692070207120722073207420752076207720782079208020812082208320841173 unmodified linesname,),)self.gemini_flash_models = discovered_flash or sorted(available_api_models)[:4]candidate_models.extend(self.gemini_flash_models)else:self.gemini_flash_models = [15 unmodified linesfor 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")):live_groq.append(f"groq/{g_id}")except Exception as groq_exc:2 unmodified linesif live_groq:live_groq.sort(key=lambda name: (0 if "70b" 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,"num_retries": 0,"timeout": 45,}144 unmodified linesdef __call__(self, question: str, task_id: str = "") -> str:import timeprompt = 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_models = set()blocked_providers = set()blocked_models = getattr(self, "_blocked_models", None)if blocked_models is None:blocked_models = set()self._blocked_models = blocked_modelsblocked_providers = getattr(self, "_blocked_providers", None)if blocked_providers is None:blocked_providers = set()self._blocked_providers = blocked_providersmodels_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 = 0while True:if (model_name in blocked_modelsor model_name in rate_limited_modelsor provider in blocked_providers):breakif not self._get_api_key(model_name):blocked_providers.add(provider)breaktry:self.model_id = model_nameself.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 cleanedblocked_models.add(model_name)breakexcept 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_lowerfor 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):continueblocked_providers.add(provider)blocked_models.add(model_name)breakif any(marker in err_lower for marker in ("429", "rate limit exceeded")):rate_limited_models.add(model_name)rate_limited_providers.add(provider)breakif any(marker in err_lowerfor marker in ("502","503","504","unavailable","high demand","overloaded","timeout","timed out","connection error",)):if transient_retries < 1:transient_retries += 1time.sleep(2)continuerate_limited_models.add(model_name)breakif any(marker in err_lowerfor 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",)):blocked_models.add(model_name)breakblocked_models.add(model_name)breakrotated_any = Falseif 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 = Trueif not rotated_any:breakreturn "AGENT ERROR: All candidate models failed."def _trim_tool_output(text: str, max_chars: int = 4000) -> str:116 unmodified linesif ran_fresh_query:time.sleep(3)ran_fresh_query = Truetry:with ThreadPoolExecutor(max_workers=1) as executor:future = executor.submit(agent, question_text, task_id=task_id)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}"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 linesif __name__ == "__main__":print("\n" + "-" * 30 + " App Starting " + "-" * 30)# Check for SPACE_HOST and SPACE_ID at startup for informationspace_host_startup = os.getenv("SPACE_HOST")space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startupif space_host_startup:print(f"✅ SPACE_HOST found: {space_host_startup}")print(f" Runtime URL should be: https://{space_host_startup}.hf.space")else:print("ℹ️ SPACE_HOST environment variable not found (running locally?).")if space_id_startup: # Print repo URLs if SPACE_ID is foundprint(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")1173 unmodified lines117411751176117711781179118015 unmodified lines119611971198119912001201120212032 unmodified lines12061207120812091210121112121213343 unmodified lines1557155815591560156115621563156415651566144 unmodified lines17111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835116 unmodified lines19521953195419551956195719581959196019611962196319641965196619671968196985 unmodified lines20552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820791173 unmodified linesname,),)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 linesfor 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", "orpheus", "guard", "safeguard", "embed", "compound")):live_groq.append(f"groq/{g_id}")except Exception as groq_exc:2 unmodified linesif live_groq:live_groq.sort(key=lambda name: (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:kwargs = {"model_id": model_name,"api_key": api_key,"max_tokens": 4096,"num_retries": 0,"timeout": 45,}144 unmodified linesdef __call__(self, question: str, task_id: str = "") -> str:import timeif not hasattr(self, "_call_lock"):import threadingself._call_lock = threading.Lock()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_models = set()blocked_providers = set()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 = 0while True:if (model_name in blocked_modelsor model_name in rate_limited_modelsor provider in blocked_providers):breakif not self._get_api_key(model_name):blocked_providers.add(provider)breaktry:self.model_id = model_nameself.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 cleanedblocked_models.add(model_name)breakexcept 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_lowerfor 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):continueblocked_providers.add(provider)blocked_models.add(model_name)breakif any(marker in err_lower for marker in ("429", "rate limit exceeded")):rate_limited_models.add(model_name)rate_limited_providers.add(provider)breakif any(marker in err_lowerfor marker in ("502","503","504","unavailable","high demand","overloaded",)):rate_limited_models.add(model_name)breakif any(marker in err_lowerfor marker in ("timeout","timed out","connection error",)):if transient_retries < 1:transient_retries += 1time.sleep(1)continuerate_limited_models.add(model_name)breakblocked_models.add(model_name)breakrotated_any = Falseif 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 = Trueif not rotated_any:breakreturn "AGENT ERROR: All candidate models failed."def _trim_tool_output(text: str, max_chars: int = 4000) -> str:116 unmodified linesif ran_fresh_query:time.sleep(3)ran_fresh_query = Trueexecutor = ThreadPoolExecutor(max_workers=1)future = executor.submit(agent, question_text, task_id=task_id)try: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 linesif __name__ == "__main__":print("\n" + "-" * 30 + " App Starting " + "-" * 30)space_host_startup = os.getenv("SPACE_HOST")space_id_startup = os.getenv("SPACE_ID")if space_host_startup:print(f"✅ SPACE_HOST found: {space_host_startup}")runtime_url = (space_host_startupif 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(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