Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files470 unmodified lines4714724734744754764774 unmodified lines48248348448548648748848949049149220 unmodified lines5135145155165175185196 unmodified lines5265275285295305315325335345355365375385395405415425435443 unmodified lines548549550551552553384 unmodified lines93893994094194294334 unmodified lines9789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210238 unmodified lines103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105651 unmodified lines11081109111011111112111311141115111611171118111911201121112211231124112511 unmodified lines11371138113911401141114211433 unmodified lines114711481149115011511152115341 unmodified lines119511961197119811991200150 unmodified lines13511352135313541355135684 unmodified lines14411442144314441445144614471448144914501451145214531454145514561457145826 unmodified lines14851486148714881489149023 unmodified lines15141515151615171518151915201521152215231524152515261527152815291530544 unmodified lines207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921309 unmodified lines21402141214221432144214521461 unmodified line21482149215021512152215320 unmodified lines2174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219637 unmodified lines223422352236223722382239224051 unmodified lines2292229322942295229622972298229923002301230252 unmodified lines23552356235723582359236023611 unmodified line2363236423652366236723682369470 unmodified linesreturn _read_single(file_path, max_chars=48000)except Exception as e:return f"Error reading file '{file_path}': {str(e)}"@tooldef web_search(query: str) -> str:4 unmodified linesfrom concurrent.futures import ThreadPoolExecutorimport refrom html import unescapeclean_q = (query or "").strip()if not clean_q:return "Empty search query."results_out = []try:ddgs_timeout = _tool_timeout(8.0, min_timeout=3.0)20 unmodified linesif not isinstance(item, dict):continuetitle = str(item.get("title", "")).strip()href = str(item.get("href", "")).strip()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 linesresp = requests.post("https://html.duckduckgo.com/html/",data={"q": clean_q},headers={"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36"},timeout=_tool_timeout(8.0, min_timeout=3.0),)resp.raise_for_status()links = re.findall(r'(?is)<a[^>]+class="result__a"[^>]+href="([^"]+)"[^>]*>(.*?)</a>',resp.text,)snippets = re.findall(r'(?is)<a[^>]+class="result__snippet"[^>]*>(.*?)</a>',resp.text,)for idx, (href, raw_title) in enumerate(links[:5]):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 linesif "task time budget exhausted" in str(html_exc).lower():return f"Web search aborted: {html_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 linesimport refrom html import unescapetry:raw = (url or "").strip()vid_match = re.search(34 unmodified linesif "task time budget exhausted" in str(req_exc).lower():raisetry: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",}},"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 = Trueif v_details.get("shortDescription"):sections.append(f"Description:\n{str(v_details['shortDescription'])[:2000]}")has_desc = Truetracks = ((player_data.get("captions") or {}).get("playerCaptionsTracklistRenderer", {}).get("captionTracks"))if isinstance(tracks, list):caption_tracks = tracksexcept Exception as req_exc:if "task time budget exhausted" in str(req_exc).lower():raiseif not has_desc or not caption_tracks:try:8 unmodified linesdesc_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")except Exception:desc_val = unescape(desc_match.group(1))sections.append(f"Description:\n{desc_val[:2000]}")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))except Exception as e:if "task time budget exhausted" in str(e).lower():raisesections.append(f"Page fetch note: {e}")if caption_tracks:sorted_tracks = sorted(caption_tracks,key=lambda t: 0 if str(t.get("languageCode", "")).lower().startswith("en") else 1,)for tr in sorted_tracks[:2]:base_url = tr.get("baseUrl")if not base_url:continue51 unmodified linesmarker in (question or "").lower() for marker in visual_markers)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",]))[:2]video_analyzed = Falsewhile not video_analyzed:rate_limited_gemini = Falsefor g_model in gemini_models:11 unmodified lines"contents": [{"parts": [{"file_data": {"mime_type": "video/mp4", "file_uri": watch_url}},{"text": question},]}3 unmodified lines"thinkingConfig": {"thinkingBudget": 0},},},timeout=_tool_timeout(28.0, min_timeout=3.0),)if gm_resp.status_code == 200:candidates = gm_resp.json().get("candidates") or []41 unmodified linescontinuebreakreturn _trim_tool_output("\n\n".join(sections), max_chars=12000)except Exception as e:return f"Error inspecting YouTube '{url}': {str(e)}"150 unmodified linesexcept Exception as e:return f"Error transcribing audio '{audio_path}': {str(e)}"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 "preview" in name.lower() else 0,name,),)self.gemini_flash_models = (discovered_flash or sorted(available_api_models))[:3]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",]candidate_models.extend(self.gemini_flash_models)26 unmodified linesexcept Exception as groq_exc:print(f"Warning: could not list Groq models: {groq_exc}")if live_groq:live_groq.sort(key=lambda name: (23 unmodified lineskey_missing = 0 if self._get_api_key(model_name) else 1if 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)ver_match = re.search(r"gemini-(\d+)(?:\.(\d+))?", low)major = int(ver_match.group(1)) if ver_match else 0minor = int(ver_match.group(2)) if (ver_match and ver_match.group(2)) else 0is_preview = 1 if "preview" in low else 0return (key_missing, 0, 3 + is_preview, (-major, -minor), model_name)if provider == "groq":sub_rank = 0 if ("70b" in low or "120b" in low) else 1544 unmodified linesraise RuntimeError("BasicAgent.__init__ failed to bind _build_model or self.agent.")print("CodeAgent initialized with LiteLLMModel.")@staticmethoddef _clean_exact_match_answer(raw_answer) -> str:import reif raw_answer 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()if not text or text.startswith("AGENT ERROR:"):return texttext = 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]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 len(text) > 1 and text.endswith(".") and not re.search(r"(?:\d|\b[A-Za-z]\.[A-Za-z])\.$", text):text = text[:-1].strip()return textdef __call__(self, question: str, task_id: str = "", file_name: str = "") -> str:import time9 unmodified linesif hasattr(self, "_reset_key_indices"):self._reset_key_indices()deadline = time.monotonic() + 75.0self._local_state.deadline = deadlineself._task_deadline = deadline1 unmodified lineprompt = question.strip()self._prefer_2022_wiki = "2022" in prompt.lower()clean_file_name = (file_name or "").strip()if task_id:prefetched_path = ""20 unmodified linesif 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."elif ext in {".png", ".jpg", ".jpeg", ".webp", ".gif"}:tool_hint = 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}."blocked_models = set(self._dead_models)blocked_providers = set()37 unmodified linesrem_now = deadline - time.monotonic()if rem_now <= 6.0:breakcall_timeout = max(10.0, min(25.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):continuecooldown_until = time.monotonic() + 30.0for m in models_to_try:if m.startswith(f"{provider}/"):rate_limited_models.add(m)self._model_cooldowns[m] = cooldown_untilrate_limited_models.add(model_name)self._model_cooldowns[model_name] = cooldown_untilrate_limited_providers.add(provider)52 unmodified linesrotated_any = Trueif not rotated_any:rem_after_pass = deadline - time.monotonic()if rate_limited_models and backoff_rounds < 1 and rem_after_pass > 20.0:backoff_rounds += 1for prov in rate_limited_providers:if prov not in blocked_providers:1 unmodified lineself._provider_key_idx[prov] = 0if 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)))continuebreakfinally:470 unmodified lines4714724734744754764774784 unmodified lines48348448548648748848949049149249349449549649749849950050150250350450520 unmodified lines5265275285295305315326 unmodified lines5395405415425435445455465475485495505515525535545555565575585595605615623 unmodified lines566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603384 unmodified lines98898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102634 unmodified lines106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111228 unmodified lines113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115851 unmodified lines12101211121212131214121512161217121812191220122112221223122412251226122711 unmodified lines12391240124112421243124412453 unmodified lines124912501251125212531254125541 unmodified lines129712981299130013011302130313041305130613071308150 unmodified lines1459146014611462146314641465146684 unmodified lines15511552155315541555155615571558155915601561156215631564156515661567156826 unmodified lines1595159615971598159916001601160223 unmodified lines162616271628162916301631163216331634163516361637163816391640164116421643164416451646544 unmodified lines21912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422759 unmodified lines22852286228722882289229022911 unmodified line229322942295229622972298229920 unmodified lines2320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237837 unmodified lines241624172418241924202421242251 unmodified lines247424752476247724782479248052 unmodified lines25332534253525362537253825391 unmodified line2541254225432544254525462547470 unmodified linesreturn _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@tooldef web_search(query: str) -> str:4 unmodified linesfrom concurrent.futures import ThreadPoolExecutorimport refrom html import unescapefrom urllib.parse import parse_qs, unquote, urlparseclean_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:" + hif "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 hresults_out = []try:ddgs_timeout = _tool_timeout(8.0, min_timeout=3.0)20 unmodified linesif not isinstance(item, dict):continuetitle = str(item.get("title", "")).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 linesresp = requests.post("https://html.duckduckgo.com/html/",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),)resp.raise_for_status()link_matches = re.findall(r"(?is)<a\b([^>]*\bclass=['\"][^'\"]*result__a[^'\"]*['\"][^>]*)>(.*?)</a>",resp.text,)snippets = re.findall(r"(?is)<(?:a|div)\b[^>]*\bclass=['\"][^'\"]*result__snippet[^'\"]*['\"][^>]*>(.*?)</(?:a|div)>",resp.text,)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 linesif "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 linesimport refrom html import unescapedef _extract_json_array_after(source: str, key_marker: str):idx = source.find(key_marker)if idx == -1:return Nonestart = source.find("[", idx + len(key_marker))if start == -1:return Nonedepth = 0in_str = Falseescape = Falsefor pos in range(start, len(source)):ch = source[pos]if in_str:if escape:escape = Falseelif ch == "\\":escape = Trueelif ch == '"':in_str = Falsecontinueif ch == '"':in_str = Trueelif ch == "[":depth += 1elif ch == "]":depth -= 1if depth == 0:try:return json.loads(source[start : pos + 1])except Exception:return Nonereturn Nonetry:raw = (url or "").strip()vid_match = re.search(34 unmodified linesif "task time budget exhausted" in str(req_exc).lower():raiseinnertube_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:breaktry:player_resp = requests.post("https://www.youtube.com/youtubei/v1/player",params={"prettyPrint": "false"},headers={"Content-Type": "application/json","User-Agent": client_ua,},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 = Trueif not has_desc and v_details.get("shortDescription"):sections.append(f"Description:\n{str(v_details['shortDescription'])[:2000]}")has_desc = Trueif not caption_tracks:tracks = ((player_data.get("captions") or {}).get("playerCaptionsTracklistRenderer", {}).get("captionTracks"))if isinstance(tracks, list) and tracks:caption_tracks = tracksexcept Exception as req_exc:if "task time budget exhausted" in str(req_exc).lower():raiseif not has_desc or not caption_tracks:try:8 unmodified linesdesc_match = re.search(r'"shortDescription"\s*:\s*"((?:\\.|[^"\\])*)"', html_text)if desc_match:try: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 = Trueif not caption_tracks:parsed_tracks = _extract_json_array_after(html_text, '"captionTracks"')if isinstance(parsed_tracks, list) and parsed_tracks:caption_tracks = parsed_tracksexcept Exception as e:if "task time budget exhausted" in str(e).lower():raiseif caption_tracks:sorted_tracks = sorted(caption_tracks,key=lambda t: (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[:3]:base_url = tr.get("baseUrl")if not base_url:continue51 unmodified linesmarker in (question or "").lower() for marker in visual_markers)video_analyzed = Falsegemini_pool = self.provider_key_pools.get("gemini") or []if gemini_pool and needs_video_analysis:gemini_models = list(dict.fromkeys(["gemini/gemini-2.5-flash","gemini/gemini-flash-latest",]+ (self.gemini_flash_models or [])))[:3]while not video_analyzed:rate_limited_gemini = Falsefor g_model in gemini_models:11 unmodified lines"contents": [{"parts": [{"file_data": {"file_uri": watch_url}},{"text": question},]}3 unmodified lines"thinkingConfig": {"thinkingBudget": 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 linescontinuebreakif 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 linesexcept Exception as e:return f"Error transcribing audio '{audio_path}': {str(e)}"self._transcribe_audio = transcribe_audiocandidate_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,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))[:4]candidate_models.extend(self.gemini_flash_models)else:self.gemini_flash_models = ["gemini/gemini-flash-latest","gemini/gemini-2.5-flash","gemini/gemini-flash-lite-latest",]candidate_models.extend(self.gemini_flash_models)26 unmodified linesexcept Exception as groq_exc:print(f"Warning: could not list Groq models: {groq_exc}")self._transcribe_audio = transcribe_audioif live_groq:live_groq.sort(key=lambda name: (23 unmodified lineskey_missing = 0 if self._get_api_key(model_name) else 1if provider == "gemini":is_lite = "flash-lite" in lowis_preview = 1 if "preview" in low else 0ver_match = re.search(r"gemini-(\d+)(?:\.(\d+))?", low)major = int(ver_match.group(1)) if ver_match else 0minor = int(ver_match.group(2)) if (ver_match and ver_match.group(2)) else 0if low == "gemini/gemini-flash-latest":return (key_missing, 0, 0, (0, 0), 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 linesraise RuntimeError("BasicAgent.__init__ failed to bind _build_model or self.agent.")print("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 cleanedcleaned = re.sub(r"<think>.*?</think>", "", cleaned, flags=re.DOTALL | re.IGNORECASE).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()breakelse:cleaned = lines[-1]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 = Falseif prefix_match:cleaned = prefix_match.group(1).strip()had_prefix = Truetrailing_bold = re.search(r"\*\*([^*]+?)\*\*[.!?]?\s*$", cleaned)if trailing_bold:candidate = trailing_bold.group(1).strip()prefix_part = cleaned[: trailing_bold.start()].strip().lower()if (candidateand len(candidate) <= 120and (not prefix_partor prefix_part.startswith(("according to", "based on", "under ", "in ", "from ", "the ", "this ", "it is", "it was")))):cleaned = candidatehad_prefix = Trueif 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 cleaneddef __call__(self, question: str, task_id: str = "", file_name: str = "") -> str:import time9 unmodified linesif hasattr(self, "_reset_key_indices"):self._reset_key_indices()deadline = time.monotonic() + 95.0self._local_state.deadline = deadlineself._task_deadline = deadline1 unmodified lineprompt = 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 linesif 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=...) 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}'. "f"Call inspect_image(image_path='{prefetched_path}', question=...) immediately.")else:tool_hint = f"Call read_local_file(file_path='{prefetched_path}') immediately."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 linesrem_now = deadline - time.monotonic()if rem_now <= 6.0:breakcall_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):continuecooldown_until = time.monotonic() + 20.0rate_limited_models.add(model_name)self._model_cooldowns[model_name] = cooldown_untilrate_limited_providers.add(provider)52 unmodified linesrotated_any = Trueif not rotated_any:rem_after_pass = deadline - time.monotonic()if rate_limited_models and backoff_rounds < 2 and rem_after_pass > 18.0:backoff_rounds += 1for prov in rate_limited_providers:if prov not in blocked_providers:1 unmodified lineself._provider_key_idx[prov] = 0if hasattr(self, "_sync_provider_env"):self._sync_provider_env(prov, pool[0] if pool else "")time.sleep(min(12.0, max(3.0, rem_after_pass - 15.0)))continuebreakfinally:
app.py+313-135