Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files2103 unmodified lines210421052106210721072108210921103 unmodified lines2114211521162117211821192120212121222123212481 unmodified lines220622072208220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122092210221184 unmodified lines229622972298235222992300230123021 unmodified line23042305230623602307230823092310231123122313231434 unmodified lines234923502351240524062352235323543 unmodified lines23582359236024162417236123622363486 unmodified lines2850285128522853285428552856113 unmodified lines29702971297230293030303129732974297529762977297829792980298129824 unmodified lines2987298829893042304330443045304630473048304929903051299129923053299329942995305630572996299729983060299930003001300230033004300530063007300830093010301131 unmodified lines3043304430453098304630473048304930503051305230533054305530563057310530583059306030613062306330643065306625 unmodified lines30923093309431373095309630973098249 unmodified lines334833493350339333513352335311 unmodified lines33653366336733683369337033713372337333743375337633773412337833793380338112 unmodified lines339433953396343133973398339914 unmodified lines341434153416345234173418345534193420342134223459342334243425346234633426342734283429343034313432343334343435343634373438343934403441344212 unmodified lines3455345634573485345834593487346034613462346334643465346634673468346934703471347234735 unmodified lines347934803481350034823483348434853486350634873488348935 unmodified lines35253526352735483528352935307 unmodified lines35383539354035623541354235433 unmodified lines3547354835493572355035513552249 unmodified lines3802380338043805380638073808380938102103 unmodified lines print(f"[LLM] {self.model_id}: {time.monotonic() - t0:.1f}s", flush=True)
@classmethod@classmethod def _sanitize_code_tags(cls, text: str) -> str: import ast import json3 unmodified lines close_t = cls.close_tag
text = 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 lines return code_str return "lines = []\n" + code_str
def _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_code try: tree = ast.parse(clean_code) except SyntaxError: return clean_code if not tree.body: return clean_code
observation_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 = None if isinstance(node.func, ast.Name): func_name = node.func.id elif isinstance(node.func, ast.Attribute): func_name = node.func.attr if func_name in observation_tools: return clean_code
last_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_snippet return clean_code
def _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 lines if ( len(tree.body) == 1 and isinstance(tree.body[0], ast.Expr) and isinstance(tree.body[0].value, (ast.Name, ast.Constant)) and isinstance(tree.body[0].value, (ast.Name, ast.Constant, ast.List, ast.Tuple)) ): continue return _ensure_observable_output(_guard_unbound_lines(candidate))1 unmodified line continue
plain = "\n".join(src_lines).strip() # Jeśli model zwrócił bezpośrednio krótki wynik (np. 'right', '42', 'Rd5') zamiast kodu Python: if ( plain and "\n" not in plain and len(plain) <= 80 and 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 lines inner = converted if converted is not None else raw_block inner = _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 lines return 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`), " "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 lines if 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() 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 lines return "" 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( raw_tool_call_pattern = re.compile( r"(?:^|\b)(?:web_search|search_wikipedia|fetch_url_text|" r"download_task_file|read_local_file|inspect_image|inspect_youtube|" 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*\(|" r"^\s*(?:import|from|def|class|for|while|try|if|elif|else|with|return|raise)\b", r"^\s*[A-Za-z_][A-Za-z0-9_]*\s*=\s*[A-Za-z_][A-Za-z0-9_.]*\s*\(", re.IGNORECASE | re.MULTILINE, ) if raw_code_pattern.search(cleaned): 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 lines
lines = [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)), ( 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_code_pattern.match(cleaned) or tech_error_pattern.search(cleaned): 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 lines def __call__(self, question: str, task_id: str = "", file_name: str = "") -> str: import time import threading
if not hasattr(self, "_local_state"): self._local_state = threading.local() if not hasattr(self, "_dead_models"):249 unmodified lines if 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 lines if 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_try if m not in blocked_models and m not in rate_limited_models and (m.split("/", 1)[0].lower() if "/" in m else "gemini") not in blocked_providers ), model_name, ) direct_ans = self._direct_extract_answer( model_name=model_name, model_name=extract_model, question=question.strip(), evidence=context_blob[:12000], deadline=deadline,12 unmodified lines break http_status = getattr(exc, "status_code", None)
# 1. Trwały błąd autoryzacji klucza (401/403) -> permanentna rotacja lub blokada providera if http_status in (401, 403) or any( marker in err_lower for marker in (14 unmodified lines blocked_providers.add(provider) break
# 2. Brak środków na płatny model (402) -> tymczasowa rotacja klucza lub blokada tylko tego modelu if 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 provider, permanent=True ): continue blocked_models.add(model_name) self._model_cooldowns[model_name] = time.monotonic() + 300.0 self._dead_models.add(model_name) break
# 3. Limity (429 / quota) -> rozróżnienie na limit konta vs limit pojedynczego modelu is_provider_quota = any( is_daily_exhausted = any( marker in err_lower for 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_lower for marker in ( "quota", "resource_exhausted", )12 unmodified lines transient_retries += 1 time.sleep(5.0) continue
if is_provider_quota or is_model_rate_limit: if hasattr(self, "_rotate_api_key") and self._rotate_api_key(provider): if hasattr(self, "_rotate_api_key") and self._rotate_api_key( provider, permanent=is_daily_exhausted ): continue if 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) break cooldown_until = time.monotonic() + 20.0 rate_limited_models.add(model_name) self._model_cooldowns[model_name] = cooldown_until5 unmodified lines self._model_cooldowns[m] = cooldown_until break
# 4. Timeout -> blokada modelu na bieżące zadanie + cooldown 60s if any(marker in err_lower for marker in ("timeout", "timed out")): blocked_models.add(model_name) self._model_cooldowns[model_name] = time.monotonic() + 60.0 break
# 5. Błędy żądania, przekroczenie kontekstu oraz trwałe 404 modelu is_context_overflow = any( marker in err_lower for marker in (35 unmodified lines self._dead_models.add(model_name) break
# 6. Przeciążenie serwera (503) -> cooldown 60s if http_status == 503 or any( marker in err_lower for marker in (7 unmodified lines self._model_cooldowns[model_name] = time.monotonic() + 60.0 break
# 7. Chwilowy błąd sieci -> 1 szybka ponowna próba, potem cooldown if "connection error" in err_lower: if transient_retries < 1 and (deadline - time.monotonic()) > 10.0: transient_retries += 13 unmodified lines self._model_cooldowns[model_name] = time.monotonic() + 60.0 break
# 8. Inny nieznany błąd -> pomiń model w tym zadaniu, bez wrzucania do _dead_models blocked_models.add(model_name) break
249 unmodified lines finally: 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