Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files470 unmodified lines4714724734744744754764774784 unmodified lines48348448548648748848949049149249349449549649749849950050150250350450520 unmodified lines5265275285165295305315326 unmodified lines5395405415295425435445455465475485335345495505515525535385545555565415575585595605615623 unmodified lines566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603384 unmodified lines98898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102634 unmodified lines10611062106398198298398498598698798898999099199299399499599610641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086998999100010011002100310041005100610071008100910101011101210131014108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111410161017101810191020111511161117111811191120112111228 unmodified lines1131113211331035113411351136113711381139104010411042114011411142114311441145104611461147114811491150105111511152115311541053115511561157115851 unmodified lines121012111212121312141215121612171115111612181219122012211222122311211122122412251226122711 unmodified lines123912401241114012421243124412453 unmodified lines1249125012511150125212531254125541 unmodified lines129712981299130013011302130313041305130613071308150 unmodified lines1459146014611462146314641465146684 unmodified lines15511552155314441554155515561557155814491559156015611562156314541564156515661567156826 unmodified lines1595159615971598159916001601160223 unmodified lines16261627162815171518151915201521152216291630163116321633163416351636152615271637163816391640164116421643164416451646544 unmodified lines219121922193207820792194219521962082219721982084208520862087208820892090209120922093209420952096209721992200220122022099210021012102210321042105210621072108210921102111211222032204211421152116211721182119212021212122220522062207220822092210221122122213221422152216221722182219222022212222222322242225212421252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271212722722273227422759 unmodified lines228522862287214322882289229022911 unmodified line229322942295229622972298229920 unmodified lines232023212322217723232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502179235123522353235421822183218421852186218721882189219021912192219323552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237837 unmodified lines2416241724182237241924202421242251 unmodified lines24742475247622952296229722982299247724782479248052 unmodified lines253325342535235825362537253825391 unmodified line25412542254323662544254525462547470 unmodified lines return _read_single(file_path, max_chars=48000) except Exception as e: return f"Error reading file '{file_path}': {str(e)}"
self._read_local_file = read_local_file
@tool def web_search(query: str) -> str:4 unmodified lines from concurrent.futures import ThreadPoolExecutor import re from html import unescape from urllib.parse import parse_qs, unquote, urlparse
clean_q = (query or "").strip() if not clean_q: return "Empty search query."
def _clean_ddg_href(raw_href: str) -> str: h = unescape((raw_href or "").strip()) if h.startswith("//"): h = "https:" + h if "duckduckgo.com/l/?" in h or h.startswith("/l/?"): parsed = urlparse(h) uddg = parse_qs(parsed.query).get("uddg") if uddg and uddg[0]: return unquote(uddg[0]) return h
results_out = [] try: ddgs_timeout = _tool_timeout(8.0, min_timeout=3.0)20 unmodified lines if not isinstance(item, dict): continue title = str(item.get("title", "")).strip() href = str(item.get("href", "")).strip() href = _clean_ddg_href(str(item.get("href", ""))) body = str(item.get("body", "")).strip() if title or href or body: results_out.append(f"- {title}\n URL: {href}\n Snippet: {body}")6 unmodified lines resp = requests.post( "https://html.duckduckgo.com/html/", data={"q": clean_q}, headers={"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36"}, headers={ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36", "Accept-Language": "en-US,en;q=0.9", }, timeout=_tool_timeout(8.0, min_timeout=3.0), ) resp.raise_for_status() links = re.findall( r'(?is)<a[^>]+class="result__a"[^>]+href="([^"]+)"[^>]*>(.*?)</a>', link_matches = re.findall( r"(?is)<a\b([^>]*\bclass=['\"][^'\"]*result__a[^'\"]*['\"][^>]*)>(.*?)</a>", resp.text, ) snippets = re.findall( r'(?is)<a[^>]+class="result__snippet"[^>]*>(.*?)</a>', r"(?is)<(?:a|div)\b[^>]*\bclass=['\"][^'\"]*result__snippet[^'\"]*['\"][^>]*>(.*?)</(?:a|div)>", resp.text, ) for idx, (href, raw_title) in enumerate(links[:5]): for idx, (tag_attrs, raw_title) in enumerate(link_matches[:5]): href_m = re.search(r"\bhref=['\"]([^'\"]+)['\"]", tag_attrs, flags=re.IGNORECASE) href = _clean_ddg_href(href_m.group(1)) if href_m else "" title = re.sub(r"\s+", " ", unescape(re.sub(r"(?s)<[^>]+>", " ", raw_title))).strip() raw_snip = snippets[idx] if idx < len(snippets) else "" snip = re.sub(r"\s+", " ", unescape(re.sub(r"(?s)<[^>]+>", " ", raw_snip))).strip()3 unmodified lines if "task time budget exhausted" in str(html_exc).lower(): return f"Web search aborted: {html_exc}"
if not results_out: try: lite_resp = requests.post( "https://lite.duckduckgo.com/lite/", data={"q": clean_q}, headers={ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36", "Accept-Language": "en-US,en;q=0.9", }, timeout=_tool_timeout(8.0, min_timeout=3.0), ) lite_resp.raise_for_status() lite_links = re.findall( r"(?is)<a\b([^>]*\bclass=['\"][^'\"]*result-link[^'\"]*['\"][^>]*)>(.*?)</a>", lite_resp.text, ) lite_snippets = re.findall( r"(?is)<td\b[^>]*\bclass=['\"][^'\"]*result-snippet[^'\"]*['\"][^>]*>(.*?)</td>", lite_resp.text, ) for idx, (tag_attrs, raw_title) in enumerate(lite_links[:5]): href_m = re.search(r"\bhref=['\"]([^'\"]+)['\"]", tag_attrs, flags=re.IGNORECASE) href = _clean_ddg_href(href_m.group(1)) if href_m else "" title = re.sub(r"\s+", " ", unescape(re.sub(r"(?s)<[^>]+>", " ", raw_title))).strip() raw_snip = lite_snippets[idx] if idx < len(lite_snippets) else "" snip = re.sub(r"\s+", " ", unescape(re.sub(r"(?s)<[^>]+>", " ", raw_snip))).strip() if title or href or snip: results_out.append(f"- {title}\n URL: {href}\n Snippet: {snip}") except Exception as lite_exc: if "task time budget exhausted" in str(lite_exc).lower(): return f"Web search aborted: {lite_exc}"
if not results_out: return f"No web results found for '{clean_q}'. Try search_wikipedia(query) or fetch_url_text(url)." return "\n\n".join(results_out)384 unmodified lines import re from html import unescape
def _extract_json_array_after(source: str, key_marker: str): idx = source.find(key_marker) if idx == -1: return None start = source.find("[", idx + len(key_marker)) if start == -1: return None depth = 0 in_str = False escape = False for pos in range(start, len(source)): ch = source[pos] if in_str: if escape: escape = False elif ch == "\\": escape = True elif ch == '"': in_str = False continue if ch == '"': in_str = True elif ch == "[": depth += 1 elif ch == "]": depth -= 1 if depth == 0: try: return json.loads(source[start : pos + 1]) except Exception: return None return None
try: raw = (url or "").strip() vid_match = re.search(34 unmodified lines if "task time budget exhausted" in str(req_exc).lower(): raise
try: player_resp = requests.post( "https://www.youtube.com/youtubei/v1/player", params={"prettyPrint": "false"}, headers={ "Content-Type": "application/json", "User-Agent": "com.google.android.youtube/19.09.37 (Linux; U; Android 11) gzip", }, json={ "context": { "client": { "clientName": "ANDROID", "clientVersion": "19.09.37", "hl": "en", "gl": "US", } innertube_clients = [ ( "ANDROID", "19.09.37", "com.google.android.youtube/19.09.37 (Linux; U; Android 11) gzip", ), ( "IOS", "19.29.1", "com.google.ios.youtube/19.29.1 (iPhone16,2; U; CPU iOS 17_5_1 like Mac OS X;)", ), ] for client_name, client_ver, client_ua in innertube_clients: if has_desc and caption_tracks: break try: player_resp = requests.post( "https://www.youtube.com/youtubei/v1/player", params={"prettyPrint": "false"}, headers={ "Content-Type": "application/json", "User-Agent": client_ua, }, "videoId": video_id, }, timeout=_tool_timeout(10.0, min_timeout=2.0), ) if player_resp.status_code == 200: player_data = player_resp.json() v_details = player_data.get("videoDetails") or {} if not has_title and v_details.get("title"): sections.append(f"Title: {v_details['title']}") has_title = True if v_details.get("shortDescription"): sections.append(f"Description:\n{str(v_details['shortDescription'])[:2000]}") has_desc = True tracks = ( (player_data.get("captions") or {}) .get("playerCaptionsTracklistRenderer", {}) .get("captionTracks") json={ "context": { "client": { "clientName": client_name, "clientVersion": client_ver, "hl": "en", "gl": "US", } }, "videoId": video_id, }, timeout=_tool_timeout(8.0, min_timeout=2.0), ) if player_resp.status_code == 200: player_data = player_resp.json() v_details = player_data.get("videoDetails") or {} if not has_title and v_details.get("title"): sections.append(f"Title: {v_details['title']}") has_title = True if not has_desc and v_details.get("shortDescription"): sections.append(f"Description:\n{str(v_details['shortDescription'])[:2000]}") has_desc = True if not caption_tracks: tracks = ( (player_data.get("captions") or {}) .get("playerCaptionsTracklistRenderer", {}) .get("captionTracks") ) if isinstance(tracks, list): caption_tracks = tracks except Exception as req_exc: if "task time budget exhausted" in str(req_exc).lower(): raise if isinstance(tracks, list) and tracks: caption_tracks = tracks except Exception as req_exc: if "task time budget exhausted" in str(req_exc).lower(): raise
if not has_desc or not caption_tracks: try:8 unmodified lines desc_match = re.search(r'"shortDescription"\s*:\s*"((?:\\.|[^"\\])*)"', html_text) if desc_match: try: desc_val = desc_match.group(1).encode("utf-8").decode("unicode_escape") desc_val = json.loads(f'"{desc_match.group(1)}"') except Exception: desc_val = unescape(desc_match.group(1)) sections.append(f"Description:\n{desc_val[:2000]}") has_desc = True if not caption_tracks: cap_match = re.search(r'"captionTracks"\s*:\s*(\[[^\]]*\])', html_text) if cap_match: caption_tracks = json.loads(cap_match.group(1)) parsed_tracks = _extract_json_array_after(html_text, '"captionTracks"') if isinstance(parsed_tracks, list) and parsed_tracks: caption_tracks = parsed_tracks except Exception as e: if "task time budget exhausted" in str(e).lower(): raise sections.append(f"Page fetch note: {e}")
if caption_tracks: sorted_tracks = sorted( caption_tracks, key=lambda t: ( key=lambda t: 0 if str(t.get("languageCode", "")).lower().startswith("en") else 1, 0 if str(t.get("languageCode", "")).lower().startswith("en") else 1, 1 if str(t.get("kind", "")).lower() == "asr" else 0, ), ) for tr in sorted_tracks[:2]: for tr in sorted_tracks[:3]: base_url = tr.get("baseUrl") if not base_url: continue51 unmodified lines marker in (question or "").lower() for marker in visual_markers )
video_analyzed = False gemini_pool = self.provider_key_pools.get("gemini") or [] if gemini_pool and needs_video_analysis: gemini_models = list( dict.fromkeys( (self.gemini_flash_models or []) + [ [ "gemini/gemini-2.5-flash", "gemini/gemini-flash-latest", ] + (self.gemini_flash_models or []) ) )[:2] video_analyzed = False )[:3] while not video_analyzed: rate_limited_gemini = False for g_model in gemini_models:11 unmodified lines "contents": [ { "parts": [ {"file_data": {"mime_type": "video/mp4", "file_uri": watch_url}}, {"file_data": {"file_uri": watch_url}}, {"text": question}, ] }3 unmodified lines "thinkingConfig": {"thinkingBudget": 0}, }, }, timeout=_tool_timeout(28.0, min_timeout=3.0), timeout=_tool_timeout(32.0, min_timeout=4.0), ) if gm_resp.status_code == 200: candidates = gm_resp.json().get("candidates") or []41 unmodified lines continue break
if not has_transcript and not video_analyzed: sections.append( "Transcript/Video Analysis Status: unavailable. " "Use web_search or search_wikipedia with the video title, channel, or quoted dialogue." )
return _trim_tool_output("\n\n".join(sections), max_chars=12000) except Exception as e: return f"Error inspecting YouTube '{url}': {str(e)}"150 unmodified lines except Exception as e: return f"Error transcribing audio '{audio_path}': {str(e)}"
self._transcribe_audio = transcribe_audio
candidate_models = [] priority_openrouter_models = [ "openrouter/google/gemma-4-31b-it:free",84 unmodified lines (m for m in available_api_models if "flash" in m.lower()), key=lambda name: ( 0 if name.lower() == "gemini/gemini-flash-latest" else 1, 0 if name.lower() == "gemini/gemini-flash-lite-latest" else 1, 1 if "flash-lite" in name.lower() else 0, 1 if "preview" in name.lower() else 0, name, ), ) self.gemini_flash_models = (discovered_flash or sorted(available_api_models))[:3] self.gemini_flash_models = (discovered_flash or sorted(available_api_models))[:4] candidate_models.extend(self.gemini_flash_models) else: self.gemini_flash_models = [ "gemini/gemini-flash-latest", "gemini/gemini-flash-lite-latest", "gemini/gemini-2.5-flash", "gemini/gemini-flash-lite-latest", ] candidate_models.extend(self.gemini_flash_models)
26 unmodified lines except Exception as groq_exc: print(f"Warning: could not list Groq models: {groq_exc}")
self._transcribe_audio = transcribe_audio if live_groq: live_groq.sort( key=lambda name: (23 unmodified lines key_missing = 0 if self._get_api_key(model_name) else 1
if provider == "gemini": if low == "gemini/gemini-flash-lite-latest": return (key_missing, 0, 0, (0, 0), model_name) if "flash-lite" in low: return (key_missing, 0, 1, (0, 0), model_name) if low == "gemini/gemini-flash-latest": return (key_missing, 0, 2, (0, 0), model_name) is_lite = "flash-lite" in low is_preview = 1 if "preview" in low else 0 ver_match = re.search(r"gemini-(\d+)(?:\.(\d+))?", low) major = int(ver_match.group(1)) if ver_match else 0 minor = int(ver_match.group(2)) if (ver_match and ver_match.group(2)) else 0
if low == "gemini/gemini-flash-latest": return (key_missing, 0, 0, (0, 0), model_name) is_preview = 1 if "preview" in low else 0 return (key_missing, 0, 3 + is_preview, (-major, -minor), model_name) if not is_lite and "flash" in low: return (key_missing, 0, 1 + is_preview, (-major, -minor), model_name) if low == "gemini/gemini-flash-lite-latest": return (key_missing, 0, 3, (0, 0), model_name) if is_lite: return (key_missing, 0, 4 + is_preview, (-major, -minor), model_name) return (key_missing, 0, 6 + is_preview, (-major, -minor), model_name)
if provider == "groq": sub_rank = 0 if ("70b" in low or "120b" in low) else 1544 unmodified lines raise RuntimeError("BasicAgent.__init__ failed to bind _build_model or self.agent.") print("CodeAgent initialized with LiteLLMModel.")
@staticmethod def _clean_exact_match_answer(raw_answer) -> str: def _clean_exact_match_answer(self, text: str) -> str: import re
if raw_answer is None: if text is None: return "" if isinstance(raw_answer, dict): extracted_val = next( ( raw_answer[k] for k in ("final_answer", "answer", "result", "value") if k in raw_answer and raw_answer[k] is not None ), next(iter(raw_answer.values()), "") if len(raw_answer) == 1 else raw_answer, ) text = str(extracted_val).strip() elif isinstance(raw_answer, (list, tuple)): text = ", ".join(str(item).strip() for item in raw_answer if str(item).strip()) else: text = str(raw_answer).strip() cleaned = str(text).strip() if not cleaned or cleaned.startswith("AGENT ERROR:"): return cleaned
if not text or text.startswith("AGENT ERROR:"): return text
text = re.sub(r"</?code[^>]*>", "", text, flags=re.IGNORECASE).strip() text = re.sub(r"^```(?:[a-zA-Z0-9_-]+)?\s*\n?", "", text) text = re.sub(r"\n?```\s*$", "", text).strip()
fa_matches = re.findall(r"(?im)^\s*(?:final\s*answer|answer)\s*:\s*(.+)$", text) if fa_matches: text = fa_matches[-1].strip() else: lines = [line.strip() for line in text.splitlines() if line.strip()] if lines: text = lines[-1] cleaned = re.sub(r"<think>.*?</think>", "", cleaned, flags=re.DOTALL | re.IGNORECASE).strip()
text = re.sub(r"</?code[^>]*>", "", text, flags=re.IGNORECASE).strip() text = re.sub(r"^\*\*(.+?)\*\*$", r"\1", text).strip()
fa_call = re.fullmatch(r"final_answer\(\s*(?:answer\s*=\s*)?(.*?)\s*\)", text, flags=re.DOTALL) if fa_call: text = fa_call.group(1).strip() if len(text) >= 2 and ((text[0] == '"' and text[-1] == '"') or (text[0] == "'" and text[-1] == "'")): text = text[1:-1].strip() if cleaned.startswith("```") and cleaned.endswith("```"): lines = cleaned.splitlines() if len(lines) >= 3: cleaned = "\n".join(lines[1:-1]).strip() else: cleaned = cleaned.strip("`").strip()
lines = [ln.strip() for ln in cleaned.splitlines() if ln.strip()] if len(lines) > 1: for ln in reversed(lines): m_final = re.match( r"^(?:\*\*)?(?:final\s+answer|answer|result|output)(?:\*\*)?\s*:\s*(.+)$", ln, flags=re.IGNORECASE, ) if m_final: cleaned = m_final.group(1).strip() break else: cleaned = lines[-1]
if len(text) > 1 and text.endswith(".") and not re.search(r"(?:\d|\b[A-Za-z]\.[A-Za-z])\.$", text): text = text[:-1].strip() prefix_match = re.match( r"^(?:\*\*)?(?:final\s+answer|the\s+final\s+answer\s+is|the\s+answer\s+is|answer|result|output)(?:\*\*)?\s*:?\s+(.+)$", cleaned, flags=re.IGNORECASE, ) had_prefix = False if prefix_match: cleaned = prefix_match.group(1).strip() had_prefix = True
trailing_bold = re.search(r"\*\*([^*]+?)\*\*[.!?]?\s*$", cleaned) if trailing_bold: candidate = trailing_bold.group(1).strip() prefix_part = cleaned[: trailing_bold.start()].strip().lower() if ( candidate and len(candidate) <= 120 and ( not prefix_part or prefix_part.startswith( ("according to", "based on", "under ", "in ", "from ", "the ", "this ", "it is", "it was") ) ) ): cleaned = candidate had_prefix = True
if len(cleaned) >= 2 and ( (cleaned.startswith("**") and cleaned.endswith("**")) or (cleaned.startswith("__") and cleaned.endswith("__")) or (cleaned.startswith("`") and cleaned.endswith("`")) or (cleaned.startswith('"') and cleaned.endswith('"')) or (cleaned.startswith("'") and cleaned.endswith("'")) ): cleaned = cleaned[2:-2].strip() if cleaned.startswith(("**", "__")) else cleaned[1:-1].strip()
if had_prefix and cleaned.endswith(".") and not re.search(r"\b(?:Mr|Mrs|Ms|Dr|St|Jr|Sr|Inc|Ltd|vs|etc)\.$", cleaned): cleaned = cleaned[:-1].strip()
if re.match( r"^(?:title|channel|transcript|description|duration|views|url|source|file\s*path|status|error|no\s+transcript)\s*:", cleaned, flags=re.IGNORECASE, ): return ""
return text return cleaned
def __call__(self, question: str, task_id: str = "", file_name: str = "") -> str: import time9 unmodified lines if hasattr(self, "_reset_key_indices"): self._reset_key_indices()
deadline = time.monotonic() + 75.0 deadline = time.monotonic() + 95.0 self._local_state.deadline = deadline self._task_deadline = deadline
1 unmodified line prompt = question.strip() self._prefer_2022_wiki = "2022" in prompt.lower() clean_file_name = (file_name or "").strip() tools_map = getattr(getattr(self, "agent", None), "tools", {}) or {}
if task_id: prefetched_path = ""20 unmodified lines if prefetched_path: ext = os.path.splitext(prefetched_path)[1].lower() if ext in {".mp3", ".wav", ".m4a", ".ogg", ".flac"}: tool_hint = f"Call transcribe_audio(audio_path='{prefetched_path}', question=...) immediately." tool_hint = f"Call transcribe_audio(audio_path='{prefetched_path}', question=...) if more detail is needed." transcribe_fn = getattr(self, "_transcribe_audio", None) or tools_map.get("transcribe_audio") if transcribe_fn is not None: try: tr_preview = transcribe_fn( audio_path=prefetched_path, question=question.strip(), ) if ( isinstance(tr_preview, str) and tr_preview.strip() and 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: print(f"[PRE-TRANSCRIBE WARN] task_id={task_id}: {tr_exc}", flush=True) if tool_hint: prompt += ( f"\n\nTask ID: {task_id}. The task attachment is downloaded at '{prefetched_path}'. " f"{tool_hint}" ) elif ext in {".png", ".jpg", ".jpeg", ".webp", ".gif"}: prompt += ( f"\n\nTask ID: {task_id}. The task attachment is downloaded at '{prefetched_path}'. " tool_hint = f"Call inspect_image(image_path='{prefetched_path}', question=...) immediately." f"Call inspect_image(image_path='{prefetched_path}', question=...) immediately." ) else: tool_hint = f"Call read_local_file(file_path='{prefetched_path}') immediately." prompt += ( f"\n\nTask ID: {task_id}. The task attachment is downloaded at '{prefetched_path}'. " f"{tool_hint}" ) elif clean_file_name: prompt += ( f"\n\nTask ID: {task_id}. Expected attachment filename: '{clean_file_name}'. " f"First call download_task_file(task_id='{task_id}', preferred_filename='{clean_file_name}') " f"and inspect the downloaded file." ) else: prompt += f"\n\nTask ID: {task_id}." read_fn = getattr(self, "_read_local_file", None) or tools_map.get("read_local_file") if read_fn is not None: try: file_preview = read_fn(file_path=prefetched_path) if ( isinstance(file_preview, str) and file_preview.strip() and not file_preview.startswith(("Error ", "File not found")) ): prompt += ( f"\n\nTask ID: {task_id}. Attachment '{prefetched_path}' content:\n" f"{file_preview.strip()[:12000]}" ) tool_hint = "" except Exception as rd_exc: print(f"[PRE-READ WARN] task_id={task_id}: {rd_exc}", flush=True) if tool_hint: prompt += ( f"\n\nTask ID: {task_id}. The task attachment is downloaded at '{prefetched_path}'. " f"{tool_hint}" )
blocked_models = set(self._dead_models) blocked_providers = set()37 unmodified lines rem_now = deadline - time.monotonic() if rem_now <= 6.0: break call_timeout = max(10.0, min(25.0, rem_now - 3.0)) call_timeout = max(12.0, min(30.0, rem_now - 3.0)) built_model = self._build_model(model_name) built_model.model_id = getattr(built_model, "model_id", model_name) built_model.timeout = call_timeout51 unmodified lines ): if hasattr(self, "_rotate_api_key") and self._rotate_api_key(provider): continue cooldown_until = time.monotonic() + 30.0 for m in models_to_try: if m.startswith(f"{provider}/"): rate_limited_models.add(m) self._model_cooldowns[m] = cooldown_until cooldown_until = time.monotonic() + 20.0 rate_limited_models.add(model_name) self._model_cooldowns[model_name] = cooldown_until rate_limited_providers.add(provider)52 unmodified lines rotated_any = True if not rotated_any: rem_after_pass = deadline - time.monotonic() if rate_limited_models and backoff_rounds < 1 and rem_after_pass > 20.0: if rate_limited_models and backoff_rounds < 2 and rem_after_pass > 18.0: backoff_rounds += 1 for prov in rate_limited_providers: if prov not in blocked_providers:1 unmodified line self._provider_key_idx[prov] = 0 if hasattr(self, "_sync_provider_env"): self._sync_provider_env(prov, pool[0] if pool else "") time.sleep(min(4.0, max(1.5, rem_after_pass - 12.0))) time.sleep(min(12.0, max(3.0, rem_after_pass - 15.0))) continue break finally:app.py+313-135