Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files27 unmodified lines2829303131323334154 unmodified lines18919019119219219319419553 unmodified lines249250251252252253254255244 unmodified lines50050150250350350450550634 unmodified lines54154254354454454554654725 unmodified lines573574575576576577578579288 unmodified lines8688698708718718728738748758738748758768775 unmodified lines88388488588788688788989088888989089189289323 unmodified lines917918919920920921922923366 unmodified lines1290129112921293129312941295129685 unmodified lines1382138313841385138513861387138863 unmodified lines1452145314541455145514561457145859 unmodified lines151815191520152115211522152315246 unmodified lines153115321533153415341535153615361537153815394 unmodified lines1544154515461547154715481549155049 unmodified lines16001601160216031604160416051606160716081606160716081611160916101611161216131614161516161617161816181619162016213 unmodified lines16251626162716281629163016317 unmodified lines163916401641164116421643164416459 unmodified lines16551656165716571658165916601661166216631658165916601667166116621669166316641665166616731667166816691670167116721673167416751676167741 unmodified lines171917201721172117221722172317241725172623 unmodified lines175017511752175317541755175617571758347 unmodified lines21062107210821052106210721082109211021092111211021112112211321142115211821162117211821191 unmodified line212121222123212621242125212821262127212821292132213321302131213219 unmodified lines215221532154215921552156215721582159216421602161216221636 unmodified lines21702171217221772173217421752176217721782179218021812182218321842185218621872188218421892190219121929 unmodified lines2202220322042205220622072208220922103 unmodified lines221422152216220922102217221822192220222112 unmodified lines2234223522362229223722382239224022412234224222432244224516 unmodified lines22622263226422572265226622672268226922592270227122722273227422752276227722782279333 unmodified lines261326142615259926162617261826194 unmodified lines26242625262626102627262826292630443 unmodified lines3074307530763060307727 unmodified lines from smolagents import CodeAgent, LiteLLMModel, MultiStepAgent, tool
litellm.drop_params = True litellm.request_timeout = 120 litellm.request_timeout = 25
provider_env_prefixes = { "openrouter": ("OPENROUTER_API_KEY", "OPENROUTER_TOKEN", "OPENROUTER_KEY"),154 unmodified lines try: response = requests.get( url, timeout=_tool_timeout(20.0), timeout=_tool_timeout(15.0), headers={"User-Agent": "Mozilla/5.0"}, ) response.raise_for_status()53 unmodified lines try: resp = requests.get( url, timeout=(10.0, _tool_timeout(30.0, min_timeout=5.0)), timeout=(8.0, _tool_timeout(25.0, min_timeout=5.0)), headers={"User-Agent": "Mozilla/5.0"}, ) if resp.status_code in {429, 502, 503, 504} and attempt < 2:244 unmodified lines
results_out = [] try: ddgs_timeout = _tool_timeout(8.0, min_timeout=3.0) ddgs_timeout = _tool_timeout(7.0, min_timeout=3.0)
def _run_ddgs(): try:34 unmodified lines "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", }, timeout=_tool_timeout(8.0, min_timeout=3.0), timeout=_tool_timeout(7.0, min_timeout=3.0), ) resp.raise_for_status() link_matches = re.findall(25 unmodified lines "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", }, timeout=_tool_timeout(8.0, min_timeout=3.0), timeout=_tool_timeout(7.0, min_timeout=3.0), ) lite_resp.raise_for_status() lite_links = re.findall(288 unmodified lines if current_model and any(tag in current_model_low for tag in vision_tags): vision_candidates.append(current_model)
if self.provider_keys.get("openrouter"): if self.provider_keys.get("groq") or self.provider_key_pools.get("groq"): vision_candidates.extend([ "openrouter/google/gemma-4-26b-a4b-it:free", "openrouter/google/gemma-4-31b-it:free", "openrouter/google/gemma-3-27b-it:free", "groq/meta-llama/llama-4-scout-17b-16e-instruct", "groq/meta-llama/llama-4-maverick-17b-128e-instruct", ])
if self.provider_keys.get("gemini"):5 unmodified lines ] )
if self.provider_keys.get("groq") or self.provider_key_pools.get("groq"): if self.provider_keys.get("openrouter"): vision_candidates.extend([ "groq/meta-llama/llama-4-scout-17b-16e-instruct", "groq/meta-llama/llama-4-maverick-17b-128e-instruct", "openrouter/google/gemma-4-26b-a4b-it:free", "openrouter/google/gemma-4-31b-it:free", "openrouter/google/gemma-3-27b-it:free", ])
for m in getattr(self, "working_models", []):23 unmodified lines call_kwargs["num_retries"] = 0 call_kwargs["max_retries"] = 0 call_kwargs["max_tokens"] = 1024 call_kwargs["timeout"] = _tool_timeout(28.0) call_kwargs["timeout"] = _tool_timeout(20.0) if v_provider == "openrouter" or (v_provider == "gemini" and "gemma" not in v_model.lower()): call_kwargs["reasoning_effort"] = "low"
366 unmodified lines "thinkingConfig": {"thinkingBudget": 0}, }, }, timeout=_tool_timeout(32.0, min_timeout=4.0), timeout=_tool_timeout(20.0, min_timeout=4.0), ) if gm_resp.status_code == 200: candidates = gm_resp.json().get("candidates") or []85 unmodified lines headers={"Authorization": f"Bearer {groq_key}"}, files={"file": (os.path.basename(audio_path), audio_f, mime_type)}, data={"model": "whisper-large-v3-turbo", "response_format": "text"}, timeout=_tool_timeout(25.0), timeout=_tool_timeout(20.0), ) if groq_resp.status_code == 200: transcript = groq_resp.text.strip()63 unmodified lines "thinkingConfig": {"thinkingBudget": 0}, }, }, timeout=_tool_timeout(60.0), timeout=_tool_timeout(30.0), ) if gm_resp.status_code == 200: candidates = gm_resp.json().get("candidates") or []59 unmodified lines try: or_resp = requests.get( "https://openrouter.ai/api/v1/models", timeout=15, timeout=10, headers={"User-Agent": "HF-Agents-Course-Bot/1.0"}, ) if or_resp.status_code == 200:6 unmodified lines
if live_free_models: curated_live = [m for m in priority_openrouter_models if m in live_free_models] candidate_models.extend(curated_live[:3] or ["openrouter/openrouter/free"]) candidate_models.extend(curated_live[:2] or ["openrouter/openrouter/free"]) else: candidate_models.extend(priority_openrouter_models[:3]) candidate_models.extend(priority_openrouter_models[:2])
if self.provider_keys.get("gemini"): available_api_models = set()4 unmodified lines models_resp = requests.get( "https://generativelanguage.googleapis.com/v1beta/models", params={"key": g_key}, timeout=30, timeout=15, ) if models_resp.status_code == 200: for m in models_resp.json().get("models", []):49 unmodified lines print(f"[GEMINI MODELS] {self.gemini_flash_models}", flush=True)
if self.provider_keys.get("groq"): # Wykluczono gpt-oss-* z CodeAgent (zawsze wywołują natywne narzędzia i wywalają tool_choice=none) preferred_groq = [ "groq/moonshotai/kimi-k2-instruct", "groq/llama-3.3-70b-versatile", "groq/openai/gpt-oss-120b", "groq/qwen/qwen3-32b", "groq/qwen/qwen3.8-27b", "groq/moonshotai/kimi-k2-instruct", "groq/meta-llama/llama-4-maverick-17b-128e-instruct", "groq/meta-llama/llama-4-scout-17b-16e-instruct", "groq/openai/gpt-oss-20b", "groq/qwen/qwen3-32b", "groq/qwen/qwen3.8-27b", "groq/llama-3.1-8b-instant", ] live_groq = [] try: groq_resp = requests.get( "https://api.groq.com/openai/v1/models", headers={"Authorization": f"Bearer {self.provider_keys['groq']}"}, timeout=15, timeout=10, ) if groq_resp.status_code == 200: for item in groq_resp.json().get("data", []):3 unmodified lines for bad in ( "whisper", "tts", "orpheus", "guard", "safeguard", "embed", "compound", "allam", "gpt-oss", ) ): live_groq.append(f"groq/{g_id}")7 unmodified lines extra_groq = sorted( (m for m in live_groq if m not in curated_groq), key=lambda name: ( 0 if any(k in name.lower() for k in ("kimi", "120b", "70b", "32b", "27b")) else 1, 0 if any(k in name.lower() for k in ("kimi", "70b", "maverick", "scout", "32b", "27b")) else 1, name, ), )9 unmodified lines low = model_name.lower() key_missing = 0 if self._get_api_key(model_name) else 1
if provider == "gemini": if low == "gemini/gemini-3-flash-preview": return (key_missing, 0, 0, (0, 0), model_name) if low == "gemini/gemini-flash-latest": return (key_missing, 0, 1, (0, 0), model_name) return (key_missing, 0, 2, (0, 0), model_name)
if provider == "groq": if "llama-3.3-70b" in low or "kimi" in low: sub_rank = 0 elif "120b" in low or "70b" in low or "32b" in low or "27b" in low: elif "maverick" in low or "scout" in low: sub_rank = 1 elif "scout" in low or "maverick" in low or "20b" in low: elif "32b" in low or "27b" in low: sub_rank = 2 else: sub_rank = 3 return (key_missing, 1, sub_rank, (0, 0), model_name) return (key_missing, 0, sub_rank, (0, 0), model_name)
if provider == "gemini": if low == "gemini/gemini-3-flash-preview": return (key_missing, 1, 0, (0, 0), model_name) if low == "gemini/gemini-flash-latest": return (key_missing, 1, 1, (0, 0), model_name) return (key_missing, 1, 2, (0, 0), model_name)
if provider == "openrouter": sub_rank = priority_rank.get(model_name, len(priority_rank))41 unmodified lines call_kwargs = self._prepare_call_kwargs(dict(kwargs)) call_kwargs["num_retries"] = 0 call_kwargs["max_retries"] = 0 req_timeout = float(call_kwargs.get("timeout") or getattr(self, "timeout", None) or 45.0) hard_timeout = req_timeout + 8.0 req_timeout = float(call_kwargs.get("timeout") or getattr(self, "timeout", None) or 18.0) hard_timeout = req_timeout + 4.0 executor = ThreadPoolExecutor(max_workers=1) future = executor.submit(super().generate, *args, **call_kwargs) try:23 unmodified lines open_t = cls.open_tag close_t = cls.close_tag
# Usuń ewentualne bloki <think>...</think> przed ekstrakcją kodu text = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL | re.IGNORECASE).strip()
def _convert_xml_tool_calls(raw: str) -> str | None: qwen_calls = re.findall( r"<tool_call>\s*<function=([A-Za-z_][A-Za-z0-9_]*)>(.*?)</function>\s*</tool_call>",347 unmodified lines if isinstance(getattr(self, "kwargs", None), dict): self.kwargs["api_key"] = key
if model_name.startswith("groq/"): default_cap = 35.0 elif model_name.startswith("openrouter/"): default_cap = 35.0 else: default_cap = 38.0 default_cap = 18.0
timeout = min(float(getattr(self, "timeout", None) or default_cap), default_cap) 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(8.0, min(timeout, remaining - 2.0)) timeout = max(6.0, min(timeout, remaining - 2.0)) self.timeout = timeout if isinstance(getattr(self, "kwargs", None), dict): self.kwargs["timeout"] = timeout1 unmodified line litellm.request_timeout = timeout
if model_name.startswith("groq/"): kwargs["max_tokens"] = 2048 kwargs["max_tokens"] = 1536 if isinstance(getattr(self, "kwargs", None), dict): self.kwargs["max_tokens"] = 2048 self.kwargs["max_tokens"] = 1536 if "qwen3" in model_name.lower(): kwargs["reasoning_effort"] = "none" kwargs["reasoning_format"] = "hidden" elif "gpt-oss" in model_name.lower(): kwargs["reasoning_effort"] = "low" if model_name.startswith("gemini/"): if "gemma" not in model_name.lower(): kwargs.setdefault("reasoning_effort", "low")19 unmodified lines
def _build_model(model_name: str): api_key = self._get_api_key(model_name) common = {"num_retries": 0, "max_retries": 0, "timeout": 45} common = {"num_retries": 0, "max_retries": 0, "timeout": 18} if model_name.startswith("gemini/"): kwargs = { "model_id": model_name, "api_key": api_key, "max_tokens": 4096, "max_tokens": 2048, **common, } if "gemma" not in model_name.lower():6 unmodified lines "model_id": f"openai/{raw_hf}", "api_base": "https://router.huggingface.co/v1", "api_key": api_key, "max_tokens": 4096, "max_tokens": 2048, **common, } elif model_name.startswith("groq/") and "qwen3" in model_name.lower(): kwargs = { "model_id": model_name, "api_key": api_key, "max_tokens": 1536, "reasoning_effort": "none", "reasoning_format": "hidden", **common, } else: kwargs = { "model_id": model_name, "api_key": api_key, "max_tokens": 4096, "max_tokens": 2048, **common, } return self._model_cls(**kwargs)9 unmodified lines kw = {"model": model_name, "api_key": api_key} if model_name.startswith("gemini/"): kw["reasoning_effort"] = "low" elif model_name.startswith("groq/") and "qwen3" in model_name.lower(): kw["reasoning_effort"] = "none" kw["reasoning_format"] = "hidden" elif model_name.startswith("huggingface/"): kw = { "model": "openai/" + model_name[len("huggingface/"):],3 unmodified lines litellm.completion( **kw, messages=[{"role": "user", "content": "Reply with the single word OK."}], max_tokens=64, timeout=15, max_tokens=32, timeout=8, num_retries=0, max_retries=0, )12 unmodified lines
from concurrent.futures import ThreadPoolExecutor, wait as futures_wait
probe_targets = [m for m in self.working_models if not m.startswith("openrouter/")][:8] probe_targets = [m for m in self.working_models if not m.startswith("openrouter/")][:6] 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=20) done, _ = futures_wait(probe_futures, timeout=12) for fut in done: try: p_name, p_state, p_info = fut.result()16 unmodified lines self._sync_provider_env(prov, "")
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] untested_non_or = [ m for m in self.working_models if m not in probe_status and not m.startswith("openrouter/") ] busy_models = [m for m in self.working_models if probe_status.get(m) == "busy"] reordered = ok_models + untested + busy_models openrouter_models = [m for m in self.working_models if m.startswith("openrouter/")]
# Jeśli działają szybkie modele Groq/Gemini, nie wrzucaj wolnych modeli openrouter:free przed busy_models if ok_models: reordered = (ok_models + untested_non_or + busy_models + openrouter_models)[:4] else: reordered = (untested_non_or + openrouter_models + busy_models)[:4] if reordered: self.working_models = reordered
333 unmodified lines rem_now = deadline - step_t0 if rem_now <= 6.0: break call_timeout = max(15.0, min(55.0, rem_now - 3.0)) call_timeout = max(10.0, min(18.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",4 unmodified lines built_model.timeout = call_timeout built_model.deadline = deadline run_agent = self._create_code_agent(built_model) run_agent.max_steps = 7 if rem_now > 30.0 else 4 run_agent.max_steps = 6 if rem_now > 30.0 else 4 result = run_agent.run(prompt) print( f"[TRACE] task_id={task_id} model={model_name} "443 unmodified lines
print("Launching Gradio Interface for Basic Agent Evaluation...") demo.queue() demo.launch(debug=True, share=False) demo.launch(debug=True, share=False, ssr_mode=False)app.py+82-65