Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files28 unmodified lines29303132323334351511 unmodified lines1547154815491550155015511552155312 unmodified lines156615671568156915701571157297 unmodified lines16701671167216721673167416751676343 unmodified lines2020202120222022202320242025202613 unmodified lines20402041204220422043204420452046204720452048204920502047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071205120522073207420752076207720782079208020812082208320842085208620532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920902091209220802081208220832084209420952085208620872088209820992089209020912092209320942095210421052106209620972098209921002101210221032104210593 unmodified lines21992200220122062202220322042205220622072208220922102211221278 unmodified lines22912292229322912294229522962297125 unmodified lines2423242424252423242624272428242928 unmodified lines2458245924602458246124622463246424612462246324652466246724682469247028 unmodified lines from smolagents import CodeAgent, LiteLLMModel, tool litellm.drop_params = True litellm.request_timeout = 25 litellm.request_timeout = 120
provider_env_prefixes = { "openrouter": ("OPENROUTER_API_KEY", "OPENROUTER_TOKEN", "OPENROUTER_KEY"),1511 unmodified lines except Exception as list_exc: print(f"Warning: could not list Gemini models via REST: {list_exc}")
if available_api_models: 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 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) self._last_llm_error = None if self._explicit_api_key: self.api_key = self._explicit_api_key if self._explicit_api_base:343 unmodified lines "reasoning_effort": "low", **common, } if "gemini-3" not in model_name.lower(): if "gemini-3" not in model_name.lower() and "latest" not in model_name.lower(): kwargs["temperature"] = 0.1 elif 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]: def _probe_candidate(model_name: str) -> tuple[str, str, str]: import time
api_key = self._get_api_key(model_name) if not api_key: return (model_name, False) return (model_name, "dead", "no api key") t0 = time.monotonic() 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)) kw = {"model": model_name, "api_key": api_key} 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) 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
probed_slice = self.working_models[:5] probe_results = {} probe_pool = ThreadPoolExecutor(max_workers=5) # OpenRouter :free ma 50 zapytań/dzień – nie marnujemy ich na test probe_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 probed_slice] done, _ = futures_wait(probe_futures, timeout=12) 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: probed_name, probed_ok = fut.result() probe_results[probed_name] = probed_ok p_name, p_state, p_info = fut.result() probe_status[p_name] = p_state print(f"[PREFLIGHT] {p_state.upper():4} {p_name} :: {p_info}", flush=True) except Exception: pass finally: 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_models
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_models if reordered: self.working_models = reordered
self.model_id = self.working_models[0] print(f"Using primary LLM model: {self.model_id} (fallbacks: {self.working_models[1:]})")93 unmodified lines if not cleaned or cleaned.startswith("AGENT ERROR:"): return cleaned
cleaned = re.sub(r"<think>.*?</think>", "", cleaned, flags=re.DOTALL | re.IGNORECASE).strip() cleaned = 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 lines if hasattr(self, "_reset_key_indices"): self._reset_key_indices()
deadline = time.monotonic() + 140.0 deadline = time.monotonic() + 185.0 self._local_state.deadline = deadline self._task_deadline = deadline
125 unmodified lines rem_now = deadline - step_t0 if rem_now <= 6.0: break call_timeout = max(12.0, min(30.0, rem_now - 3.0)) call_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 lines 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( http_status = getattr(exc, "status_code", None) if http_status in (401, 402, 403) or any( marker in err_lower for marker in ( "401", "402", "403", "authentication", "invalid api key", "api key not valid", "permission_denied", "insufficient permissions", )app.py+64-62