Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files103 unmodified lines104105106107108109110111112113114115116117118119120121122123124125126127128113129130115131132133118134135120136137138139140141142143123124125126127128129130131132133134135144145137146147148149150151152153154155156142157158159160113 unmodified lines27427527627727827928026428128228328428528628728828918 unmodified lines30830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036111 unmodified lines37337437530931037637737837938027 unmodified lines408409410411412413414450 unmodified lines86586686786886987087187287387487587687787887980888088188288388488588688788888989089189282082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385489389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797824 unmodified lines1003100410058851006100710081009193 unmodified lines1203120412051085108612061088120712081209121012111212121312141215179 unmodified lines1395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422172 unmodified lines159515961597146015981599160016011602146514661603160416051606160714681469147016081609161016111612161316141615161616171618161916201621162216231624162561 unmodified lines168716881689153916901691169216931543169416951696169716981699170017011702114 unmodified lines18171818181918201821182218231824182518261827182819 unmodified lines1848184918501851185218531854185518561857185818591860186118621692186318641865186612 unmodified lines1879188018811711188218831884188518861887188818891890189118921893189418954 unmodified lines190019011902190319041905172217231724172519061907190819091910191119121913191415 unmodified lines193019311932174717481749175019331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202 unmodified lines202320242025175920262027202817622029203020312032103 unmodified lines os.environ["HF_TOKEN"] = hf_key os.environ["HUGGINGFACE_API_KEY"] = hf_key
def _sync_provider_env(provider: str, key: str) -> None: self.provider_keys[provider] = key if not key: return if provider == "openrouter": os.environ["OPENROUTER_API_KEY"] = key elif provider == "groq": os.environ["GROQ_API_KEY"] = key elif provider == "huggingface": os.environ["HF_TOKEN"] = key os.environ["HUGGINGFACE_API_KEY"] = key elif provider == "gemini": self.gemini_key = key os.environ["GEMINI_API_KEY"] = key os.environ["GOOGLE_API_KEY"] = key
def _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] = key _sync_provider_env(provider, key) return key self.provider_keys[provider] = "" _sync_provider_env(provider, "") return None
def _rotate_api_key(provider: str) -> bool: def _rotate_api_key(provider: str, permanent: bool = False) -> bool: pool = self.provider_key_pools.get(provider) or [] next_idx = self._provider_key_idx.get(provider, 0) + 1 cur_idx = self._provider_key_idx.get(provider, 0) if permanent and 0 <= cur_idx < len(pool): pool.pop(cur_idx) next_idx = cur_idx else: next_idx = cur_idx + 1 self._provider_key_idx[provider] = next_idx if next_idx < len(pool): new_key = pool[next_idx] self.provider_keys[provider] = new_key if provider == "openrouter": os.environ["OPENROUTER_API_KEY"] = new_key elif provider == "groq": os.environ["GROQ_API_KEY"] = new_key elif provider == "huggingface": os.environ["HF_TOKEN"] = new_key os.environ["HUGGINGFACE_API_KEY"] = new_key elif provider == "gemini": self.gemini_key = new_key os.environ["GEMINI_API_KEY"] = new_key os.environ["GOOGLE_API_KEY"] = new_key _sync_provider_env(provider, pool[next_idx]) return True self.provider_keys[provider] = "" _sync_provider_env(provider, "") return False
def _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_env self._get_api_key = _get_api_key self._rotate_api_key = _rotate_api_key self.gemini_flash_models = [] self._reset_key_indices = _reset_key_indices
@tool def fetch_url_text(url: str) -> str:113 unmodified lines return 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
@tool def read_local_file(file_path: str) -> str: """Reads text, PDF, ZIP archive, or spreadsheet content from a local file downloaded by download_task_file. """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 re import xml.etree.ElementTree as ET import zipfile
def _read_single(path: str, max_chars: int) -> str:18 unmodified lines text = "\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.text for 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.text for 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 lines if 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)): 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 lines return _read_single(file_path, max_chars=48000) except Exception as e: return f"Error reading file '{file_path}': {str(e)}"
@tool def web_search(query: str) -> str:450 unmodified lines 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", "Cookie": "SOCS=CAI", } sections = [f"Video ID: {video_id}", f"URL: {watch_url}"] has_title = False has_desc = False caption_tracks = []
try: oembed_resp = requests.get( "https://www.youtube.com/oembed", params={"url": watch_url, "format": "json"}, headers=headers, timeout=20, timeout=15, ) if oembed_resp.status_code == 200: oembed = oembed_resp.json() if oembed.get("title"): sections.append(f"Title: {oembed['title']}") has_title = True if oembed.get("author_name"): sections.append(f"Channel: {oembed['author_name']}") except Exception: pass
try: page_resp = requests.get(watch_url, headers=headers, timeout=25) if page_resp.status_code == 200: html_text = page_resp.text 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]}")
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: continue 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]}") break except Exception: pass except Exception as e: sections.append(f"Page fetch note: {e}") 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 = 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") ) if isinstance(tracks, list): caption_tracks = tracks except Exception: pass
if 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.text if 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: continue try: 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]}") break except Exception: continue
gemini_pool = self.provider_key_pools.get("gemini") or [] if gemini_pool:24 unmodified lines "contents": [ { "parts": [ {"file_data": {"file_uri": watch_url}}, {"file_data": {"mime_type": "video/mp4", "file_uri": watch_url}}, {"text": question}, ] }193 unmodified lines
candidate_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/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 lines super().__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_key if self._explicit_api_base: self.api_base = self._explicit_api_base
if hasattr(LiteLLMModel, "generate"): def generate(self, *args, **kwargs): import time
t0 = 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 msg except Exception as exc: self._last_llm_error = exc # <-- DODAJ TĘ LINIĘ (24 spacje) raise finally: print(f"[LLM] {self.model_id}: {time.monotonic() - t0:.1f}s")
@classmethod def _sanitize_code_tags(cls, text: str) -> str: import ast172 unmodified lines content_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( code_matches = re.findall( r"(<code>.*?</code>|```(?:py|python)?\s*\n.*?```)", reasoning_str, flags=re.DOTALL | re.IGNORECASE, ) if code_match: content_str = code_match.group(1).strip() if code_matches: content_str = code_matches[-1].strip() elif "final_answer(" in reasoning_str: content_str = reasoning_str 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}' 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 lines if hasattr(LiteLLMModel, "generate"): def generate(self, *args, **kwargs): import time
t0 = time.monotonic() kwargs = self._prepare_call_kwargs(dict(kwargs)) try: return self._validate_message(super().generate(*args, **kwargs)) msg = self._validate_message(super().generate(*args, **kwargs)) self._last_llm_error = None return msg except Exception as exc: self._last_llm_error = exc raise 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." )
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_err
agent_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": 10, "max_steps": 8, "verbosity_level": 0, } 12 unmodified lines
if raw_answer is None: return "" if isinstance(raw_answer, (list, tuple)): 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 lines 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() 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] 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 lines prompt = 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." ) 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_path except Exception: pass
if 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.0 prev_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 while 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: break if 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 = 0 while time.monotonic() < deadline: if ( model_name in blocked_models or model_name in rate_limited_models or provider in blocked_providers ): break if not self._get_api_key(model_name): blocked_providers.add(provider) break try: rem_now = deadline - time.monotonic() if rem_now <= 4.0: break call_timeout = max(5.0, min(30.0, rem_now - 1.0)) self.model_id = model_name built_model = self._build_model(model_name) built_model.timeout = call_timeout built_model.deadline = deadline self.agent.model = built_model result = 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 cleaned blocked_models.add(model_name) break 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: exc = llm_err err_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 lines if self.model_id and self.model_id not in models_to_try: models_to_try.append(self.model_id)
deadline = time.monotonic() + 80.0 deadline = time.monotonic() + 100.0 prev_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) self.agent.max_steps = min(int(prev_max_steps), 8)
try: backoff_rounds = 0app.py+349-82