Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files233 unmodified lines23423523623723823924049 unmodified lines290291292293294295141 unmodified lines4374384394404414423 unmodified lines4464474484494504514524534544554564572 unmodified lines4604614624634644654664671 unmodified line46947047147247347447510 unmodified lines48648748848949049149249331 unmodified lines52552652752852953053153253326 unmodified lines56056156256356456556620 unmodified lines58758858959059159259359459553 unmodified lines6496506516526536546553 unmodified lines659660661662663664665666667668669670671672673829 unmodified lines1503150415051506150715081509151015111512151315141515151615171518151915201521260 unmodified lines17821783178417851786178717881789179017911792179317941795231 unmodified lines202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206922 unmodified lines20922093209420952096209720982099210021012102210321049 unmodified lines2114211521162117211821192120233 unmodified linestry:resp = requests.get(url,timeout=30,headers={"User-Agent": "Mozilla/5.0"},)if resp.status_code == 404:49 unmodified linesreturn out_pathexcept Exception as exc:last_err = excif last_err is not None:return f"Error downloading file for task '{clean_id}': {str(last_err)}"141 unmodified linesArgs:query: The search query string."""import refrom html import unescape3 unmodified linesresults_out = []try:try:from ddgs import DDGSexcept ImportError:from duckduckgo_search import DDGSraw_results = DDGS().text(clean_q, max_results=5) or []for item in raw_results:if not isinstance(item, dict):continue2 unmodified linesbody = str(item.get("body", "")).strip()if title or href or body:results_out.append(f"- {title}\n URL: {href}\n Snippet: {body}")except Exception:passif not results_out:try:1 unmodified line"https://html.duckduckgo.com/html/",data={"q": clean_q},headers={"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36"},timeout=25,)resp.raise_for_status()links = re.findall(10 unmodified linessnip = 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:passif not results_out:return f"No web results found for '{clean_q}'. Try search_wikipedia(query) or fetch_url_text(url)."31 unmodified lines"srlimit": 5,},headers=headers,timeout=12,)if search_resp.status_code == 429 and attempt < 1:time.sleep(0.5)continuebreak26 unmodified lines"format": "json",},headers=headers,timeout=10,)if rev_resp.status_code == 200:pages = rev_resp.json().get("query", {}).get("pages", {})20 unmodified linesapi_endpoint,params=parse_params,headers=headers,timeout=12,)if parse_resp.status_code == 429 and attempt < 1:time.sleep(0.5)continuebreak53 unmodified lines"https://en.wikipedia.org/w/api.php",params={"action": "opensearch", "search": cleaned_query, "limit": 3, "format": "json"},headers={"User-Agent": "BasicAgent/1.0"},timeout=15,)resp.raise_for_status()data = resp.json()3 unmodified lineswiki_lines = [f"{t}: {d} ({u})" for t, d, u in zip(titles, descs, urls) if t or d]if wiki_lines:return "\n".join(wiki_lines)except Exception:passtry:ddg_resp = requests.post("https://html.duckduckgo.com/html/",data={"q": cleaned_query},headers={"User-Agent": "Mozilla/5.0"},timeout=15,)ddg_resp.raise_for_status()matches = re.findall(829 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")@classmethoddef _sanitize_code_tags(cls, text: str) -> str:260 unmodified linesos.environ["OPENROUTER_API_KEY"] = keyelif model_name.startswith("groq/"):os.environ["GROQ_API_KEY"] = keytimeout = getattr(self, "timeout", None) or 45task_deadline = getattr(self, "deadline", None)if task_deadline is not None:remaining = task_deadline - time.monotonic()if remaining <= 3.0:raise RuntimeError("Task time budget exhausted")timeout = min(timeout, remaining)kwargs.setdefault("timeout", timeout)if model_name.startswith("openrouter/"):kwargs["max_tokens"] = 4096return kwargs231 unmodified linesif hasattr(self, "_reset_key_indices"):self._reset_key_indices()prompt = 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() + 62.0self._local_state.deadline = deadlinetry:backoff_rounds = 0while time.monotonic() < deadline:rate_limited_models = set()22 unmodified linesrem_now = deadline - time.monotonic()if rem_now <= 4.0:breakcall_timeout = max(5.0, min(22.0, rem_now - 1.0))self.model_id = model_namebuilt_model = self._build_model(model_name)built_model.timeout = call_timeoutbuilt_model.deadline = deadlinerun_agent = self._create_code_agent(built_model)run_agent.max_steps = 6result = run_agent.run(prompt)raw_result = "" if result is None else str(result).strip()if raw_result.lower().startswith("error in generating"):9 unmodified linesexc = llm_errerr_text = str(exc)err_lower = err_text.lower()print(f"[AGENT ERROR] task_id={task_id} model={model_name}: {err_text}")if "task time budget exhausted" in err_lower:breakif any(233 unmodified lines23423523623723823924049 unmodified lines290291292293294295296297141 unmodified lines4394404414424434444453 unmodified lines4494504514524534544554564574584594604614624634644654664674684694704714724734742 unmodified lines4774784794804814824834844851 unmodified line48748848949049149249310 unmodified lines50450550650750850951051151231 unmodified lines54454554654754854955055155255326 unmodified lines58058158258358458558620 unmodified lines60760860961061161261361461561653 unmodified lines6706716726736746756763 unmodified lines680681682683684685686687688689690691692693694695829 unmodified lines1525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555260 unmodified lines181618171818181918201821182218231824182518261827182818291830183118321833231 unmodified lines206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210722 unmodified lines21302131213221332134213521362137213821392140214121429 unmodified lines2152215321542155215621572158233 unmodified linestry:resp = requests.get(url,timeout=_tool_timeout(8.0, min_timeout=2.0),headers={"User-Agent": "Mozilla/5.0"},)if resp.status_code == 404:49 unmodified linesreturn out_pathexcept Exception as exc:last_err = excif "task time budget exhausted" in str(exc).lower():breakif last_err is not None:return f"Error downloading file for task '{clean_id}': {str(last_err)}"141 unmodified linesArgs:query: The search query string."""from concurrent.futures import ThreadPoolExecutorimport refrom html import unescape3 unmodified linesresults_out = []try:ddgs_timeout = _tool_timeout(8.0, min_timeout=3.0)def _run_ddgs():try:from ddgs import DDGSexcept ImportError:from duckduckgo_search import DDGStry:client = DDGS(timeout=int(ddgs_timeout))except TypeError:client = DDGS()return client.text(clean_q, max_results=5) or []ddgs_pool = ThreadPoolExecutor(max_workers=1)ddgs_fut = ddgs_pool.submit(_run_ddgs)try:raw_results = ddgs_fut.result(timeout=ddgs_timeout)finally:ddgs_pool.shutdown(wait=False, cancel_futures=True)for item in raw_results:if not isinstance(item, dict):continue2 unmodified linesbody = str(item.get("body", "")).strip()if title or href or body:results_out.append(f"- {title}\n URL: {href}\n Snippet: {body}")except Exception as ddgs_exc:if "task time budget exhausted" in str(ddgs_exc).lower():return f"Web search aborted: {ddgs_exc}"if not results_out:try:1 unmodified line"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(10 unmodified linessnip = 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 html_exc:if "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)."31 unmodified lines"srlimit": 5,},headers=headers,timeout=_tool_timeout(8.0, min_timeout=2.5),)if search_resp.status_code == 429 and attempt < 1:_tool_timeout(3.0, min_timeout=1.0)time.sleep(0.5)continuebreak26 unmodified lines"format": "json",},headers=headers,timeout=_tool_timeout(6.0, min_timeout=2.0),)if rev_resp.status_code == 200:pages = rev_resp.json().get("query", {}).get("pages", {})20 unmodified linesapi_endpoint,params=parse_params,headers=headers,timeout=_tool_timeout(8.0, min_timeout=2.5),)if parse_resp.status_code == 429 and attempt < 1:_tool_timeout(3.0, min_timeout=1.0)time.sleep(0.5)continuebreak53 unmodified lines"https://en.wikipedia.org/w/api.php",params={"action": "opensearch", "search": cleaned_query, "limit": 3, "format": "json"},headers={"User-Agent": "BasicAgent/1.0"},timeout=_tool_timeout(7.0, min_timeout=2.5),)resp.raise_for_status()data = resp.json()3 unmodified lineswiki_lines = [f"{t}: {d} ({u})" for t, d, u in zip(titles, descs, urls) if t or d]if wiki_lines:return "\n".join(wiki_lines)except Exception as wiki_exc:if "task time budget exhausted" in str(wiki_exc).lower():return "Brak wyników."try:ddg_resp = requests.post("https://html.duckduckgo.com/html/",data={"q": cleaned_query},headers={"User-Agent": "Mozilla/5.0"},timeout=_tool_timeout(7.0, min_timeout=2.5),)ddg_resp.raise_for_status()matches = re.findall(829 unmodified linesif hasattr(LiteLLMModel, "generate"):def generate(self, *args, **kwargs):from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeoutErrorimport timet0 = time.monotonic()call_kwargs = self._prepare_call_kwargs(dict(kwargs))hard_timeout = float(call_kwargs.get("timeout") or getattr(self, "timeout", None) or 20.0) + 2.0executor = ThreadPoolExecutor(max_workers=1)future = executor.submit(super().generate, *args, **call_kwargs)try:raw_msg = future.result(timeout=hard_timeout)msg = self._validate_message(raw_msg)self._last_llm_error = Nonereturn msgexcept FutureTimeoutError:timeout_exc = TimeoutError(f"LLM call timed out after {hard_timeout:.1f}s for {self.model_id}")self._last_llm_error = timeout_excraise timeout_excexcept Exception as exc:self._last_llm_error = excraisefinally:executor.shutdown(wait=False, cancel_futures=True)print(f"[LLM] {self.model_id}: {time.monotonic() - t0:.1f}s", flush=True)@classmethoddef _sanitize_code_tags(cls, text: str) -> str:260 unmodified linesos.environ["OPENROUTER_API_KEY"] = keyelif model_name.startswith("groq/"):os.environ["GROQ_API_KEY"] = keytimeout = float(getattr(self, "timeout", None) or 20.0)task_deadline = getattr(self, "deadline", None)if task_deadline is not None:remaining = task_deadline - time.monotonic()if remaining <= 3.0:raise RuntimeError("Task time budget exhausted")timeout = max(3.0, min(timeout, remaining - 1.5))self.timeout = timeoutif isinstance(getattr(self, "kwargs", None), dict):self.kwargs["timeout"] = timeoutkwargs["timeout"] = timeoutlitellm.request_timeout = timeoutif model_name.startswith("openrouter/"):kwargs["max_tokens"] = 4096return kwargs231 unmodified linesif hasattr(self, "_reset_key_indices"):self._reset_key_indices()deadline = time.monotonic() + 55.0self._local_state.deadline = deadlinetry:prompt = 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)backoff_rounds = 0while time.monotonic() < deadline:rate_limited_models = set()22 unmodified linesrem_now = deadline - time.monotonic()if rem_now <= 4.0:breakcall_timeout = max(4.0, min(16.0, rem_now - 2.0))self.model_id = model_namebuilt_model = self._build_model(model_name)built_model.timeout = call_timeoutbuilt_model.deadline = deadlinerun_agent = self._create_code_agent(built_model)run_agent.max_steps = 4result = run_agent.run(prompt)raw_result = "" if result is None else str(result).strip()if raw_result.lower().startswith("error in generating"):9 unmodified linesexc = llm_errerr_text = str(exc)err_lower = err_text.lower()print(f"[AGENT ERROR] task_id={task_id} model={model_name}: {err_text}", flush=True)if "task time budget exhausted" in err_lower:breakif any(
app.py+97-59