Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files103 unmodified lines104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145113 unmodified lines25926026126226326426526626726826927018 unmodified lines28929029129229329411 unmodified lines30630730830931031131231327 unmodified lines341342343344345346450 unmodified lines79779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685724 unmodified lines882883884885886887888193 unmodified lines1082108310841085108610871088108910901091109210931094179 unmodified lines12741275127612771278127912801281128212831284172 unmodified lines14571458145914601461146214631464146514661467146814691470147114721473147461 unmodified lines15361537153815391540154115421543154415451546114 unmodified lines16611662166316641665166619 unmodified lines168616871688168916901691169216931694169512 unmodified lines17081709171017111712171317144 unmodified lines171917201721172217231724172517261727172815 unmodified lines17441745174617471748174917501751175217532 unmodified lines1756175717581759176017611762176317641765103 unmodified linesos.environ["HF_TOKEN"] = hf_keyos.environ["HUGGINGFACE_API_KEY"] = hf_keydef _get_api_key(model_name: str) -> str | None:provider = model_name.split("/", 1)[0].lower() if "/" in model_name else "gemini"pool = self.provider_key_pools.get(provider) or []idx = self._provider_key_idx.get(provider, 0)if idx < len(pool):key = pool[idx]self.provider_keys[provider] = keyreturn keyself.provider_keys[provider] = ""return Nonedef _rotate_api_key(provider: str) -> bool:pool = self.provider_key_pools.get(provider) or []next_idx = self._provider_key_idx.get(provider, 0) + 1self._provider_key_idx[provider] = next_idxif next_idx < len(pool):new_key = pool[next_idx]self.provider_keys[provider] = new_keyif provider == "openrouter":os.environ["OPENROUTER_API_KEY"] = new_keyelif provider == "groq":os.environ["GROQ_API_KEY"] = new_keyelif provider == "huggingface":os.environ["HF_TOKEN"] = new_keyos.environ["HUGGINGFACE_API_KEY"] = new_keyelif provider == "gemini":self.gemini_key = new_keyos.environ["GEMINI_API_KEY"] = new_keyos.environ["GOOGLE_API_KEY"] = new_keyreturn Trueself.provider_keys[provider] = ""return Falseself._get_api_key = _get_api_keyself._rotate_api_key = _rotate_api_keyself.gemini_flash_models = []@tooldef fetch_url_text(url: str) -> str:113 unmodified linesreturn f"Error downloading file for task '{clean_id}': {str(last_err)}"return f"No attachment available for task '{clean_id}' (404 Not Found)."@tooldef read_local_file(file_path: str) -> str:"""Reads text, PDF, ZIP archive, or spreadsheet content from a local file downloaded by download_task_file.Args:file_path: Local path to the downloaded file."""import zipfiledef _read_single(path: str, max_chars: int) -> str:18 unmodified linestext = "\n\n".join(p for p in pages if p.strip()) or "Empty PDF text."except Exception as pdf_exc:return f"Error reading PDF '{path}': {str(pdf_exc)}"elif f_ext in {".png", ".jpg", ".jpeg", ".webp", ".gif"}:return f"Binary image file '{path}'. Use inspect_image(image_path='{path}', question=...)."elif f_ext in {".mp3", ".wav", ".m4a", ".ogg", ".flac"}:11 unmodified linesif not os.path.isfile(file_path):return f"File not found: '{file_path}'"ext = os.path.splitext(file_path)[1].lower()excel_exts = {".xlsx", ".xlsm", ".xls"}if ext == ".zip" or (ext not in excel_exts and zipfile.is_zipfile(file_path)):extract_dir = os.path.join(os.path.dirname(file_path),f"extracted_{os.path.basename(file_path)}",27 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:450 unmodified linesheaders = {"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",}sections = [f"Video ID: {video_id}", f"URL: {watch_url}"]try:oembed_resp = requests.get("https://www.youtube.com/oembed",params={"url": watch_url, "format": "json"},headers=headers,timeout=20,)if oembed_resp.status_code == 200:oembed = oembed_resp.json()if oembed.get("title"):sections.append(f"Title: {oembed['title']}")if oembed.get("author_name"):sections.append(f"Channel: {oembed['author_name']}")except Exception:passtry:page_resp = requests.get(watch_url, headers=headers, timeout=25)if page_resp.status_code == 200:html_text = page_resp.textdesc_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]}")cap_match = re.search(r'"captionTracks"\s*:\s*(\[[^\]]*\])', html_text)if cap_match:try:tracks = json.loads(cap_match.group(1))for tr in tracks[:3]:base_url = tr.get("baseUrl")if not base_url:continuetr_resp = requests.get(unescape(base_url), headers=headers, timeout=20)if tr_resp.status_code == 200 and tr_resp.text:raw_cues = re.findall(r"(?is)<text[^>]*>(.*?)</text>", tr_resp.text)cues = [re.sub(r"\s+", " ", unescape(re.sub(r"(?s)<[^>]+>", " ", c))).strip()for c in raw_cues]transcript = " ".join(c for c in cues if c)if transcript:lang = tr.get("languageCode", "unknown")sections.append(f"Transcript ({lang}):\n{transcript[:8000]}")breakexcept Exception:passexcept Exception as e:sections.append(f"Page fetch note: {e}")gemini_pool = self.provider_key_pools.get("gemini") or []if gemini_pool:24 unmodified lines"contents": [{"parts": [{"file_data": {"file_uri": watch_url}},{"text": question},]}193 unmodified linescandidate_models = []priority_openrouter_models = ["openrouter/openrouter/free","openrouter/google/gemma-4-26b-a4b-it:free","openrouter/google/gemma-4-31b-it:free","openrouter/nvidia/nemotron-3-nano-30b-a3b:free","openrouter/qwen/qwen3-next-80b-a3b-instruct:free","openrouter/meta-llama/llama-3.3-70b-instruct:free","openrouter/google/gemma-3-27b-it:free",]if self.provider_keys.get("openrouter"):179 unmodified linessuper().__init__(*args, **kwargs)self._explicit_api_key = kwargs.get("api_key")self._explicit_api_base = kwargs.get("api_base")if self._explicit_api_key:self.api_key = self._explicit_api_keyif self._explicit_api_base:self.api_base = self._explicit_api_base@classmethoddef _sanitize_code_tags(cls, text: str) -> str:import ast172 unmodified linescontent_str = f"{cls.open_tag}\n" + "\n".join(rendered_calls) + f"\n{cls.close_tag}"if not content_str and reasoning_str:code_match = re.search(r"(<code>.*?</code>|```(?:py|python)?\s*\n.*?```)",reasoning_str,flags=re.DOTALL | re.IGNORECASE,)if code_match:content_str = code_match.group(1).strip()else:first_line = reasoning_str.splitlines()[0].replace('"', "'")content_str = (f'{cls.open_tag}\nprint(ask_web("{first_line[:120]}")) # fallback from reasoning\n{cls.close_tag}')if not content_str:raise RuntimeError(61 unmodified linesif hasattr(LiteLLMModel, "generate"):def generate(self, *args, **kwargs):import timet0 = time.monotonic()kwargs = self._prepare_call_kwargs(dict(kwargs))try:return self._validate_message(super().generate(*args, **kwargs))finally:print(f"[LLM] {self.model_id}: {time.monotonic() - t0:.1f}s")114 unmodified lines"- Do not wrap the answer in a dictionary like {'answer': ...}; pass the plain answer string directly.")agent_kwargs = {"model": model,"tools": [19 unmodified lines"string","re","time",],"instructions": exact_match_rule,"code_block_tags": (code_open_tag, code_close_tag),"max_steps": 10,"verbosity_level": 0,}12 unmodified linesif raw_answer is None:return ""if 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()4 unmodified linestext = re.sub(r"^```(?:[a-zA-Z0-9_-]+)?\s*\n?", "", text)text = re.sub(r"\n?```\s*$", "", text).strip()text = re.sub(r"(?im)^\s*(final\s*answer|answer)\s*:\s*", "", text).strip()lines = [line.strip() for line in text.splitlines() if line.strip()]if lines:text = lines[-1]if len(text) >= 2 and ((text[0] == '"' and text[-1] == '"') or (text[0] == "'" and text[-1] == "'")):text = text[1:-1].strip()15 unmodified linesprompt = question.strip()self._prefer_2022_wiki = "2022" in prompt.lower()if task_id:prompt += (f"\n\nTask ID: {task_id}. If the question references an attached file "f"or image, use download_task_file(task_id='{task_id}') to inspect it.")blocked_models = set()blocked_providers = set()2 unmodified linesif self.model_id and self.model_id not in models_to_try:models_to_try.append(self.model_id)deadline = time.monotonic() + 80.0prev_max_steps = getattr(self.agent, "max_steps", None)if prev_max_steps is not None:self.agent.max_steps = min(int(prev_max_steps), 4)try:backoff_rounds = 0103 unmodified lines104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160113 unmodified lines27427527627727827928028128228328428528628728828918 unmodified lines30830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036111 unmodified lines37337437537637737837938027 unmodified lines408409410411412413414450 unmodified lines86586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797824 unmodified lines1003100410051006100710081009193 unmodified lines1203120412051206120712081209121012111212121312141215179 unmodified lines1395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422172 unmodified lines159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162561 unmodified lines1687168816891690169116921693169416951696169716981699170017011702114 unmodified lines18171818181918201821182218231824182518261827182819 unmodified lines184818491850185118521853185418551856185718581859186018611862186318641865186612 unmodified lines187918801881188218831884188518861887188818891890189118921893189418954 unmodified lines19001901190219031904190519061907190819091910191119121913191415 unmodified lines19301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202 unmodified lines2023202420252026202720282029203020312032103 unmodified linesos.environ["HF_TOKEN"] = hf_keyos.environ["HUGGINGFACE_API_KEY"] = hf_keydef _sync_provider_env(provider: str, key: str) -> None:self.provider_keys[provider] = keyif not key:returnif provider == "openrouter":os.environ["OPENROUTER_API_KEY"] = keyelif provider == "groq":os.environ["GROQ_API_KEY"] = keyelif provider == "huggingface":os.environ["HF_TOKEN"] = keyos.environ["HUGGINGFACE_API_KEY"] = keyelif provider == "gemini":self.gemini_key = keyos.environ["GEMINI_API_KEY"] = keyos.environ["GOOGLE_API_KEY"] = keydef _get_api_key(model_name: str) -> str | None:provider = model_name.split("/", 1)[0].lower() if "/" in model_name else "gemini"pool = self.provider_key_pools.get(provider) or []idx = self._provider_key_idx.get(provider, 0)if idx < len(pool):key = pool[idx]_sync_provider_env(provider, key)return key_sync_provider_env(provider, "")return Nonedef _rotate_api_key(provider: str, permanent: bool = False) -> bool:pool = self.provider_key_pools.get(provider) or []cur_idx = self._provider_key_idx.get(provider, 0)if permanent and 0 <= cur_idx < len(pool):pool.pop(cur_idx)next_idx = cur_idxelse:next_idx = cur_idx + 1self._provider_key_idx[provider] = next_idxif next_idx < len(pool):_sync_provider_env(provider, pool[next_idx])return True_sync_provider_env(provider, "")return Falsedef _reset_key_indices() -> None:for prov, pool in self.provider_key_pools.items():self._provider_key_idx[prov] = 0_sync_provider_env(prov, pool[0] if pool else "")self._sync_provider_env = _sync_provider_envself._get_api_key = _get_api_keyself._rotate_api_key = _rotate_api_keyself._reset_key_indices = _reset_key_indices@tooldef fetch_url_text(url: str) -> str:113 unmodified linesreturn f"Error downloading file for task '{clean_id}': {str(last_err)}"return f"No attachment available for task '{clean_id}' (404 Not Found)."self._download_task_file = download_task_file@tooldef read_local_file(file_path: str) -> str:"""Reads text, PDF, DOCX, PPTX, ZIP archive, or spreadsheet content from a local file downloaded by download_task_file.Args:file_path: Local path to the downloaded file."""import reimport xml.etree.ElementTree as ETimport zipfiledef _read_single(path: str, max_chars: int) -> str:18 unmodified linestext = "\n\n".join(p for p in pages if p.strip()) or "Empty PDF text."except Exception as pdf_exc:return f"Error reading PDF '{path}': {str(pdf_exc)}"elif f_ext == ".docx":try:with zipfile.ZipFile(path, "r") as zf:if "word/document.xml" not in zf.namelist():return f"Invalid DOCX archive '{path}': missing word/document.xml."root = ET.fromstring(zf.read("word/document.xml"))paragraphs = []for p_elem in root.iter():if p_elem.tag.endswith("}p"):runs = [t_elem.textfor t_elem in p_elem.iter()if t_elem.tag.endswith("}t") and t_elem.text]line = "".join(runs).strip()if line:paragraphs.append(line)text = "\n".join(paragraphs) or "Empty DOCX document."except Exception as docx_exc:return f"Error reading DOCX '{path}': {str(docx_exc)}"elif f_ext == ".pptx":try:with zipfile.ZipFile(path, "r") as zf:slide_names = [name for name in zf.namelist()if re.fullmatch(r"ppt/slides/slide\d+\.xml", name)]slide_names.sort(key=lambda n: int(re.search(r"slide(\d+)\.xml$", n).group(1)))slides_out = []for idx, s_name in enumerate(slide_names, start=1):root = ET.fromstring(zf.read(s_name))s_lines = []for p_elem in root.iter():if p_elem.tag.endswith("}p"):runs = [t_elem.textfor t_elem in p_elem.iter()if t_elem.tag.endswith("}t") and t_elem.text]line = "".join(runs).strip()if line:s_lines.append(line)slides_out.append(f"=== Slide {idx} ===\n" + ("\n".join(s_lines) or "(empty)"))text = "\n\n".join(slides_out) or "Empty PPTX presentation."except Exception as pptx_exc:return f"Error reading PPTX '{path}': {str(pptx_exc)}"elif f_ext in {".png", ".jpg", ".jpeg", ".webp", ".gif"}:return f"Binary image file '{path}'. Use inspect_image(image_path='{path}', question=...)."elif f_ext in {".mp3", ".wav", ".m4a", ".ogg", ".flac"}:11 unmodified linesif not os.path.isfile(file_path):return f"File not found: '{file_path}'"ext = os.path.splitext(file_path)[1].lower()office_zip_exts = {".xlsx", ".xlsm", ".xls", ".docx", ".pptx"}if ext == ".zip" or (ext not in office_zip_exts and zipfile.is_zipfile(file_path)):extract_dir = os.path.join(os.path.dirname(file_path),f"extracted_{os.path.basename(file_path)}",27 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:450 unmodified linesheaders = {"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","Cookie": "SOCS=CAI",}sections = [f"Video ID: {video_id}", f"URL: {watch_url}"]has_title = Falsehas_desc = Falsecaption_tracks = []try:oembed_resp = requests.get("https://www.youtube.com/oembed",params={"url": watch_url, "format": "json"},headers=headers,timeout=15,)if oembed_resp.status_code == 200:oembed = oembed_resp.json()if oembed.get("title"):sections.append(f"Title: {oembed['title']}")has_title = Trueif oembed.get("author_name"):sections.append(f"Channel: {oembed['author_name']}")except Exception:passtry: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=20,)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:passif not has_desc or not caption_tracks:try:page_resp = requests.get(watch_url, headers=headers, timeout=20)if page_resp.status_code == 200:html_text = page_resp.textif not has_desc: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")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:sections.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[:3]:base_url = tr.get("baseUrl")if not base_url:continuetry:tr_resp = requests.get(unescape(base_url), headers=headers, timeout=20)if tr_resp.status_code == 200 and tr_resp.text:raw_cues = re.findall(r"(?is)<text[^>]*>(.*?)</text>", tr_resp.text)cues = [re.sub(r"\s+", " ", unescape(re.sub(r"(?s)<[^>]+>", " ", c))).strip()for c in raw_cues]transcript = " ".join(c for c in cues if c)if transcript:lang = tr.get("languageCode", "unknown")sections.append(f"Transcript ({lang}):\n{transcript[:8000]}")breakexcept Exception:continuegemini_pool = self.provider_key_pools.get("gemini") or []if gemini_pool:24 unmodified lines"contents": [{"parts": [{"file_data": {"mime_type": "video/mp4", "file_uri": watch_url}},{"text": question},]}193 unmodified linescandidate_models = []priority_openrouter_models = ["openrouter/google/gemma-4-31b-it:free","openrouter/google/gemma-4-26b-a4b-it:free","openrouter/qwen/qwen3-next-80b-a3b-instruct:free","openrouter/meta-llama/llama-3.3-70b-instruct:free","openrouter/google/gemma-3-27b-it:free","openrouter/nvidia/nemotron-3-nano-30b-a3b:free","openrouter/openrouter/free",]if self.provider_keys.get("openrouter"):179 unmodified linessuper().__init__(*args, **kwargs)self._explicit_api_key = kwargs.get("api_key")self._explicit_api_base = kwargs.get("api_base")self._last_llm_error = None # <-- DODAJ TĘ LINIĘ (16 spacji)if self._explicit_api_key:self.api_key = self._explicit_api_keyif self._explicit_api_base:self.api_base = self._explicit_api_baseif hasattr(LiteLLMModel, "generate"):def generate(self, *args, **kwargs):import timet0 = time.monotonic()kwargs = self._prepare_call_kwargs(dict(kwargs))try:msg = self._validate_message(super().generate(*args, **kwargs))self._last_llm_error = None # <-- DODAJ TĘ LINIĘ (24 spacje)return msgexcept Exception as exc:self._last_llm_error = exc # <-- DODAJ TĘ LINIĘ (24 spacje)raisefinally:print(f"[LLM] {self.model_id}: {time.monotonic() - t0:.1f}s")@classmethoddef _sanitize_code_tags(cls, text: str) -> str:import ast172 unmodified linescontent_str = f"{cls.open_tag}\n" + "\n".join(rendered_calls) + f"\n{cls.close_tag}"if not content_str and reasoning_str:code_matches = re.findall(r"(<code>.*?</code>|```(?:py|python)?\s*\n.*?```)",reasoning_str,flags=re.DOTALL | re.IGNORECASE,)if code_matches:content_str = code_matches[-1].strip()elif "final_answer(" in reasoning_str:content_str = reasoning_strelse:fa_matches = re.findall(r"(?im)^\s*(?:final\s*answer|answer)\s*:\s*(.+)$",reasoning_str,)if fa_matches and fa_matches[-1].strip():ans_val = fa_matches[-1].strip()content_str = (f"{cls.open_tag}\n"f"final_answer({json.dumps(ans_val, ensure_ascii=False)})\n"f"{cls.close_tag}")else:raise RuntimeError("Error in generating model output: reasoning-only response without code or final answer")if not content_str:raise RuntimeError(61 unmodified linesif hasattr(LiteLLMModel, "generate"):def generate(self, *args, **kwargs):import timet0 = time.monotonic()kwargs = self._prepare_call_kwargs(dict(kwargs))try:msg = self._validate_message(super().generate(*args, **kwargs))self._last_llm_error = Nonereturn msgexcept Exception as exc:self._last_llm_error = excraisefinally:print(f"[LLM] {self.model_id}: {time.monotonic() - t0:.1f}s")114 unmodified lines"- Do not wrap the answer in a dictionary like {'answer': ...}; pass the plain answer string directly.")def _abort_on_fatal_llm_error(step_log, *args, **kwargs):active_model = getattr(self.agent, "model", None)llm_err = getattr(active_model, "_last_llm_error", None)if llm_err is not None:raise llm_erragent_kwargs = {"model": model,"tools": [19 unmodified lines"string","re","time","math","cmath","statistics","datetime","collections","itertools","operator","openpyxl",],"instructions": exact_match_rule,"code_block_tags": (code_open_tag, code_close_tag),"step_callbacks": [_abort_on_fatal_llm_error],"max_steps": 8,"verbosity_level": 0,}12 unmodified linesif 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()4 unmodified linestext = 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"^\*\*(.+?)\*\*$", r"\1", text).strip()if len(text) >= 2 and ((text[0] == '"' and text[-1] == '"') or (text[0] == "'" and text[-1] == "'")):text = text[1:-1].strip()15 unmodified linesprompt = question.strip()self._prefer_2022_wiki = "2022" in prompt.lower()if task_id:prefetched_path = ""if hasattr(self, "_download_task_file"):try:res_path = self._download_task_file(task_id=task_id)if (isinstance(res_path, str)and not res_path.startswith(("Error ", "No attachment"))and os.path.isfile(res_path)):prefetched_path = res_pathexcept Exception:passif prefetched_path:prompt += (f"\n\nTask ID: {task_id}. The task attachment is already downloaded at '{prefetched_path}'. "f"Inspect it directly with read_local_file(file_path='{prefetched_path}'), "f"inspect_image(image_path='{prefetched_path}', question=...), or "f"transcribe_audio(audio_path='{prefetched_path}', question=...).")else:prompt += f"\n\nTask ID: {task_id}."blocked_models = set()blocked_providers = set()models_to_try = list(getattr(self, "working_models", []) or [self.model_id])if self.model_id and self.model_id not in models_to_try:models_to_try.append(self.model_id)deadline = time.monotonic() + 100.0prev_max_steps = getattr(self.agent, "max_steps", None)if prev_max_steps is not None:self.agent.max_steps = min(int(prev_max_steps), 8)try:backoff_rounds = 0while time.monotonic() < deadline:rate_limited_models = set()rate_limited_providers = set()for model_name in models_to_try:remaining = deadline - time.monotonic()if remaining <= 4.0:breakif not hasattr(self, "_build_model") or not hasattr(self, "agent"):return "AGENT ERROR: Agent not initialized."provider = model_name.split("/", 1)[0].lower() if "/" in model_name else "gemini"transient_retries = 0while time.monotonic() < deadline:if (model_name in blocked_modelsor model_name in rate_limited_modelsor provider in blocked_providers):breakif not self._get_api_key(model_name):blocked_providers.add(provider)breaktry:rem_now = deadline - time.monotonic()if rem_now <= 4.0:breakcall_timeout = max(5.0, min(30.0, rem_now - 1.0))self.model_id = model_namebuilt_model = self._build_model(model_name)built_model.timeout = call_timeoutbuilt_model.deadline = deadlineself.agent.model = built_modelresult = self.agent.run(prompt)raw_result = "" if result is None else str(result).strip()if raw_result.lower().startswith("error in generating"):raise RuntimeError(raw_result)cleaned = self._clean_exact_match_answer(raw_result)if cleaned and not cleaned.startswith("AGENT ERROR:"):return cleanedblocked_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:exc = llm_errerr_text = str(exc)err_lower = err_text.lower()print(f"[AGENT ERROR] task_id={task_id} model={model_name}: {err_text}")blocked_models = set()blocked_providers = set()2 unmodified linesif self.model_id and self.model_id not in models_to_try:models_to_try.append(self.model_id)deadline = time.monotonic() + 100.0prev_max_steps = getattr(self.agent, "max_steps", None)if prev_max_steps is not None:self.agent.max_steps = min(int(prev_max_steps), 8)try:backoff_rounds = 0
app.py+349-82