Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files2103 unmodified lines21042105210621072108210921103 unmodified lines21142115211621172118211981 unmodified lines220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226484 unmodified lines23492350235123522353235423551 unmodified line2357235823592360236123622363236423652366236734 unmodified lines240224032404240524062407240824093 unmodified lines24132414241524162417241824192420486 unmodified lines290729082909291029112912113 unmodified lines3026302730283029303030313032303330344 unmodified lines303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306331 unmodified lines3095309630973098309931003101310231033104310531063107310825 unmodified lines3134313531363137313831393140249 unmodified lines339033913392339333943395339611 unmodified lines3408340934103411341234133414341512 unmodified lines342834293430343134323433343414 unmodified lines34493450345134523453345434553456345734583459346034613462346334643465346634673468346912 unmodified lines34823483348434853486348734883489349034915 unmodified lines349734983499350035013502350335043505350635073508350935 unmodified lines35453546354735483549355035517 unmodified lines35593560356135623563356435653 unmodified lines3569357035713572357335743575249 unmodified lines3825382638273828382938302103 unmodified linesprint(f"[LLM] {self.model_id}: {time.monotonic() - t0:.1f}s", flush=True)@classmethoddef _sanitize_code_tags(cls, text: str) -> str:import astimport json3 unmodified linesclose_t = cls.close_tagtext = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL | re.IGNORECASE).strip()def _convert_xml_tool_calls(raw: str) -> str | None:qwen_calls = re.findall(81 unmodified linesreturn code_strreturn "lines = []\n" + code_strdef _ensure_final_answer_call(code_str: str) -> str:clean_code = (code_str or "").strip()if not clean_code or "final_answer(" in clean_code:return clean_codetry:tree = ast.parse(clean_code)except SyntaxError:return clean_codeif not tree.body:return clean_codeobservation_tools = {"web_search","search_wikipedia","fetch_url_text","download_task_file","read_local_file","inspect_image","inspect_youtube","transcribe_audio","ask_web",}for node in ast.walk(tree):if isinstance(node, ast.Call):func_name = Noneif isinstance(node.func, ast.Name):func_name = node.func.idelif isinstance(node.func, ast.Attribute):func_name = node.func.attrif func_name in observation_tools:return clean_codelast_node = tree.body[-1]if (isinstance(last_node, ast.Expr)and isinstance(last_node.value, ast.Call)and isinstance(last_node.value.func, ast.Name)and last_node.value.func.id == "print"and len(last_node.value.args) == 1):lines_list = clean_code.splitlines()start_idx = max(0, (getattr(last_node, "lineno", len(lines_list)) - 1))prefix = "\n".join(lines_list[:start_idx]).strip()printed_arg_src = ast.get_source_segment(clean_code, last_node.value.args[0])if not printed_arg_src:line_txt = lines_list[start_idx].strip()m_p = re.match(r"^print\((.*)\)$", line_txt)if m_p:printed_arg_src = m_p.group(1).strip()if printed_arg_src:final_snippet = (f"_final_out = {printed_arg_src}\n"f"print(_final_out)\n"f"final_answer(_final_out)")return f"{prefix}\n{final_snippet}".strip() if prefix else final_snippetreturn clean_codedef _ensure_observable_output(code_str: str) -> str:clean_code = (code_str or "").strip()if not clean_code or "final_answer(" in clean_code:84 unmodified linesif (len(tree.body) == 1and isinstance(tree.body[0], ast.Expr)and isinstance(tree.body[0].value, (ast.Name, ast.Constant))):continuereturn _ensure_observable_output(_guard_unbound_lines(candidate))1 unmodified linecontinueplain = "\n".join(src_lines).strip()# Jeśli model zwrócił bezpośrednio krótki wynik (np. 'right', '42', 'Rd5') zamiast kodu Python:if (plainand "\n" not in plainand len(plain) <= 80and not plain.endswith((".", "?", ":"))and not re.match(r"^(?:thoughts?|thinking|invalid|error)\b", plain, re.IGNORECASE)):34 unmodified linesinner = converted if converted is not None else raw_blockinner = _guard_unbound_lines(inner)inner = _ensure_observable_output(inner)if "Invalid non-code output." not in inner:inner = _ensure_final_answer_call(inner)try:tree = ast.parse(inner)if not tree.body:3 unmodified linesreturn f"{open_t}\n{inner}\n{close_t}"extracted = _extract_valid_python(text)if "Invalid non-code output." not in extracted:extracted = _ensure_final_answer_call(extracted)return f"{open_t}\n{extracted}\n{close_t}"@classmethod486 unmodified lines"For chess moves, pass ONLY Standard Algebraic Notation (SAN, e.g., 'Rd5', 'Nf6+', 'O-O') without move numbers or commentary. ""For numbers, omit commas ('1500' not '1,500'). ""Always define every variable before using it (never reference undefined variables like `lines`), ""do not import `requests` or `posixpath`, and use `read_local_file(file_path=...)` instead of `open(...)` for local files.")113 unmodified linesif tech_error_pattern.search(cleaned):return ""if cleaned.startswith("final_answer(") and cleaned.endswith(")"):inner_fa = cleaned[len("final_answer("):-1].strip()inner_fa = re.sub(r"^answer\s*=\s*", "", inner_fa).strip()try:lit_val = ast.literal_eval(inner_fa)if isinstance(lit_val, (list, tuple)):4 unmodified linesreturn ""except Exception:return ""else:fa_call = re.search(r"final_answer\s*\(\s*(?:answer\s*=\s*)?(['\"])(.*?)\1\s*\)",cleaned,flags=re.DOTALL,)if fa_call:cleaned = fa_call.group(2).strip()raw_code_pattern = re.compile(r"(?:^|\b)(?:web_search|search_wikipedia|fetch_url_text|"r"download_task_file|read_local_file|inspect_image|inspect_youtube|"r"transcribe_audio|ask_web|final_answer)\s*\(|"r"^\s*print\s*\(|"r"^\s*[A-Za-z_][A-Za-z0-9_]*\s*=\s*[A-Za-z_][A-Za-z0-9_.]*\s*\(|"r"^\s*(?:import|from|def|class|for|while|try|if|elif|else|with|return|raise)\b",re.IGNORECASE | re.MULTILINE,)if raw_code_pattern.search(cleaned):return ""arrow_match = re.search(31 unmodified lineslines = [ln.strip() for ln in cleaned.splitlines() if ln.strip()]answer_line = next((ln for ln in reversed(lines) if not junk_pattern.match(ln) and not raw_code_pattern.match(ln)),"",)if not answer_line:return ""cleaned = answer_line.strip("`").strip()if junk_pattern.match(cleaned) or raw_code_pattern.match(cleaned) or tech_error_pattern.search(cleaned):return ""if (25 unmodified linesdef __call__(self, question: str, task_id: str = "", file_name: str = "") -> str:import timeimport threadingif not hasattr(self, "_local_state"):self._local_state = threading.local()if not hasattr(self, "_dead_models"):249 unmodified linesif cleaned and len(cleaned) <= 2000 and not cleaned.startswith("AGENT ERROR:"):return cleaned# Fallback: wyciągnij zebrane obserwacje z kroków agenta i poproś model o samą odpowiedźcollected_obs = []mem_steps = getattr(getattr(run_agent, "memory", None), "steps", None) or []for st in mem_steps:11 unmodified linesif raw_result and "max steps" not in raw_result.lower():context_blob += f"\n---\nAgent draft: {raw_result[:1500]}"if context_blob.strip():direct_ans = self._direct_extract_answer(model_name=model_name,question=question.strip(),evidence=context_blob[:12000],deadline=deadline,12 unmodified linesbreakhttp_status = getattr(exc, "status_code", None)# 1. Trwały błąd autoryzacji klucza (401/403) -> permanentna rotacja lub blokada provideraif http_status in (401, 403) or any(marker in err_lowerfor marker in (14 unmodified linesblocked_providers.add(provider)break# 2. Brak środków na płatny model (402) -> tymczasowa rotacja klucza lub blokada tylko tego modeluif http_status == 402 or "payment required" in err_lower or "insufficient_quota" in err_lower:if hasattr(self, "_rotate_api_key") and self._rotate_api_key(provider, permanent=False):continueblocked_models.add(model_name)self._model_cooldowns[model_name] = time.monotonic() + 300.0break# 3. Limity (429 / quota) -> rozróżnienie na limit konta vs limit pojedynczego modeluis_provider_quota = any(marker in err_lowerfor marker in ("free-models-per-day","quota","resource_exhausted",)12 unmodified linestransient_retries += 1time.sleep(5.0)continueif is_provider_quota or is_model_rate_limit:if hasattr(self, "_rotate_api_key") and self._rotate_api_key(provider):continuecooldown_until = time.monotonic() + 20.0rate_limited_models.add(model_name)self._model_cooldowns[model_name] = cooldown_until5 unmodified linesself._model_cooldowns[m] = cooldown_untilbreak# 4. Timeout -> blokada modelu na bieżące zadanie + cooldown 60sif any(marker in err_lower for marker in ("timeout", "timed out")):blocked_models.add(model_name)self._model_cooldowns[model_name] = time.monotonic() + 60.0break# 5. Błędy żądania, przekroczenie kontekstu oraz trwałe 404 modeluis_context_overflow = any(marker in err_lowerfor marker in (35 unmodified linesself._dead_models.add(model_name)break# 6. Przeciążenie serwera (503) -> cooldown 60sif http_status == 503 or any(marker in err_lowerfor marker in (7 unmodified linesself._model_cooldowns[model_name] = time.monotonic() + 60.0break# 7. Chwilowy błąd sieci -> 1 szybka ponowna próba, potem cooldownif "connection error" in err_lower:if transient_retries < 1 and (deadline - time.monotonic()) > 10.0:transient_retries += 13 unmodified linesself._model_cooldowns[model_name] = time.monotonic() + 60.0break# 8. Inny nieznany błąd -> pomiń model w tym zadaniu, bez wrzucania do _dead_modelsblocked_models.add(model_name)break249 unmodified linesfinally: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})2103 unmodified lines21042105210621072108210921103 unmodified lines2114211521162117211821192120212121222123212481 unmodified lines22062207220822092210221184 unmodified lines22962297229822992300230123021 unmodified line2304230523062307230823092310231123122313231434 unmodified lines2349235023512352235323543 unmodified lines235823592360236123622363486 unmodified lines2850285128522853285428552856113 unmodified lines29702971297229732974297529762977297829792980298129824 unmodified lines298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301131 unmodified lines30433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306625 unmodified lines3092309330943095309630973098249 unmodified lines33483349335033513352335311 unmodified lines3365336633673368336933703371337233733374337533763377337833793380338112 unmodified lines33943395339633973398339914 unmodified lines3414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344212 unmodified lines34553456345734583459346034613462346334643465346634673468346934703471347234735 unmodified lines3479348034813482348334843485348634873488348935 unmodified lines3525352635273528352935307 unmodified lines3538353935403541354235433 unmodified lines354735483549355035513552249 unmodified lines3802380338043805380638073808380938102103 unmodified linesprint(f"[LLM] {self.model_id}: {time.monotonic() - t0:.1f}s", flush=True)@classmethoddef _sanitize_code_tags(cls, text: str) -> str:import astimport json3 unmodified linesclose_t = cls.close_tagtext = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL | re.IGNORECASE).strip()text = re.sub(r"(?im)^\s*(?:from\s+(?:tools|download_task_file|read_local_file|web_search|search_wikipedia|fetch_url_text|inspect_image|analyze_chessboard|inspect_youtube|transcribe_audio|ask_web)\s+import\s+.*|import\s+(?:tools|download_task_file|read_local_file|web_search|search_wikipedia|fetch_url_text|inspect_image|analyze_chessboard|inspect_youtube|transcribe_audio|ask_web)\b.*)$","",text,).strip()def _convert_xml_tool_calls(raw: str) -> str | None:qwen_calls = re.findall(81 unmodified linesreturn code_strreturn "lines = []\n" + code_strdef _ensure_observable_output(code_str: str) -> str:clean_code = (code_str or "").strip()if not clean_code or "final_answer(" in clean_code:84 unmodified linesif (len(tree.body) == 1and isinstance(tree.body[0], ast.Expr)and isinstance(tree.body[0].value, (ast.Name, ast.Constant, ast.List, ast.Tuple))):continuereturn _ensure_observable_output(_guard_unbound_lines(candidate))1 unmodified linecontinueplain = "\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)):34 unmodified linesinner = 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:3 unmodified linesreturn f"{open_t}\n{inner}\n{close_t}"extracted = _extract_valid_python(text)return f"{open_t}\n{extracted}\n{close_t}"@classmethod486 unmodified lines"For chess moves, pass ONLY Standard Algebraic Notation (SAN, e.g., 'Rd5', 'Nf6+', 'O-O') without move numbers or commentary. ""For numbers, omit commas ('1500' not '1,500'). ""Always define every variable before using it (never reference undefined variables like `lines`), ""NEVER import tools (do NOT write `from download_task_file import ...` or `import tools`—all tools are already built-in global functions), ""do not import `requests` or `posixpath`, and use `read_local_file(file_path=...)` instead of `open(...)` for local files.")113 unmodified linesif tech_error_pattern.search(cleaned):return ""fa_matches = re.findall(r"final_answer\s*\(\s*(?:answer\s*=\s*)?([^()]+?)\s*\)",cleaned,flags=re.DOTALL,)if fa_matches:inner_fa = fa_matches[-1].strip()try:lit_val = ast.literal_eval(inner_fa)if isinstance(lit_val, (list, tuple)):4 unmodified linesreturn ""except Exception:return ""raw_tool_call_pattern = re.compile(r"(?:^|\b)(?:web_search|search_wikipedia|fetch_url_text|"r"download_task_file|read_local_file|inspect_image|analyze_chessboard|inspect_youtube|"r"transcribe_audio|ask_web|final_answer)\s*\(|"r"^\s*print\s*\(|"r"^\s*[A-Za-z_][A-Za-z0-9_]*\s*=\s*[A-Za-z_][A-Za-z0-9_.]*\s*\(",re.IGNORECASE | re.MULTILINE,)raw_py_stmt_pattern = re.compile(r"^\s*(?:import\s+[A-Za-z_][A-Za-z0-9_.]*|"r"from\s+[A-Za-z_][A-Za-z0-9_.]*\s+import\b|"r"def\s+[A-Za-z_][A-Za-z0-9_]*\s*\(|"r"class\s+[A-Za-z_][A-Za-z0-9_]*\s*[:(]|"r"(?:for|while|if|elif|else|try|with)\b.*:\s*$|"r"return\b|raise\b)",re.MULTILINE,)if raw_tool_call_pattern.search(cleaned) or raw_py_stmt_pattern.search(cleaned):return ""arrow_match = re.search(31 unmodified lineslines = [ln.strip() for ln in cleaned.splitlines() if ln.strip()]answer_line = next((ln for ln in reversed(lines)if not junk_pattern.match(ln)and not raw_tool_call_pattern.search(ln)and not raw_py_stmt_pattern.search(ln)),"",)if not answer_line:return ""cleaned = answer_line.strip("`").strip()if (junk_pattern.match(cleaned)or raw_tool_call_pattern.search(cleaned)or raw_py_stmt_pattern.search(cleaned)or tech_error_pattern.search(cleaned)):return ""if (25 unmodified linesdef __call__(self, question: str, task_id: str = "", file_name: str = "") -> str:import timeimport threadingif not hasattr(self, "_local_state"):self._local_state = threading.local()if not hasattr(self, "_dead_models"):249 unmodified linesif cleaned and len(cleaned) <= 2000 and not cleaned.startswith("AGENT ERROR:"):return cleanedcollected_obs = []mem_steps = getattr(getattr(run_agent, "memory", None), "steps", None) or []for st in mem_steps:11 unmodified linesif raw_result and "max steps" not in raw_result.lower():context_blob += f"\n---\nAgent draft: {raw_result[:1500]}"if context_blob.strip():extract_model = next((m for m in [model_name] + models_to_tryif m not in blocked_modelsand m not in rate_limited_modelsand (m.split("/", 1)[0].lower() if "/" in m else "gemini") not in blocked_providers),model_name,)direct_ans = self._direct_extract_answer(model_name=extract_model,question=question.strip(),evidence=context_blob[:12000],deadline=deadline,12 unmodified linesbreakhttp_status = getattr(exc, "status_code", None)if http_status in (401, 403) or any(marker in err_lowerfor marker in (14 unmodified linesblocked_providers.add(provider)breakif http_status == 402 or "payment required" in err_lower or "insufficient_quota" in err_lower:if hasattr(self, "_rotate_api_key") and self._rotate_api_key(provider, permanent=True):continueblocked_models.add(model_name)self._dead_models.add(model_name)breakis_daily_exhausted = any(marker in err_lowerfor marker in ("free-models-per-day","perday","per_day","tokens per day","tpd","daily limit",))is_provider_quota = is_daily_exhausted or any(marker in err_lowerfor marker in ("quota","resource_exhausted",)12 unmodified linestransient_retries += 1time.sleep(5.0)continueif is_provider_quota or is_model_rate_limit:if hasattr(self, "_rotate_api_key") and self._rotate_api_key(provider, permanent=is_daily_exhausted):continueif is_daily_exhausted:for m in models_to_try:if m.startswith(f"{provider}/"):blocked_models.add(m)self._dead_models.add(m)blocked_providers.add(provider)breakcooldown_until = time.monotonic() + 20.0rate_limited_models.add(model_name)self._model_cooldowns[model_name] = cooldown_until5 unmodified linesself._model_cooldowns[m] = cooldown_untilbreakif any(marker in err_lower for marker in ("timeout", "timed out")):blocked_models.add(model_name)self._model_cooldowns[model_name] = time.monotonic() + 60.0breakis_context_overflow = any(marker in err_lowerfor marker in (35 unmodified linesself._dead_models.add(model_name)breakif http_status == 503 or any(marker in err_lowerfor marker in (7 unmodified linesself._model_cooldowns[model_name] = time.monotonic() + 60.0breakif "connection error" in err_lower:if transient_retries < 1 and (deadline - time.monotonic()) > 10.0:transient_retries += 13 unmodified linesself._model_cooldowns[model_name] = time.monotonic() + 60.0breakblocked_models.add(model_name)break249 unmodified linesfinally:executor.shutdown(wait=False, cancel_futures=True)if not isinstance(submitted_answer, str) or not submitted_answer.strip():submitted_answer = "AGENT ERROR: Empty answer"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})
app.py+79-99