Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files896 unmodified lines8978988999009019029035 unmodified lines909910911911912913914915850 unmodified lines17661767176817681769176917701771177217731 unmodified line17751776177717771778177817791780178117811782178317841785178617861787178817891790540 unmodified lines23312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523382376237723782379238023422343234423452346234723812382234923832384238523862387238823892356239023912392239323942361239523962363236423652366236723682369237023712372239723982399240024012402240324047 unmodified lines24122413241423862415241624172418241924202392239323942395239623972398239924002401242124222423240324042424242524262427242824292430243124322433243424352436243724382439240624402441244224092443241124122444244524462447244824492450245124522453245424152416245524562457245824592460246124622463246475 unmodified lines254025412542250125432544254525462547250725482549255025112512251325142515251625172551255225532554255525562557255825592560256114 unmodified lines25762577257825422579258025811 unmodified line25832584258525502586258725881 unmodified line25902591259225932594259525962597259825992600260126022603260425622563260526062607256625672568256925702571257225732574257525762577257826082609261026112612261325832584258525862587258825892614261526162617261899 unmodified lines27182719272027212722272327242725272627272728269626972729273027312732273389 unmodified lines2823282428252793282628272828282918 unmodified lines2848284928502818281928512852282128222853285428552856285728584 unmodified lines286328642865286628672833286828692870287112 unmodified lines288428852886285228872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291328612914291529162917291829192920292128672922292329242925292629272869287028712872287328742875292829292930293129322933293429352936293729386 unmodified lines2945294629472891289228932894289528962897289828992900290129022903290429052906290729482949295029512952295329542955295629572909295829592960296129622963296429652966296729682969297029712972291129732974297529142976297729782979298029815 unmodified lines298729882989299029912992299329942 unmodified lines2997299829993000300130023003300422 unmodified lines30273028302930303031303229623033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060896 unmodified lines self.gemini_flash_models or [ "gemini/gemini-3-flash-preview", "gemini/gemini-2.5-flash", "gemini/gemini-flash-latest", ] )5 unmodified lines ]) if self.provider_keys.get("nvidia_nim"): vision_candidates.extend([ "nvidia_nim/moonshotai/kimi-k3_1-pro", "nvidia_nim/moonshotai/kimi-k2.5", "nvidia_nim/nvidia/nemotron-3-ultra-550b-a55b", ])
850 unmodified lines def _trim_messages(raw_msgs): if not isinstance(raw_msgs, list): return raw_msgs if len(raw_msgs) > 4: selected = [raw_msgs[0]] + raw_msgs[-2:] if len(raw_msgs) > 6: selected = [raw_msgs[0]] + raw_msgs[-4:] else: selected = raw_msgs out = []1 unmodified line m_copy = copy.copy(m) if isinstance(m_copy, dict): content = m_copy.get("content") if isinstance(content, str) and len(content) > 2500: m_copy["content"] = content[:1200] + "\n...[trimmed]...\n" + content[-1200:] if isinstance(content, str) and len(content) > 3200: m_copy["content"] = content[:1500] + "\n...[trimmed]...\n" + content[-1500:] else: content = getattr(m_copy, "content", None) if isinstance(content, str) and len(content) > 2500: if isinstance(content, str) and len(content) > 3200: try: setattr( m_copy, "content", content[:1200] + "\n...[trimmed]...\n" + content[-1200:], content[:1500] + "\n...[trimmed]...\n" + content[-1500:], ) except Exception: pass540 unmodified lines } return self._model_cls(**kwargs)
DEAD_MODEL_PATTERNS = ( "model_not_found", "does not exist", "decommissioned", "no longer supported", "is not found for api version", "unknown model", )
def _classify_preflight_error(err: Exception) -> str: msg = str(err).lower() status = getattr(err, "status_code", None) if status is None: resp = getattr(err, "response", None) status = getattr(resp, "status_code", None)
if status == 404 or any(p in msg for p in DEAD_MODEL_PATTERNS): return "DEAD_MODEL"
if status in (401, 403) or "invalid_api_key" in msg or "permission_denied" in msg: return "DEAD_KEY"
if status == 400 or "unsupported" in msg or "invalid_request_error" in msg: return "BAD_REQUEST_PARAM"
return "TRANSIENT_BUSY"
def _remove_specific_key(provider: str, bad_key: str) -> None: with self._state_lock: pool = self.provider_key_pools.get(provider) or [] if bad_key and bad_key in pool: pool = [k for k in pool if k != bad_key] self.provider_key_pools[provider] = pool self._provider_key_idx[provider] = 0 _sync_provider_env(provider, pool[0] if pool else "")
def _probe_candidate(model_name: str) -> tuple[str, str, str]: import time
provider = 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", "no 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("gemini/"): kw["reasoning_effort"] = "low" elif model_name.startswith("groq/") and "qwen3" in model_name.lower(): kw["reasoning_effort"] = "none" kw["reasoning_format"] = "hidden" elif model_name.startswith("huggingface/"): if model_name.startswith("huggingface/"): kw = { "model": "openai/" + model_name[len("huggingface/"):], "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=32, max_tokens=16, timeout=8, num_retries=0, max_retries=0, ) return (model_name, "ok", f"{time.monotonic() - t0:.1f}s") return (model_name, "OK", f"{time.monotonic() - t0:.1f}s") except Exception as exc: text = f"{type(exc).__name__}: {exc}" low = text.lower() short = " ".join(text.split())[:220] transient_markers = ( "429", "403", "401", "quota", "rate limit", "resource_exhausted", "timeout", "timed out", "connection", "503", "502", "overloaded", "unavailable", ) if any(m in low for m in transient_markers): return (model_name, "busy", short) return (model_name, "dead", short) 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_wait
7 unmodified lines try: p_name, p_state, p_info = fut.result() probe_status[p_name] = p_state print(f"[PREFLIGHT] {p_state.upper():4} {p_name} :: {p_info}", flush=True) print(f"[PREFLIGHT] {p_state:18} {p_name} :: {p_info}", flush=True) except Exception: pass finally: probe_pool.shutdown(wait=False, cancel_futures=True)
tested_providers = { m.split("/", 1)[0].lower() for m in probe_status if "/" in m } for prov in tested_providers: prov_states = [ st for m, st in probe_status.items() if m.startswith(f"{prov}/") ] if prov_states and all(st == "dead" for st in prov_states): self.provider_key_pools[prov] = [] self._sync_provider_env(prov, "") if not hasattr(self, "_dead_models"): self._dead_models = set()
dead_models = {m for m, st in probe_status.items() if st == "dead"} ok_models = [m for m in self.working_models if probe_status.get(m) == "ok"] for m_name, st in probe_status.items(): if st == "DEAD_MODEL": self._dead_models.add(m_name)
# Usuwamy tylko trwałe DEAD_MODEL; reszta (OK, BAD_REQUEST_PARAM, TRANSIENT_BUSY, DEAD_KEY jeśli zostały inne klucze) zostaje surviving_models = [] for m_name in self.working_models: if m_name in self._dead_models or probe_status.get(m_name) == "DEAD_MODEL": continue prov = m_name.split("/", 1)[0].lower() if "/" in m_name else "gemini" if not (self.provider_key_pools.get(prov) or []): continue surviving_models.append(m_name)
ok_models = [m for m in surviving_models if probe_status.get(m) == "OK"] untested_non_or = [ m for m in self.working_models m for m in surviving_models if m not in probe_status and not m.startswith("openrouter/") ] busy_models = [m for m in self.working_models if probe_status.get(m) == "busy"] openrouter_models = [ m for m in self.working_models if m.startswith("openrouter/") and m not in dead_models m for m in surviving_models if m.startswith("openrouter/") ] degraded_models = [ m for m in surviving_models if probe_status.get(m) in ("BAD_REQUEST_PARAM", "TRANSIENT_BUSY", "DEAD_KEY") and m not in ok_models and m not in untested_non_or and m not in openrouter_models ]
# OpenRouter wchodzi przed chwilowo przeciążone (busy) modele, a martwe (dead) są całkowicie odrzucane reordered = (ok_models + untested_non_or + openrouter_models + busy_models)[:4] reordered = ok_models + untested_non_or + openrouter_models + degraded_models if reordered: self.working_models = reordered
if not self.working_models: raise RuntimeError("No models available after preflight.")
self.model_id = self.working_models[0] print(f"Using primary LLM model: {self.model_id} (fallbacks: {self.working_models[1:]})")
75 unmodified lines print("CodeAgent initialized with LiteLLMModel.")
def _clean_exact_match_answer(self, text: str) -> str: import json import re
if text is None: return ""
# Na początku funkcji, po sprawdzeniu None cleaned = str(text).strip() if not cleaned or cleaned.startswith("AGENT ERROR:"): return cleaned # Usuwanie znaczników cleaned = re.sub(r"</?code[^>]*>", "", cleaned, flags=re.IGNORECASE) cleaned = re.sub(r"final_answer\s*\(\s*", "", cleaned, flags=re.IGNORECASE) cleaned = re.sub(r"^final_answer\s*:\s*", "", cleaned, flags=re.IGNORECASE) cleaned = cleaned.strip()
code_match = re.search(r"<code[^>]*>(.*?)</code>", cleaned, flags=re.DOTALL | re.IGNORECASE) if code_match: cleaned = code_match.group(1).strip() else: cleaned = re.sub(r"</?code[^>]*>", "", cleaned, flags=re.IGNORECASE).strip()
cleaned = re.sub(r"^final_answer\s*:\s*", "", cleaned, flags=re.IGNORECASE).strip()
cleaned = re.sub( r'\{\s*["\']tool["\']\s*:\s*["\'][^"\']+["\']\s*,\s*["\']arguments["\']\s*:\s*\{.*?\}\s*\}',14 unmodified lines if fa_call: cleaned = (fa_call.group(2) or fa_call.group(3) or "").strip()
# Obsługa formatu "answer -> wartość" (tylko gdy -> jest w kontekście odpowiedzi) arrow_match = re.search( r"\b(?:answer|result|output|final\s+answer)\s*->\s*(.+)$", cleaned,1 unmodified line ) if arrow_match: tail_part = arrow_match.group(1).strip() # Najpierw spróbuj wyciągnąć ostatni fragment w cudzysłowach (pojedynczych lub podwójnych) quoted_match = re.findall(r'"([^"]+)"|\'([^\']+)\'', tail_part) if quoted_match: last_q = quoted_match[-1]1 unmodified line else: cleaned = tail_part.strip(" .\"'")
cleaned = re.sub( r"^(?:so\s+the\s+answer\s+is|the\s+answer\s+is|therefore|thus|hence|in\s+conclusion|" r"based\s+on\s+the\s+(?:text|article|table|video|search\s+results)|according\s+to\s+the\s+(?:text|article|table|video))\s*[,:\-–—]?\s*", "", cleaned, flags=re.IGNORECASE, ).strip()
junk_pattern = re.compile( r"^(?:the wikipedia article|the youtube video|the search results show|this scene is from|" r"the page is quite long|the task doesn't have|the download failed|let me try|let me search|" r"let me check|now i need to find|i found the|the operation is not commutative|" r"the scene occurs|so the answer is|therefore|thus|hence|in conclusion|" r"i need to|i should|i will|i can|based on the|according to the)\b", r"the scene occurs|i need to|i should|i will|i can)\b", re.IGNORECASE, ) answer_line = "" for ln in reversed(lines): if not junk_pattern.match(ln): answer_line = ln break lines = [ln.strip() for ln in cleaned.splitlines() if ln.strip()] answer_line = "" for ln in reversed(lines): if not junk_pattern.match(ln): answer_line = ln break
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)), "") if not answer_line: return ""
cleaned = answer_line
if re.match( r"^(?:the wikipedia article|the youtube video|the search results show|this scene is from|the page is quite long|the task doesn't have|the download failed|let me try|let me search|let me check|now i need to find|i found the|the operation is not commutative|the scene occurs)\b", cleaned, flags=re.IGNORECASE, ): cleaned = answer_line.strip("`").strip() if junk_pattern.match(cleaned): return ""
return cleaned99 unmodified lines and file_preview.strip() and not file_preview.startswith(("Error ", "File not found")) ): clean_preview = file_preview.strip() if len(clean_preview) > 6000: clean_preview = ( clean_preview[:3000] + "\n...[truncated]...\n" + clean_preview[-3000:] ) prompt += ( f"\n\nTask ID: {task_id}. Attachment '{prefetched_path}' content (truncated):\n" f"{file_preview.strip()[:4000]}" f"\n\nTask ID: {task_id}. Attachment '{prefetched_path}' content:\n" f"{clean_preview}" ) tool_hint = "" except Exception as rd_exc:89 unmodified lines built_model.timeout = call_timeout built_model.deadline = deadline run_agent = self._create_code_agent(built_model) run_agent.max_steps = 4 if rem_now > 45.0 else (3 if rem_now > 20.0 else 2) run_agent.max_steps = 6 if rem_now > 60.0 else (4 if rem_now > 25.0 else 3) result = run_agent.run(prompt) print( f"[TRACE] task_id={task_id} model={model_name} "18 unmodified lines and not fallback_clean.startswith( ("AGENT ERROR:", "Error ", "No attachment", "No web results", "No Wikipedia") ) and "\n" not in fallback_clean and len(fallback_clean) <= 200 and len(fallback_clean) <= 600 ): return fallback_clean return "" return " ".join(fallback_clean.splitlines()).strip() blocked_models.add(model_name) continue except Exception as exc: llm_err = getattr(built_model, "_last_llm_error", None) if llm_err is not None and llm_err is not exc:4 unmodified lines if "task time budget exhausted" in err_lower: 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, 402, 403) or any( if http_status in (401, 403) or any( marker in err_lower for marker in ( "authentication",12 unmodified lines blocked_models.add(m) blocked_providers.add(provider) break if any(
# 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 ): continue blocked_models.add(model_name) self._model_cooldowns[model_name] = time.monotonic() + 300.0 break
# 3. Limity (429 / quota) -> rozróżnienie na limit konta vs limit pojedynczego modelu is_provider_quota = any( marker in err_lower for marker in ( "free-models-per-day", "quota", "resource_exhausted", ) ) is_model_rate_limit = http_status == 429 or any( marker in err_lower for marker in ( "429", "rate limit exceeded", "too many requests", ) ): ) if is_provider_quota or is_model_rate_limit: if hasattr(self, "_rotate_api_key") and self._rotate_api_key(provider): continue cooldown_until = time.monotonic() + 20.0 rate_limited_models.add(model_name) self._model_cooldowns[model_name] = cooldown_until if is_provider_quota: rate_limited_providers.add(provider) rate_limited_providers.add(provider) for m in models_to_try: if m.startswith(f"{provider}/"): rate_limited_models.add(m) self._model_cooldowns[m] = cooldown_until break if any( marker in err_lower for marker in ( "timeout", "timed out", ) ):
# 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 (6 unmodified lines "request too large", ) ) if ( http_status in (400, 404) or any( marker in err_lower for marker in ( "badrequesterror", "bad request", "invalid_request_error", "reasoning is mandatory", "cannot be disabled", "does not support", "404", "not found", "model_not_found", "decommissioned", "unsupported", ) is_hard_dead_model = http_status == 404 or any( marker in err_lower for marker in ( "model_not_found", "does not exist", "decommissioned", "no longer supported", "is not found for api version", "unknown model", ) ): ) is_bad_request = http_status == 400 or any( marker in err_lower for marker in ( "badrequesterror", "bad request", "invalid_request_error", "reasoning is mandatory", "cannot be disabled", "does not support", "unsupported", ) ) if is_hard_dead_model or is_bad_request or is_context_overflow: blocked_models.add(model_name) if not is_context_overflow: if is_hard_dead_model and not is_context_overflow: self._dead_models.add(model_name) break if any(
# 6. Przeciążenie serwera (503) -> cooldown 60s if http_status == 503 or any( marker in err_lower for marker in ( "503",5 unmodified lines blocked_models.add(model_name) 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 += 12 unmodified lines blocked_models.add(model_name) 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
22 unmodified lines continue break finally: local_state = getattr(self, "_local_state", None) if local_state is not None: try: self._local_state.deadline = None local_state.deadline = None except Exception: pass self._task_deadline = None
last_non_empty_steps = None last_agent = locals().get("run_agent") last_steps = getattr(getattr(last_agent, "memory", None), "steps", None) if last_steps: last_non_empty_steps = last_steps if last_non_empty_steps: for st in reversed(last_non_empty_steps): cand_val = getattr(st, "action_output", None) if cand_val is None: continue fallback_clean = self._clean_exact_match_answer(str(cand_val)) if ( fallback_clean and not fallback_clean.startswith( ("AGENT ERROR:", "Error ", "No attachment", "No web results", "No Wikipedia") ) and len(fallback_clean) <= 600 ): return " ".join(fallback_clean.splitlines()).strip()
return ""
app.py+211-118