Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files28 unmodified lines293031323334351511 unmodified lines154715481549155015511552155312 unmodified lines15661567156815691570157197 unmodified lines1669167016711672167316741675343 unmodified lines201920202021202220232024202513 unmodified lines2039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210993 unmodified lines220322042205220622072208220978 unmodified lines2288228922902291229222932294125 unmodified lines242024212422242324242425242628 unmodified lines2455245624572458245924602461246224632464246524662467246828 unmodified linesfrom smolagents import CodeAgent, LiteLLMModel, toollitellm.drop_params = Truelitellm.request_timeout = 25provider_env_prefixes = {"openrouter": ("OPENROUTER_API_KEY", "OPENROUTER_TOKEN", "OPENROUTER_KEY"),1511 unmodified linesexcept Exception as list_exc:print(f"Warning: could not list Gemini models via REST: {list_exc}")if available_api_models:discovered_flash = sorted((m for m in available_api_models if "flash" in m.lower()),key=lambda name: (12 unmodified lines"gemini/gemini-flash-lite-latest",]candidate_models.extend(self.gemini_flash_models)if self.provider_keys.get("groq"):live_groq = []97 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:343 unmodified lines"reasoning_effort": "low",**common,}if "gemini-3" not in model_name.lower():kwargs["temperature"] = 0.1elif model_name.startswith("huggingface/"):raw_hf = model_name[len("huggingface/"):]13 unmodified lines}return self._model_cls(**kwargs)def _probe_candidate(model_name: str) -> tuple[str, bool]:api_key = self._get_api_key(model_name)if not api_key:return (model_name, False)try:if model_name.startswith("gemini/"):raw_gemini = model_name[len("gemini/"):]resp = requests.post(f"https://generativelanguage.googleapis.com/v1beta/models/{raw_gemini}:generateContent",params={"key": api_key},headers={"Content-Type": "application/json"},json={"contents": [{"parts": [{"text": "hi"}]}],"generationConfig": {"maxOutputTokens": 1},},timeout=10,)return (model_name, resp.status_code not in (400, 404, 410))if model_name.startswith("groq/"):resp = requests.post("https://api.groq.com/openai/v1/chat/completions",headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},json={"model": model_name[len("groq/"):],"messages": [{"role": "user", "content": "hi"}],"max_tokens": 1,},timeout=10,)return (model_name, resp.status_code not in (400, 404, 410))if model_name.startswith("huggingface/"):resp = requests.post("https://router.huggingface.co/v1/chat/completions",headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},json={"model": model_name[len("huggingface/"):],"messages": [{"role": "user", "content": "hi"}],"max_tokens": 1,},timeout=10,)return (model_name, resp.status_code not in (400, 404, 410))return (model_name, True)except Exception:return (model_name, True)from concurrent.futures import ThreadPoolExecutor, wait as futures_waitprobed_slice = self.working_models[:5]probe_results = {}probe_pool = ThreadPoolExecutor(max_workers=5)try:probe_futures = [probe_pool.submit(_probe_candidate, m) for m in probed_slice]done, _ = futures_wait(probe_futures, timeout=12)for fut in done:try:probed_name, probed_ok = fut.result()probe_results[probed_name] = probed_okexcept Exception:passfinally:probe_pool.shutdown(wait=False, cancel_futures=True)filtered_models = [m for m in self.working_models if probe_results.get(m, True)]if filtered_models:self.working_models = filtered_modelsself.model_id = self.working_models[0]print(f"Using primary LLM model: {self.model_id} (fallbacks: {self.working_models[1:]})")93 unmodified linesif 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()78 unmodified linesif hasattr(self, "_reset_key_indices"):self._reset_key_indices()deadline = time.monotonic() + 140.0self._local_state.deadline = deadlineself._task_deadline = deadline125 unmodified linesrem_now = deadline - step_t0if rem_now <= 6.0:breakcall_timeout = max(12.0, min(30.0, rem_now - 3.0))print(f"[TRACE] task_id={task_id} model={model_name} provider={provider} "f"rem={rem_now:.1f}s timeout={call_timeout:.1f}s start",28 unmodified linesprint(f"[AGENT ERROR] task_id={task_id} model={model_name}: {err_text}", flush=True)if "task time budget exhausted" in err_lower:breakif any(marker in err_lowerfor marker in ("401","402","403","authentication","invalid api key","permission_denied","insufficient permissions",)28 unmodified lines293031323334351511 unmodified lines154715481549155015511552155312 unmodified lines156615671568156915701571157297 unmodified lines1670167116721673167416751676343 unmodified lines202020212022202320242025202613 unmodified lines20402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210593 unmodified lines2199220022012202220322042205220622072208220922102211221278 unmodified lines2291229222932294229522962297125 unmodified lines242324242425242624272428242928 unmodified lines245824592460246124622463246424652466246724682469247028 unmodified linesfrom smolagents import CodeAgent, LiteLLMModel, toollitellm.drop_params = Truelitellm.request_timeout = 120provider_env_prefixes = {"openrouter": ("OPENROUTER_API_KEY", "OPENROUTER_TOKEN", "OPENROUTER_KEY"),1511 unmodified linesexcept Exception as list_exc:print(f"Warning: could not list Gemini models via REST: {list_exc}")f available_api_models:discovered_flash = sorted((m for m in available_api_models if "flash" in m.lower()),key=lambda name: (12 unmodified lines"gemini/gemini-flash-lite-latest",]candidate_models.extend(self.gemini_flash_models)print(f"[GEMINI MODELS] {self.gemini_flash_models}", flush=True)if self.provider_keys.get("groq"):live_groq = []97 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 = Noneif self._explicit_api_key:self.api_key = self._explicit_api_keyif self._explicit_api_base:343 unmodified lines"reasoning_effort": "low",**common,}if "gemini-3" not in model_name.lower() and "latest" not in model_name.lower():kwargs["temperature"] = 0.1elif model_name.startswith("huggingface/"):raw_hf = model_name[len("huggingface/"):]13 unmodified lines}return self._model_cls(**kwargs)def _probe_candidate(model_name: str) -> tuple[str, str, str]:import timeapi_key = self._get_api_key(model_name)if not api_key:return (model_name, "dead", "no api key")t0 = time.monotonic()try:kw = {"model": model_name, "api_key": api_key}if model_name.startswith("huggingface/"):kw = {"model": "openai/" + model_name[len("huggingface/"):],"api_base": "https://router.huggingface.co/v1","api_key": api_key,}litellm.completion(**kw,messages=[{"role": "user", "content": "Reply with the single word OK."}],max_tokens=64,timeout=20,num_retries=0,)return (model_name, "ok", f"{time.monotonic() - t0:.1f}s")except Exception as exc:text = f"{type(exc).__name__}: {exc}"low = text.lower()short = " ".join(text.split())[:220]busy_markers = ("429", "rate limit", "quota", "resource_exhausted","timeout", "timed out", "connection", "503", "overloaded", "unavailable",)if any(m in low for m in busy_markers):return (model_name, "busy", short)return (model_name, "dead", short)from concurrent.futures import ThreadPoolExecutor, wait as futures_wait# OpenRouter :free ma 50 zapytań/dzień – nie marnujemy ich na testprobe_targets = [m for m in self.working_models if not m.startswith("openrouter/")][:8]probe_status = {}probe_pool = ThreadPoolExecutor(max_workers=6)try:probe_futures = [probe_pool.submit(_probe_candidate, m) for m in probe_targets]done, _ = futures_wait(probe_futures, timeout=30)for fut in done:try:p_name, p_state, p_info = fut.result()probe_status[p_name] = p_stateprint(f"[PREFLIGHT] {p_state.upper():4} {p_name} :: {p_info}", flush=True)except Exception:passfinally:probe_pool.shutdown(wait=False, cancel_futures=True)ok_models = [m for m in self.working_models if probe_status.get(m) == "ok"]untested = [m for m in self.working_models if m not in probe_status]busy_models = [m for m in self.working_models if probe_status.get(m) == "busy"]reordered = ok_models + untested + busy_modelsif reordered:self.working_models = reorderedself.model_id = self.working_models[0]print(f"Using primary LLM model: {self.model_id} (fallbacks: {self.working_models[1:]})")93 unmodified linesif not cleaned or cleaned.startswith("AGENT ERROR:"):return cleanedcleaned = re.sub(r"</?code[^>]*>", "", cleaned, flags=re.IGNORECASE).strip()fa_call = re.fullmatch(r"final_answer\(\s*(?:answer\s*=\s*)?(.*?)\s*\)",cleaned,flags=re.DOTALL,)if fa_call:cleaned = fa_call.group(1).strip()if cleaned.startswith("```") and cleaned.endswith("```"):lines = cleaned.splitlines()78 unmodified linesif hasattr(self, "_reset_key_indices"):self._reset_key_indices()deadline = time.monotonic() + 185.0self._local_state.deadline = deadlineself._task_deadline = deadline125 unmodified linesrem_now = deadline - step_t0if rem_now <= 6.0:breakcall_timeout = max(15.0, min(55.0, rem_now - 3.0))print(f"[TRACE] task_id={task_id} model={model_name} provider={provider} "f"rem={rem_now:.1f}s timeout={call_timeout:.1f}s start",28 unmodified linesprint(f"[AGENT ERROR] task_id={task_id} model={model_name}: {err_text}", flush=True)if "task time budget exhausted" in err_lower:breakhttp_status = getattr(exc, "status_code", None)if http_status in (401, 402, 403) or any(marker in err_lowerfor marker in ("authentication","invalid api key","api key not valid","permission_denied","insufficient permissions",)
app.py+64-62