Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files807 unmodified lines808809810811812813814201 unmodified lines101610171018101910201021102210231024102510261027199 unmodified lines12271228122912301231123212331277 unmodified lines2511251225132514251525162517251825192520252125222523252425253 unmodified lines252925302531253225332534253525362537253825392540254164 unmodified lines2606260726082609261026112612261394 unmodified lines27082709271027112712271327149 unmodified lines272427252726272727282729273027312732273327342735273627372738273927402741274227432744807 unmodified linesreturn "No results."def _litellm_route_kwargs(model_name: str, api_key: str) -> dict:return {"model": model_name, "api_key": api_key}def _is_daily_quota_exhausted(err_lower: str) -> bool:return any(201 unmodified linescontinueif _is_daily_quota_exhausted(err_low):rate_limited_providers.add(v_provider)else:with self._state_lock:pool = self.provider_key_pools.get(v_provider) or []self._provider_key_idx[v_provider] = 0if hasattr(self, "_sync_provider_env"):self._sync_provider_env(v_provider, pool[0] if pool else "")breakbreak199 unmodified linestranscript = " ".join(c for c in cues if c)if transcript:lang = tr.get("languageCode", "unknown")sections.append(f"Transcript ({lang}):\n{transcript[:8000]}")has_transcript = Truebreakexcept Exception as tr_exc:1277 unmodified linesif code_match:cleaned = code_match.group(1).strip()json_block = re.search(r'\{\s*["\']tool["\']\s*:\s*["\'][^"\']+["\']\s*,\s*["\']arguments["\']\s*:\s*\{.*?\}\s*\}',cleaned,flags=re.DOTALL,)if json_block:cleaned = (cleaned[: json_block.start()] + cleaned[json_block.end() :]).strip()if not cleaned:return ""fa_call = re.search(r"final_answer\(\s*(?:answer\s*=\s*)?(['\"])(.*?)\1\s*\)",3 unmodified linesif fa_call:cleaned = fa_call.group(2).strip()lines = [ln.strip(" \t\r\n-*•\"'") for ln in cleaned.splitlines() if ln.strip()]if not lines:return ""cleaned = lines[-1]if re.match(r"^(?: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|now i need to find|i found the)\b",cleaned,flags=re.IGNORECASE,):64 unmodified linesand not tr_preview.startswith(("Error ", "Audio file not found"))):prompt += (f"\n\nTask ID: {task_id}. Audio file '{prefetched_path}' transcription:\n"f"{tr_preview.strip()[:8000]}")tool_hint = ""except Exception as tr_exc:94 unmodified linesbuilt_model.timeout = call_timeoutbuilt_model.deadline = deadlinerun_agent = self._create_code_agent(built_model)run_agent.max_steps = 3 if rem_now > 25.0 else 2result = run_agent.run(prompt)print(f"[TRACE] task_id={task_id} model={model_name} "9 unmodified lineslast_step = getattr(getattr(run_agent, "memory", None), "steps", None)if last_step:for st in reversed(last_step):for attr in ("action_output", "model_output", "observations"):cand_val = getattr(st, attr, 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:")and "\n" not in fallback_cleanand len(fallback_clean) <= 220):return fallback_cleanreturn "AGENT ERROR: All candidate models failed."blocked_models.add(model_name)breakexcept Exception as exc:llm_err = getattr(built_model, "_last_llm_error", None)if llm_err is not None and llm_err is not exc:807 unmodified lines808809810811812813814815816817818819201 unmodified lines102110221023102410251026199 unmodified lines12261227122812291230123112321277 unmodified lines251025112512251325142515251625172518251925202521252225233 unmodified lines252725282529253025312532253325342535253625372538253925402541254225432544254525462547254864 unmodified lines2613261426152616261726182619262094 unmodified lines27152716271727182719272027219 unmodified lines273127322733273427352736273727382739274027412742274327442745274627472748807 unmodified linesreturn "No results."def _litellm_route_kwargs(model_name: str, api_key: str) -> dict:route = {"model": model_name, "api_key": api_key}if model_name.startswith("huggingface/"):raw_hf = model_name[len("huggingface/") :]route["model"] = f"openai/{raw_hf}"route["api_base"] = "https://router.huggingface.co/v1"return routedef _is_daily_quota_exhausted(err_lower: str) -> bool:return any(201 unmodified linescontinueif _is_daily_quota_exhausted(err_low):rate_limited_providers.add(v_provider)breakbreak199 unmodified linestranscript = " ".join(c for c in cues if c)if transcript:lang = tr.get("languageCode", "unknown")sections.append(f"Transcript ({lang}):\n{transcript[:5000]}")has_transcript = Truebreakexcept Exception as tr_exc:1277 unmodified linesif code_match:cleaned = code_match.group(1).strip()cleaned = re.sub(r'\{\s*["\']tool["\']\s*:\s*["\'][^"\']+["\']\s*,\s*["\']arguments["\']\s*:\s*\{.*?\}\s*\}',"",cleaned,flags=re.DOTALL,).strip()cleaned = re.sub(r"(?im)^\s*(?:#\s*)?(?:thought|reasoning|plan)\s*:.*$", "", cleaned).strip()fa_call = re.search(r"final_answer\(\s*(?:answer\s*=\s*)?(['\"])(.*?)\1\s*\)",3 unmodified linesif fa_call:cleaned = fa_call.group(2).strip()if "->" in cleaned:tail_part = cleaned.split("->")[-1].strip()quoted_match = re.findall(r'""([^"]+)""|"([^"]+)"', tail_part)if quoted_match:last_q = quoted_match[-1]cleaned = (last_q[0] or last_q[1]).strip()else:cleaned = tail_part.strip(" .\"'")lines = [ln.strip(" \t\r\n-*•\"'") for ln in cleaned.splitlines() if ln.strip()]if not lines:return ""cleaned = lines[-1]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,):64 unmodified linesand not tr_preview.startswith(("Error ", "Audio 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 tr_exc:94 unmodified linesbuilt_model.timeout = call_timeoutbuilt_model.deadline = deadlinerun_agent = self._create_code_agent(built_model)run_agent.max_steps = 4 if rem_now > 40.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} "9 unmodified lineslast_step = getattr(getattr(run_agent, "memory", None), "steps", None)if last_step:for st in reversed(last_step):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"))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:
app.py+37-33