Spaces:
Runtime error
Runtime error
Update app.py
Browse files233 unmodified lines23423523623723723823924049 unmodified lines290291292293294295296297141 unmodified lines4394404414424434444453 unmodified lines4494504514524534544554564574584594604614624634644654664674504514524684694704714544724734742 unmodified lines4774784794634644804814824834844851 unmodified line48748848947249049149249310 unmodified lines50450550648949050750850951051151231 unmodified lines54454554652854754854955055155255326 unmodified lines58058158256358358458558620 unmodified lines60760860959061061161261361461561653 unmodified lines6706716726526736746756763 unmodified lines680681682662663683684685686687688689690691670692693694695829 unmodified lines1525152615271528152915301531150915321533153415351536151115371538153915401541154215431544154515461547154815491550155115181552155315541555260 unmodified lines181618171818178518191820182118221823182417911792182518261827182818291830183118321833231 unmodified lines206520662067203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420682069207020562057207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097205920602061209820992100206320642101210221032104206621052106210722 unmodified lines2130213121322095213321342135213621372138210121392140214121429 unmodified lines21522153215421172155215621572158233 unmodified lines try: resp = requests.get( url, timeout=30, timeout=_tool_timeout(8.0, min_timeout=2.0), headers={"User-Agent": "Mozilla/5.0"}, ) if resp.status_code == 404:49 unmodified lines return out_path except Exception as exc: last_err = exc if "task time budget exhausted" in str(exc).lower(): break
if last_err is not None: return f"Error downloading file for task '{clean_id}': {str(last_err)}"141 unmodified lines Args: query: The search query string. """ from concurrent.futures import ThreadPoolExecutor import re from html import unescape
3 unmodified lines
results_out = [] try: ddgs_timeout = _tool_timeout(8.0, min_timeout=3.0)
def _run_ddgs(): try: from ddgs import DDGS except ImportError: from duckduckgo_search import DDGS try: 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: from ddgs import DDGS except ImportError: from duckduckgo_search import DDGS raw_results = ddgs_fut.result(timeout=ddgs_timeout) finally: ddgs_pool.shutdown(wait=False, cancel_futures=True)
raw_results = DDGS().text(clean_q, max_results=5) or [] for item in raw_results: if not isinstance(item, dict): continue2 unmodified lines body = str(item.get("body", "")).strip() if title or href or body: results_out.append(f"- {title}\n URL: {href}\n Snippet: {body}") except Exception: pass 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=25, timeout=_tool_timeout(8.0, min_timeout=3.0), ) resp.raise_for_status() links = re.findall(10 unmodified lines 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: pass 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=12, 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) continue break26 unmodified lines "format": "json", }, headers=headers, timeout=10, 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 lines api_endpoint, params=parse_params, headers=headers, timeout=12, 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) continue break53 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, timeout=_tool_timeout(7.0, min_timeout=2.5), ) resp.raise_for_status() data = resp.json()3 unmodified lines wiki_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: pass 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=15, timeout=_tool_timeout(7.0, min_timeout=2.5), ) ddg_resp.raise_for_status() matches = re.findall(829 unmodified lines
if hasattr(LiteLLMModel, "generate"): def generate(self, *args, **kwargs): from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeoutError import time
t0 = time.monotonic() kwargs = self._prepare_call_kwargs(dict(kwargs)) call_kwargs = self._prepare_call_kwargs(dict(kwargs)) hard_timeout = float(call_kwargs.get("timeout") or getattr(self, "timeout", None) or 20.0) + 2.0 executor = ThreadPoolExecutor(max_workers=1) future = executor.submit(super().generate, *args, **call_kwargs) try: msg = self._validate_message(super().generate(*args, **kwargs)) raw_msg = future.result(timeout=hard_timeout) msg = self._validate_message(raw_msg) self._last_llm_error = None return msg except FutureTimeoutError: timeout_exc = TimeoutError( f"LLM call timed out after {hard_timeout:.1f}s for {self.model_id}" ) self._last_llm_error = timeout_exc raise timeout_exc except Exception as exc: self._last_llm_error = exc raise finally: executor.shutdown(wait=False, cancel_futures=True) print(f"[LLM] {self.model_id}: {time.monotonic() - t0:.1f}s") print(f"[LLM] {self.model_id}: {time.monotonic() - t0:.1f}s", flush=True)
@classmethod def _sanitize_code_tags(cls, text: str) -> str:260 unmodified lines os.environ["OPENROUTER_API_KEY"] = key elif model_name.startswith("groq/"): os.environ["GROQ_API_KEY"] = key timeout = getattr(self, "timeout", None) or 45 timeout = 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 = min(timeout, remaining) kwargs.setdefault("timeout", timeout) timeout = max(3.0, min(timeout, remaining - 1.5)) self.timeout = timeout if isinstance(getattr(self, "kwargs", None), dict): self.kwargs["timeout"] = timeout kwargs["timeout"] = timeout litellm.request_timeout = timeout if model_name.startswith("openrouter/"): kwargs["max_tokens"] = 4096 return kwargs231 unmodified lines if 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_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}." deadline = time.monotonic() + 55.0 self._local_state.deadline = deadline
blocked_models = set() blocked_providers = set() try: 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_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}."
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) blocked_models = set() blocked_providers = set()
deadline = time.monotonic() + 62.0 self._local_state.deadline = deadline 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)
try: backoff_rounds = 0 while time.monotonic() < deadline: rate_limited_models = set()22 unmodified lines rem_now = deadline - time.monotonic() if rem_now <= 4.0: break call_timeout = max(5.0, min(22.0, rem_now - 1.0)) call_timeout = max(4.0, min(16.0, rem_now - 2.0)) self.model_id = model_name built_model = self._build_model(model_name) built_model.timeout = call_timeout built_model.deadline = deadline run_agent = self._create_code_agent(built_model) run_agent.max_steps = 6 run_agent.max_steps = 4 result = run_agent.run(prompt) raw_result = "" if result is None else str(result).strip() if raw_result.lower().startswith("error in generating"):9 unmodified lines 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}") print(f"[AGENT ERROR] task_id={task_id} model={model_name}: {err_text}", flush=True) if "task time budget exhausted" in err_lower: break if any(app.py+97-59