Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files832 unmodified lines833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914868 unmodified lines17831784178517861787178881 unmodified lines187018711872187318741875187618771878183 unmodified lines2062206320642065206620675 unmodified lines207320742075207620772078125 unmodified lines22042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722284 unmodified lines223322342235223622372238223922402241224222432244224522462247224822492250225122522253225426 unmodified lines22812282228322842285228622871 unmodified line228922902291229222932294229593 unmodified lines238923902391239223932394832 unmodified linesunique_vision = list(dict.fromkeys(vision_candidates))last_err = Nonewhile True:rate_limited_providers = set()for v_model in unique_vision:v_provider = v_model.split("/", 1)[0].lower() if "/" in v_model else "gemini"while True:v_key = self._get_api_key(v_model)if not v_key:breaktry:response = litellm.completion(**_litellm_route_kwargs(v_model, v_key),messages=[{"role": "user","content": [{"type": "text", "text": question},{"type": "image_url","image_url": {"url": f"data:{mime_type};base64,{b64_data}"},},],}],max_tokens=2048,timeout=_tool_timeout(45.0),)out = (response.choices[0].message.content or "").strip()if out:return outbreakexcept Exception as exc:last_err = excerr_low = str(exc).lower()if "task time budget exhausted" in err_low:raiseif any(marker in err_lowfor marker in ("401","402","403","authentication","missing authentication header","insufficient permissions","does not have sufficient permissions",)):if hasattr(self, "_rotate_api_key") and self._rotate_api_key(v_provider, permanent=True):continuebreakif any(marker in err_lowfor marker in ("429","rate limit","free-models-per-day","quota","resource_exhausted",)):rate_limited_providers.add(v_provider)breakbreakrotated_any = Falseif hasattr(self, "_rotate_api_key"):for prov in rate_limited_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:breakraise RuntimeError(str(last_err) if last_err else "No vision model available.")except Exception as e:868 unmodified lines)cleaned = cls._sanitize_code_tags(content_str)if not cleaned.strip():raise RuntimeError("Error in generating model output: empty model response after sanitization"81 unmodified lines"api_key": api_key,"max_tokens": 8192,"temperature": 0.1,"reasoning_effort": "low",**common,}elif model_name.startswith("huggingface/"):raw_hf = model_name[len("huggingface/"):]kwargs = {183 unmodified linesif not text or text.startswith("AGENT ERROR:"):return texttext = re.sub(r"^```(?:[a-zA-Z0-9_-]+)?\s*\n?", "", text)text = re.sub(r"\n?```\s*$", "", text).strip()5 unmodified linesif lines:text = lines[-1]text = re.sub(r"^\*\*(.+?)\*\*$", r"\1", text).strip()if len(text) >= 2 and ((text[0] == '"' and text[-1] == '"') or (text[0] == "'" and text[-1] == "'")):125 unmodified linesprint(f"[AGENT ERROR] task_id={task_id} model={model_name}: {err_text}", flush=True)if "task time budget exhausted" in err_lower:breakif any(marker in err_lowerfor marker in ("401","402","403","authentication","missing authentication header","insufficient permissions","does not have sufficient permissions",)):if hasattr(self, "_rotate_api_key") and self._rotate_api_key(provider, permanent=True):continueblocked_providers.add(provider)blocked_models.add(model_name)breakif any(marker in err_lowerfor marker in (4 unmodified lines"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 (26 unmodified linesrotated_any = Trueif not rotated_any:rem_after_pass = deadline - time.monotonic()if rate_limited_models and backoff_rounds < 2 and rem_after_pass > 15.0:backoff_rounds += 1for prov in rate_limited_providers:if prov not in blocked_providers:1 unmodified lineself._provider_key_idx[prov] = 0if hasattr(self, "_sync_provider_env"):self._sync_provider_env(prov, pool[0] if pool else "")time.sleep(min(3.0 * backoff_rounds, max(0.5, rem_after_pass - 10.0)))continuebreakfinally:93 unmodified linesisinstance(c_ans, str)and c_ans.strip()and not c_ans.strip().startswith("AGENT ERROR:")):clean_cached = c_ans.strip()if isinstance(c_tid, str) and c_tid.strip():832 unmodified lines833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907868 unmodified lines177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180081 unmodified lines1882188318841885188618871888188918901891183 unmodified lines20752076207720782079208020815 unmodified lines2087208820892090209120922093125 unmodified lines2219222022212222222322244 unmodified lines2229223022312232223322342235223622372238223922402241224226 unmodified lines22692270227122722273227422751 unmodified line227722782279228022812282228393 unmodified lines23772378237923802381238223832384832 unmodified linesunique_vision = list(dict.fromkeys(vision_candidates))last_err = Nonerate_limited_providers = set()for v_model in unique_vision:v_provider = v_model.split("/", 1)[0].lower() if "/" in v_model else "gemini"if v_provider in rate_limited_providers:continuewhile True:v_key = self._get_api_key(v_model)if not v_key:breaktry:response = litellm.completion(**_litellm_route_kwargs(v_model, v_key),messages=[{"role": "user","content": [{"type": "text", "text": question},{"type": "image_url","image_url": {"url": f"data:{mime_type};base64,{b64_data}"},},],}],max_tokens=2048,timeout=_tool_timeout(45.0),)out = (response.choices[0].message.content or "").strip()if out:return outbreakexcept Exception as exc:last_err = excerr_low = str(exc).lower()if "task time budget exhausted" in err_low:raiseif any(marker in err_lowfor marker in ("401","402","403","authentication","missing authentication header","insufficient permissions","does not have sufficient permissions",)):if hasattr(self, "_rotate_api_key") and self._rotate_api_key(v_provider, permanent=True):continuebreakif any(marker in err_lowfor marker in ("429","rate limit","free-models-per-day","quota","resource_exhausted",)):if hasattr(self, "_rotate_api_key") and self._rotate_api_key(v_provider):continuerate_limited_providers.add(v_provider)breakbreakraise RuntimeError(str(last_err) if last_err else "No vision model available.")except Exception as e:868 unmodified lines)cleaned = cls._sanitize_code_tags(content_str)if cls.open_tag not in cleaned and cls.close_tag not in cleaned:fa_direct = re.findall(r"(?im)^\s*(?:final\s*answer|answer)\s*:\s*(.+)$",cleaned,)if fa_direct and fa_direct[-1].strip():ans_val = fa_direct[-1].strip()cleaned = (f"{cls.open_tag}\n"f"final_answer({json.dumps(ans_val, ensure_ascii=False)})\n"f"{cls.close_tag}")elif len(cleaned.splitlines()) == 1 and len(cleaned) <= 200:cleaned = (f"{cls.open_tag}\n"f"final_answer({json.dumps(cleaned.strip(), ensure_ascii=False)})\n"f"{cls.close_tag}")if not cleaned.strip():raise RuntimeError("Error in generating model output: empty model response after sanitization"81 unmodified lines"api_key": api_key,"max_tokens": 8192,"temperature": 0.1,**common,}if "2.5" in raw_gemini or "3" in raw_gemini:kwargs["reasoning_effort"] = "low"elif model_name.startswith("huggingface/"):raw_hf = model_name[len("huggingface/"):]kwargs = {183 unmodified linesif not text or text.startswith("AGENT ERROR:"):return texttext = re.sub(r"</?code[^>]*>", "", text, flags=re.IGNORECASE).strip()text = re.sub(r"^```(?:[a-zA-Z0-9_-]+)?\s*\n?", "", text)text = re.sub(r"\n?```\s*$", "", text).strip()5 unmodified linesif lines:text = lines[-1]text = re.sub(r"</?code[^>]*>", "", text, flags=re.IGNORECASE).strip()text = re.sub(r"^\*\*(.+?)\*\*$", r"\1", text).strip()if len(text) >= 2 and ((text[0] == '"' and text[-1] == '"') or (text[0] == "'" and text[-1] == "'")):125 unmodified linesprint(f"[AGENT ERROR] task_id={task_id} model={model_name}: {err_text}", flush=True)if "task time budget exhausted" in err_lower:breakif any(marker in err_lowerfor marker in (4 unmodified lines"rate limit exceeded",)):if hasattr(self, "_rotate_api_key") and self._rotate_api_key(provider):continuefor m in models_to_try:if m.startswith(f"{provider}/"):rate_limited_models.add(m)rate_limited_models.add(model_name)rate_limited_providers.add(provider)breakif any(marker in err_lowerfor marker in (26 unmodified linesrotated_any = Trueif not rotated_any:rem_after_pass = deadline - time.monotonic()if rate_limited_models and backoff_rounds < 1 and rem_after_pass > 20.0:backoff_rounds += 1for prov in rate_limited_providers:if prov not in blocked_providers:1 unmodified lineself._provider_key_idx[prov] = 0if hasattr(self, "_sync_provider_env"):self._sync_provider_env(prov, pool[0] if pool else "")time.sleep(min(10.0, max(2.0, rem_after_pass - 12.0)))continuebreakfinally:93 unmodified linesisinstance(c_ans, str)and c_ans.strip()and not c_ans.strip().startswith("AGENT ERROR:")and "</code>" not in c_ans.lower()and "without access to" not in c_ans.lower()):clean_cached = c_ans.strip()if isinstance(c_tid, str) and c_tid.strip():
app.py+97-107