Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files896 unmodified lines8978988999009019025 unmodified lines908909910911912913914850 unmodified lines176517661767176817691770177117721 unmodified line1774177517761777177817791780178117821783178417851786178717881789540 unmodified lines23302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423757 unmodified lines238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242275 unmodified lines24982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252414 unmodified lines25392540254125422543254425451 unmodified line25472548254925502551255225531 unmodified line2555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259299 unmodified lines26922693269426952696269726982699270089 unmodified lines279027912792279327942795279618 unmodified lines281528162817281828192820282128222823282428254 unmodified lines283028312832283328342835283612 unmodified lines2849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028816 unmodified lines2888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629175 unmodified lines2923292429252926292729282 unmodified lines29312932293329342935293622 unmodified lines295929602961296229632964296529662967896 unmodified linesself.gemini_flash_modelsor ["gemini/gemini-3-flash-preview","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/nvidia/nemotron-3-ultra-550b-a55b",])850 unmodified linesdef _trim_messages(raw_msgs):if not isinstance(raw_msgs, list):return raw_msgsif len(raw_msgs) > 4:selected = [raw_msgs[0]] + raw_msgs[-2:]else:selected = raw_msgsout = []1 unmodified linem_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:]else:content = getattr(m_copy, "content", None)if isinstance(content, str) and len(content) > 2500:try:setattr(m_copy,"content",content[:1200] + "\n...[trimmed]...\n" + content[-1200:],)except Exception:pass540 unmodified lines}return self._model_cls(**kwargs)def _probe_candidate(model_name: str) -> tuple[str, str, str]:import timeapi_key = self._get_api_key(model_name)if not api_key:return (model_name, "dead", "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/"):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=32,timeout=8,num_retries=0,max_retries=0,)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)from concurrent.futures import ThreadPoolExecutor, wait as futures_wait7 unmodified linestry:p_name, p_state, p_info = fut.result()probe_status[p_name] = p_stateprint(f"[PREFLIGHT] {p_state.upper():4} {p_name} :: {p_info}", flush=True)except Exception:passfinally: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, "")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"]untested_non_or = [m for m in self.working_modelsif 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_modelsif m.startswith("openrouter/") and m not in dead_models]# OpenRouter wchodzi przed chwilowo przeciążone (busy) modele, a martwe (dead) są całkowicie odrzucanereordered = (ok_models + untested_non_or + openrouter_models + busy_models)[:4]if reordered:self.working_models = reorderedself.model_id = self.working_models[0]print(f"Using primary LLM model: {self.model_id} (fallbacks: {self.working_models[1:]})")75 unmodified linesprint("CodeAgent initialized with LiteLLMModel.")def _clean_exact_match_answer(self, text: str) -> str:import jsonimport reif text is None:return ""# Na początku funkcji, po sprawdzeniu Nonecleaned = str(text).strip()if not cleaned or cleaned.startswith("AGENT ERROR:"):return cleaned# Usuwanie znacznikówcleaned = 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()cleaned = re.sub(r'\{\s*["\']tool["\']\s*:\s*["\'][^"\']+["\']\s*,\s*["\']arguments["\']\s*:\s*\{.*?\}\s*\}',14 unmodified linesif 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 lineelse:cleaned = tail_part.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",re.IGNORECASE,)answer_line = ""for ln in reversed(lines):if not junk_pattern.match(ln):answer_line = lnbreaklines = [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 = lnbreakif not answer_line:return ""cleaned = answer_lineif 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,):return ""return cleaned99 unmodified linesand file_preview.strip()and not file_preview.startswith(("Error ", "File not found"))):prompt += (f"\n\nTask ID: {task_id}. Attachment '{prefetched_path}' content (truncated):\n"f"{file_preview.strip()[:4000]}")tool_hint = ""except Exception as rd_exc:89 unmodified linesbuilt_model.timeout = call_timeoutbuilt_model.deadline = deadlinerun_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)result = run_agent.run(prompt)print(f"[TRACE] task_id={task_id} model={model_name} "18 unmodified linesand not fallback_clean.startswith(("AGENT ERROR:", "Error ", "No attachment", "No web results", "No Wikipedia"))and "\n" not in fallback_cleanand len(fallback_clean) <= 200):return fallback_cleanreturn ""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 linesif "task time budget exhausted" in err_lower:breakhttp_status = getattr(exc, "status_code", None)if http_status in (401, 402, 403) or any(marker in err_lowerfor marker in ("authentication",12 unmodified linesblocked_models.add(m)blocked_providers.add(provider)breakif any(marker in err_lowerfor marker in ("free-models-per-day","quota","resource_exhausted","429","rate limit exceeded",)):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_untilrate_limited_providers.add(provider)breakif any(marker in err_lowerfor 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 (6 unmodified lines"request too large",))if (http_status in (400, 404)or any(marker in err_lowerfor 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",))):blocked_models.add(model_name)if not is_context_overflow:self._dead_models.add(model_name)breakif any(marker in err_lowerfor marker in ("503",5 unmodified linesblocked_models.add(model_name)self._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 += 12 unmodified linesblocked_models.add(model_name)self._model_cooldowns[model_name] = time.monotonic() + 60.0breakblocked_models.add(model_name)break22 unmodified linescontinuebreakfinally:self._local_state.deadline = Noneself._task_deadline = Nonereturn ""896 unmodified lines8978988999009019029035 unmodified lines909910911912913914915850 unmodified lines176617671768176917701771177217731 unmodified line1775177617771778177917801781178217831784178517861787178817891790540 unmodified lines233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324047 unmodified lines2412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246475 unmodified lines254025412542254325442545254625472548254925502551255225532554255525562557255825592560256114 unmodified lines2576257725782579258025811 unmodified line2583258425852586258725881 unmodified line2590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261899 unmodified lines271827192720272127222723272427252726272727282729273027312732273389 unmodified lines282328242825282628272828282918 unmodified lines284828492850285128522853285428552856285728584 unmodified lines28632864286528662867286828692870287112 unmodified lines28842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729386 unmodified lines29452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029815 unmodified lines298729882989299029912992299329942 unmodified lines2997299829993000300130023003300422 unmodified lines3027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060896 unmodified linesself.gemini_flash_modelsor ["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-k2.5","nvidia_nim/nvidia/nemotron-3-ultra-550b-a55b",])850 unmodified linesdef _trim_messages(raw_msgs):if not isinstance(raw_msgs, list):return raw_msgsif len(raw_msgs) > 6:selected = [raw_msgs[0]] + raw_msgs[-4:]else:selected = raw_msgsout = []1 unmodified linem_copy = copy.copy(m)if isinstance(m_copy, dict):content = m_copy.get("content")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) > 3200:try:setattr(m_copy,"content",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] = poolself._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 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_wait7 unmodified linestry:p_name, p_state, p_info = fut.result()probe_status[p_name] = p_stateprint(f"[PREFLIGHT] {p_state:18} {p_name} :: {p_info}", flush=True)except Exception:passfinally:probe_pool.shutdown(wait=False, cancel_futures=True)if not hasattr(self, "_dead_models"):self._dead_models = set()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) zostajesurviving_models = []for m_name in self.working_models:if m_name in self._dead_models or probe_status.get(m_name) == "DEAD_MODEL":continueprov = m_name.split("/", 1)[0].lower() if "/" in m_name else "gemini"if not (self.provider_key_pools.get(prov) or []):continuesurviving_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 surviving_modelsif m not in probe_status and not m.startswith("openrouter/")]openrouter_models = [m for m in surviving_modelsif m.startswith("openrouter/")]degraded_models = [m for m in surviving_modelsif probe_status.get(m) in ("BAD_REQUEST_PARAM", "TRANSIENT_BUSY", "DEAD_KEY")and m not in ok_modelsand m not in untested_non_orand m not in openrouter_models]reordered = ok_models + untested_non_or + openrouter_models + degraded_modelsif reordered:self.working_models = reorderedif 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 linesprint("CodeAgent initialized with LiteLLMModel.")def _clean_exact_match_answer(self, text: str) -> str:import reif text is None:return ""cleaned = str(text).strip()if not cleaned or cleaned.startswith("AGENT ERROR:"):return cleanedcode_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 linesif fa_call:cleaned = (fa_call.group(2) or fa_call.group(3) or "").strip()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()quoted_match = re.findall(r'"([^"]+)"|\'([^\']+)\'', tail_part)if quoted_match:last_q = quoted_match[-1]1 unmodified lineelse: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|i need to|i should|i will|i can)\b",re.IGNORECASE,)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.strip("`").strip()if junk_pattern.match(cleaned):return ""return cleaned99 unmodified linesand 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:\n"f"{clean_preview}")tool_hint = ""except Exception as rd_exc:89 unmodified linesbuilt_model.timeout = call_timeoutbuilt_model.deadline = deadlinerun_agent = self._create_code_agent(built_model)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 linesand 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()blocked_models.add(model_name)continueexcept 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 linesif "task time budget exhausted" in err_lower:breakhttp_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 ("authentication",12 unmodified linesblocked_models.add(m)blocked_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",))is_model_rate_limit = http_status == 429 or any(marker in err_lowerfor 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):continuecooldown_until = time.monotonic() + 20.0rate_limited_models.add(model_name)self._model_cooldowns[model_name] = cooldown_untilif is_provider_quota: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_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 (6 unmodified lines"request too large",))is_hard_dead_model = http_status == 404 or any(marker in err_lowerfor 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_lowerfor 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 is_hard_dead_model and not is_context_overflow:self._dead_models.add(model_name)break# 6. Przeciążenie serwera (503) -> cooldown 60sif http_status == 503 or any(marker in err_lowerfor marker in ("503",5 unmodified linesblocked_models.add(model_name)self._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 += 12 unmodified linesblocked_models.add(model_name)self._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)break22 unmodified linescontinuebreakfinally:local_state = getattr(self, "_local_state", None)if local_state is not None:try:local_state.deadline = Noneexcept Exception:passself._task_deadline = Nonelast_non_empty_steps = Nonelast_agent = locals().get("run_agent")last_steps = getattr(getattr(last_agent, "memory", None), "steps", None)if last_steps:last_non_empty_steps = last_stepsif last_non_empty_steps:for st in reversed(last_non_empty_steps):cand_val = getattr(st, "action_output", None)if cand_val is None:continuefallback_clean = self._clean_exact_match_answer(str(cand_val))if (fallback_cleanand 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