Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files1975 unmodified lines197619771978197919801981122 unmodified lines210421052106210721082109211070 unmodified lines21812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221093 unmodified lines230423052306230723082309231023112312231323142315231623172318231911 unmodified lines23312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365231 unmodified lines2597259825992600260126022603260426052606260726082609261026112612261326142615124 unmodified lines27402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227731975 unmodified linesfloat(call_kwargs.get("timeout") or getattr(self, "timeout", None) or 22.0),22.0,)call_kwargs["timeout"] = req_timeoutlitellm.request_timeout = req_timeouthard_timeout = req_timeout + 3.0122 unmodified linesprint(f"[LLM] {self.model_id}: {time.monotonic() - t0:.1f}s", flush=True)@classmethoddef _sanitize_code_tags(cls, text: str) -> str:import astimport json70 unmodified linesreturn Nonedef _guard_unbound_lines(code_str: str) -> str:if not code_str or "lines" not in code_str:return code_strtry:tree = ast.parse(code_str)except SyntaxError:return code_strassigned_before_use = Falsefor node in ast.walk(tree):if isinstance(node, (ast.Assign, ast.AugAssign, ast.AnnAssign)):targets = []if isinstance(node, ast.Assign):targets = node.targetselif isinstance(node, ast.AugAssign):targets = [node.target]elif isinstance(node, ast.AnnAssign) and node.value is not None:targets = [node.target]if any(isinstance(t, ast.Name) and t.id == "lines" for t in targets):assigned_before_use = Truebreakif assigned_before_use:return code_strreturn "lines = []\n" + code_strdef _ensure_observable_output(code_str: str) -> str:clean_code = (code_str or "").strip()93 unmodified linescontinueplain = "\n".join(src_lines).strip()if (plainand "\n" not in plainand len(plain) <= 80and plain.lower() not in {"[code]", "code", "python", "py"}and not plain.endswith((".", "?", ":"))and not re.match(r"^(?:thoughts?|thinking|invalid|error)\b", plain, re.IGNORECASE)):safe_direct = json.dumps(plain.strip("\"'` "), ensure_ascii=False)return f"final_answer({safe_direct})"fa_match = re.findall(r"(?im)^\s*(?:final\s*answer|answer)\s*:\s*(.+)$",plain,11 unmodified lines'the code block calling a tool or final_answer(...).")')tag_matches = re.findall(rf"{re.escape(open_t)}(.*?){re.escape(close_t)}",text,flags=re.DOTALL,)if not tag_matches and open_t != "```py":tag_matches = re.findall(r"```(?:py|python)?\s*\n(.*?)```",text,flags=re.DOTALL | re.IGNORECASE,)if tag_matches:raw_block = tag_matches[-1].strip()converted = _convert_json_tool_calls(raw_block) or _convert_xml_tool_calls(raw_block)inner = converted if converted is not None else raw_blockinner = _guard_unbound_lines(inner)inner = _ensure_observable_output(inner)try:tree = ast.parse(inner)if not tree.body:inner = _extract_valid_python(raw_block)except SyntaxError:inner = _extract_valid_python(raw_block)return f"{open_t}\n{inner}\n{close_t}"extracted = _extract_valid_python(text)return f"{open_t}\n{extracted}\n{close_t}"@classmethoddef _validate_message(cls, msg):import json231 unmodified linesif isinstance(getattr(self, "kwargs", None), dict):self.kwargs["api_key"] = keydefault_cap = 28.0timeout = min(float(getattr(self, "timeout", None) or default_cap), default_cap)task_deadline = getattr(self, "deadline", None)if task_deadline is not None:remaining = task_deadline - time.monotonic()if remaining <= 3.0:raise RuntimeError("Task time budget exhausted")timeout = max(5.0, min(timeout, remaining - 2.0))if isinstance(getattr(self, "kwargs", None), dict):self.kwargs["timeout"] = timeoutkwargs["timeout"] = timeoutlitellm.request_timeout = timeoutif model_name.startswith("gemini/"):if "gemma" not in model_name.lower():124 unmodified linesimport timeprovider = model_name.split("/", 1)[0].lower() if "/" in model_name else "gemini"api_key = self._get_api_key(model_name)if not api_key:return (model_name, "DEAD_KEY", "no api key")t0 = time.monotonic()try:kw = {"model": model_name, "api_key": api_key}if model_name.startswith("huggingface/"):kw = {"model": "openai/" + model_name[len("huggingface/") :],"api_base": "https://router.huggingface.co/v1","api_key": api_key,}litellm.completion(**kw,messages=[{"role": "user", "content": "Reply with the single word OK."}],max_tokens=16,timeout=8,num_retries=0,max_retries=0,)return (model_name, "OK", f"{time.monotonic() - t0:.1f}s")except Exception as exc:status_kind = _classify_preflight_error(exc)if status_kind == "DEAD_KEY":_remove_specific_key(provider, api_key)short = " ".join(f"{type(exc).__name__}: {exc}".split())[:220]return (model_name, status_kind, short)from concurrent.futures import ThreadPoolExecutor, wait as futures_wait1975 unmodified lines197619771978197919801981198219831984198519861987198819891990122 unmodified lines211321142115211621172118211970 unmodified lines219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224193 unmodified lines23352336233723382339234011 unmodified lines235223532354235523562357231 unmodified lines25892590259125922593259425952596259725982599260026012602260326042605124 unmodified lines27302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727781975 unmodified linesfloat(call_kwargs.get("timeout") or getattr(self, "timeout", None) or 22.0),22.0,)task_deadline = getattr(self, "deadline", None)if task_deadline is not None:remaining = task_deadline - time.monotonic()if remaining <= 1.0:raise RuntimeError("Task time budget exhausted")req_timeout = max(1.0, min(req_timeout, remaining - 0.5))hard_timeout = max(1.5, min(req_timeout + 2.0, remaining))else:hard_timeout = req_timeout + 3.0call_kwargs["timeout"] = req_timeoutlitellm.request_timeout = req_timeouthard_timeout = req_timeout + 3.0122 unmodified linesprint(f"[LLM] {self.model_id}: {time.monotonic() - t0:.1f}s", flush=True)@classmethoddef _sanitize_code_tags(cls, text: str) -> str:import astimport json70 unmodified linesreturn Nonedef _guard_unbound_lines(code_str: str) -> str:if not code_str:return code_strtry:tree = ast.parse(code_str)except SyntaxError:return code_strdef _has_load(node: ast.AST) -> bool:return any(isinstance(n, ast.Name) and n.id == "lines" and isinstance(n.ctx, ast.Load)for n in ast.walk(node))def _has_store(node: ast.AST) -> bool:return any(isinstance(n, ast.Name) and n.id == "lines" and isinstance(n.ctx, ast.Store)for n in ast.walk(node))defined = Falseneeds_guard = Falsefor stmt in tree.body:if isinstance(stmt, ast.Assign):if not defined and _has_load(stmt.value):needs_guard = Truebreakif any(_has_store(t) for t in stmt.targets):defined = Trueelif isinstance(stmt, ast.AnnAssign):if not defined and stmt.value is not None and _has_load(stmt.value):needs_guard = Truebreakif stmt.value is not None and _has_store(stmt.target):defined = Trueelif isinstance(stmt, ast.AugAssign):if not defined:needs_guard = Truebreakelse:if not defined and _has_load(stmt):needs_guard = Truebreakif _has_store(stmt):defined = Truereturn ("lines = []\n" + code_str) if needs_guard else code_strdef _ensure_observable_output(code_str: str) -> str:clean_code = (code_str or "").strip()93 unmodified linescontinueplain = "\n".join(src_lines).strip()fa_match = re.findall(r"(?im)^\s*(?:final\s*answer|answer)\s*:\s*(.+)$",plain,11 unmodified lines'the code block calling a tool or final_answer(...).")')@classmethoddef _validate_message(cls, msg):import json231 unmodified linesif isinstance(getattr(self, "kwargs", None), dict):self.kwargs["api_key"] = keydefault_cap = 22.0raw_timeout = kwargs.get("timeout") or getattr(self, "timeout", None) or default_captimeout = min(float(raw_timeout), default_cap)task_deadline = getattr(self, "deadline", None)if task_deadline is not None:remaining = task_deadline - time.monotonic()if remaining <= 2.5:raise RuntimeError("Task time budget exhausted")timeout = max(1.5, min(timeout, remaining - 1.5))kwargs["timeout"] = timeoutif model_name.startswith("gemini/"):if "gemma" not in model_name.lower():124 unmodified linesimport timeprovider = model_name.split("/", 1)[0].lower() if "/" in model_name else "gemini"t0 = time.monotonic()max_key_attempts = max(1, len(self.provider_key_pools.get(provider) or []))tried_keys = set()last_short = "no api key"for _ in range(max_key_attempts):api_key = self._get_api_key(model_name)if not api_key or api_key in tried_keys:return (model_name, "DEAD_KEY", last_short)tried_keys.add(api_key)try:kw = {"model": model_name,"api_key": api_key,"max_tokens": 128,"timeout": 8,"num_retries": 0,"max_retries": 0,}if model_name.startswith("huggingface/"):kw["model"] = "openai/" + model_name[len("huggingface/"):]kw["api_base"] = "https://router.huggingface.co/v1"elif model_name.startswith("gemini/") and "gemma" not in model_name.lower():kw["reasoning_effort"] = "low"elif model_name.startswith("groq/") and "qwen3" in model_name.lower():kw["reasoning_effort"] = "none"kw["reasoning_format"] = "hidden"litellm.completion(**kw,messages=[{"role": "user", "content": "Reply with the single word OK."}],)return (model_name, "OK", f"{time.monotonic() - t0:.1f}s")except Exception as exc:status_kind = _classify_preflight_error(exc)last_short = " ".join(f"{type(exc).__name__}: {exc}".split())[:220]if status_kind == "DEAD_KEY":_remove_specific_key(provider, api_key)continuereturn (model_name, status_kind, last_short)return (model_name, "DEAD_KEY", last_short)from concurrent.futures import ThreadPoolExecutor, wait as futures_wait
app.py+92-87