Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files951 unmodified lines9529539549559569579584 unmodified lines96396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112951 unmodified linesdef __call__(self, question: str, task_id: str = "") -> str:import timefrom smolagents import LiteLLMModelprompt = question.strip()if task_id:4 unmodified linesmodels_to_try = list(getattr(self, "working_models", []) or [self.model_id])if self.model_id not in models_to_try:models_to_try.insert(0, self.model_id)max_attempts = min(max(3, len(models_to_try)), 5)model_cls = getattr(self, "_model_cls", LiteLLMModel)output_error_markers = ("error in generating model output","empty model response","error in code parsing","expected string or bytes-like object","reached max steps","tool_use_failed",)exception_error_markers = output_error_markers + ("authenticationerror","401","402","403","429","404","notfounderror","permission","does not have sufficient permissions","ratelimiterror","resource_exhausted","quota","too many requests","503","overloaded","temporarily unavailable","timeout","timed out",)permanent_model_markers = ("401","402","403","404","authenticationerror","notfounderror","permission","does not have sufficient permissions",)provider_limit_markers = ("429","503","overloaded","temporarily unavailable","ratelimiterror","resource_exhausted","quota","too many requests",)fast_retry_markers = permanent_model_markers + ("empty model response","error in code parsing","expected string or bytes-like object","reached max steps","tool_use_failed",)for attempt in range(max_attempts):step_start = time.monotonic()try:result = self.agent.run(prompt)raw_text = "" if result is None else str(result).strip()raw_lower = raw_text.lower()if any(marker in raw_lower for marker in output_error_markers):raise RuntimeError(raw_text)return self._clean_exact_match_answer(raw_text)except Exception as exc:elapsed = time.monotonic() - step_starterr_lower = str(exc).lower()is_recoverable = any(marker in err_lower for marker in exception_error_markers)print(f"[AGENT ERROR] task_id={task_id} model={self.model_id} "f"elapsed={elapsed:.1f}s (attempt {attempt + 1}/{max_attempts}): {exc}")if not is_recoverable or attempt == max_attempts - 1:return f"AGENT ERROR: {exc}"failed_model = self.model_idis_permanent = any(m in err_lower for m in permanent_model_markers)is_rate_limited = any(m in err_lower for m in provider_limit_markers)is_empty_or_parse = any(m in err_lowerfor m in ("empty model response", "error in code parsing", "tool_use_failed"))if len(models_to_try) > 1:models_to_try = [m for m in models_to_try if m != failed_model]if (is_permanent or is_empty_or_parse) and hasattr(self, "working_models") and len(self.working_models) > 1:self.working_models = [m for m in self.working_models if m != failed_model]print(f"Removed problematic model '{failed_model}' from working_models.")current_provider = (failed_model.split("/", 1)[0].lower()if "/" in failed_modelelse "gemini")switched_provider = Falseif models_to_try:other_provider_models = [mfor m in models_to_tryif (m.split("/", 1)[0].lower() if "/" in m else "gemini") != current_provider]if other_provider_models and (is_permanent or is_rate_limited):next_model = other_provider_models[0]else:next_model = models_to_try[0]new_provider = (next_model.split("/", 1)[0].lower()if "/" in next_modelelse "gemini")switched_provider = new_provider != current_providerself.model_id = next_modelbuild_fn = getattr(self, "_build_model", None)if callable(build_fn):self.agent.model = build_fn(self.model_id)else:model_kwargs = {"model_id": self.model_id,"api_key": self._get_api_key(self.model_id),"max_tokens": 8192,"num_retries": 0,"timeout": 45,}if self.model_id.startswith("gemini/"):model_kwargs["reasoning_effort"] = "low"self.agent.model = model_cls(**model_kwargs)print(f"Switched model to {self.model_id}.")if switched_provider or any(m in err_lower for m in fast_retry_markers):wait_sec = 1else:wait_sec = 4print(f"Sleeping {wait_sec}s before next attempt...")time.sleep(wait_sec)return "AGENT ERROR: Max retries exceeded."def run_and_submit_all(profile: gr.OAuthProfile | None):951 unmodified lines9529539549559569579584 unmodified lines9639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006951 unmodified linesdef __call__(self, question: str, task_id: str = "") -> str:import timeimport litellmprompt = question.strip()if task_id:4 unmodified linesmodels_to_try = list(getattr(self, "working_models", []) or [self.model_id])if self.model_id not in models_to_try:models_to_try.append(self.model_id)for model_name in models_to_try:api_key = self._get_api_key(model_name) if hasattr(self, "_get_api_key") else Noneif not api_key:continuefor attempt in range(2):try:response = litellm.completion(model=model_name,api_key=api_key,messages=[{"role": "system","content": ("Answer with ONLY the concise exact answer value itself. ""No explanation, no markdown, no prefix."),},{"role": "user", "content": prompt},],max_tokens=512,timeout=25,)content = (response.choices[0].message.content or "").strip()if content:self.model_id = model_namereturn self._clean_exact_match_answer(content)except Exception as exc:print(f"[DIRECT FALLBACK] task_id={task_id} model={model_name} attempt={attempt + 1}: {exc}")if attempt == 0:time.sleep(1.5)try:result = self.agent.run(prompt)return self._clean_exact_match_answer("" if result is None else str(result).strip())except Exception as exc:return f"AGENT ERROR: {exc}"def run_and_submit_all(profile: gr.OAuthProfile | None):
app.py+36-142