Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files832 unmodified lines833834835836837837838839840841842843844845846847848849850851852853854855856857858859860861838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883863864865866867868869870871872873874875876877878879880881882883884885884885886886887888889890891892893894895896897887899900888889902903904905906907908909910911890891892893894895896897898899900901902903904905906907868 unmodified lines177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180081 unmodified lines18821883188418731885188618871888188918901891183 unmodified lines20752076207720782079208020815 unmodified lines2087208820892090209120922093125 unmodified lines22192220222122072208220922102211221222132214221522162217221822192220222122222223222422252222222322244 unmodified lines22292230223122322233223422352236223722382239223922402241224222432244224522462247224822492250225122402241224226 unmodified lines226922702271228422722273227422751 unmodified line2277227822792292228022812282228393 unmodified lines23772378237923802381238223832384832 unmodified lines
unique_vision = list(dict.fromkeys(vision_candidates)) last_err = None rate_limited_providers = set()
while True: rate_limited_providers = set() for v_model in unique_vision: v_provider = v_model.split("/", 1)[0].lower() if "/" in v_model else "gemini" while True: v_key = self._get_api_key(v_model) if not v_key: break try: response = litellm.completion( **_litellm_route_kwargs(v_model, v_key), messages=[ { "role": "user", "content": [ {"type": "text", "text": question}, { "type": "image_url", "image_url": {"url": f"data:{mime_type};base64,{b64_data}"}, }, ], } ], max_tokens=2048, timeout=_tool_timeout(45.0), for v_model in unique_vision: v_provider = v_model.split("/", 1)[0].lower() if "/" in v_model else "gemini" if v_provider in rate_limited_providers: continue while True: v_key = self._get_api_key(v_model) if not v_key: break try: response = litellm.completion( **_litellm_route_kwargs(v_model, v_key), messages=[ { "role": "user", "content": [ {"type": "text", "text": question}, { "type": "image_url", "image_url": {"url": f"data:{mime_type};base64,{b64_data}"}, }, ], } ], max_tokens=2048, timeout=_tool_timeout(45.0), ) out = (response.choices[0].message.content or "").strip() if out: return out break except Exception as exc: last_err = exc err_low = str(exc).lower() if "task time budget exhausted" in err_low: raise if any( marker in err_low for marker in ( "401", "402", "403", "authentication", "missing authentication header", "insufficient permissions", "does not have sufficient permissions", ) out = (response.choices[0].message.content or "").strip() if out: return out break except Exception as exc: last_err = exc err_low = str(exc).lower() if "task time budget exhausted" in err_low: raise if any( marker in err_low for marker in ( "401", "402", "403", "authentication", "missing authentication header", "insufficient permissions", "does not have sufficient permissions", ) ): if hasattr(self, "_rotate_api_key") and self._rotate_api_key( v_provider, permanent=True ): if hasattr(self, "_rotate_api_key") and self._rotate_api_key( v_provider, permanent=True ): continue break if any( marker in err_low for marker in ( "429", "rate limit", "free-models-per-day", "quota", "resource_exhausted", ) ): rate_limited_providers.add(v_provider) break continue break
rotated_any = False if hasattr(self, "_rotate_api_key"): for prov in rate_limited_providers: pool = self.provider_key_pools.get(prov) or [] if self._provider_key_idx.get(prov, 0) + 1 < len(pool): if self._rotate_api_key(prov): rotated_any = True if not rotated_any: break if any( marker in err_low for marker in ( "429", "rate limit", "free-models-per-day", "quota", "resource_exhausted", ) ): if hasattr(self, "_rotate_api_key") and self._rotate_api_key(v_provider): continue rate_limited_providers.add(v_provider) break break
raise RuntimeError(str(last_err) if last_err else "No vision model available.") except Exception as e:868 unmodified lines )
cleaned = cls._sanitize_code_tags(content_str) if cls.open_tag not in cleaned and cls.close_tag not in cleaned: fa_direct = re.findall( r"(?im)^\s*(?:final\s*answer|answer)\s*:\s*(.+)$", cleaned, ) if fa_direct and fa_direct[-1].strip(): ans_val = fa_direct[-1].strip() cleaned = ( f"{cls.open_tag}\n" f"final_answer({json.dumps(ans_val, ensure_ascii=False)})\n" f"{cls.close_tag}" ) elif len(cleaned.splitlines()) == 1 and len(cleaned) <= 200: cleaned = ( f"{cls.open_tag}\n" f"final_answer({json.dumps(cleaned.strip(), ensure_ascii=False)})\n" f"{cls.close_tag}" )
if not cleaned.strip(): raise RuntimeError( "Error in generating model output: empty model response after sanitization"81 unmodified lines "api_key": api_key, "max_tokens": 8192, "temperature": 0.1, "reasoning_effort": "low", **common, } if "2.5" in raw_gemini or "3" in raw_gemini: kwargs["reasoning_effort"] = "low" elif model_name.startswith("huggingface/"): raw_hf = model_name[len("huggingface/"):] kwargs = {183 unmodified lines if not text or text.startswith("AGENT ERROR:"): return text
text = re.sub(r"</?code[^>]*>", "", text, flags=re.IGNORECASE).strip() text = re.sub(r"^```(?:[a-zA-Z0-9_-]+)?\s*\n?", "", text) text = re.sub(r"\n?```\s*$", "", text).strip()
5 unmodified lines if lines: text = lines[-1]
text = re.sub(r"</?code[^>]*>", "", text, flags=re.IGNORECASE).strip() text = re.sub(r"^\*\*(.+?)\*\*$", r"\1", text).strip()
if len(text) >= 2 and ((text[0] == '"' and text[-1] == '"') or (text[0] == "'" and text[-1] == "'")):125 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( marker in err_lower for marker in ( "401", "402", "403", "authentication", "missing authentication header", "insufficient permissions", "does not have sufficient permissions", ) ): if hasattr(self, "_rotate_api_key") and self._rotate_api_key( provider, permanent=True ): continue blocked_providers.add(provider) blocked_models.add(model_name) break if any( marker in err_lower for marker in (4 unmodified lines "rate limit exceeded", ) ): if hasattr(self, "_rotate_api_key") and self._rotate_api_key(provider): continue for m in models_to_try: if m.startswith(f"{provider}/"): rate_limited_models.add(m) rate_limited_models.add(model_name) rate_limited_providers.add(provider) break if any( marker in err_lower for marker in ( "502", "503", "504", "unavailable", "high demand", "overloaded", ) ): rate_limited_models.add(model_name) break if any( marker in err_lower for marker in (26 unmodified lines rotated_any = True if not rotated_any: rem_after_pass = deadline - time.monotonic() if rate_limited_models and backoff_rounds < 2 and rem_after_pass > 15.0: if rate_limited_models and backoff_rounds < 1 and rem_after_pass > 20.0: backoff_rounds += 1 for prov in rate_limited_providers: if prov not in blocked_providers:1 unmodified line self._provider_key_idx[prov] = 0 if hasattr(self, "_sync_provider_env"): self._sync_provider_env(prov, pool[0] if pool else "") time.sleep(min(3.0 * backoff_rounds, max(0.5, rem_after_pass - 10.0))) time.sleep(min(10.0, max(2.0, rem_after_pass - 12.0))) continue break finally:93 unmodified lines isinstance(c_ans, str) and c_ans.strip() and not c_ans.strip().startswith("AGENT ERROR:") and "</code>" not in c_ans.lower() and "without access to" not in c_ans.lower() ): clean_cached = c_ans.strip() if isinstance(c_tid, str) and c_tid.strip():app.py+97-107