Spaces:
Runtime error
Runtime error
Update app.py
Browse files12 unmodified lines13141516171819202122232425262728293031323370 unmodified lines10410510610710810911011167 unmodified lines17918018118218318418545 unmodified lines23123223323423523623723823924087 unmodified lines328329330331332333334137 unmodified lines472473474475476477478274 unmodified lines75375475575675775875912 unmodified lines77277377477577677777817 unmodified lines7967977987998008018028 unmodified lines81181281381481581681757 unmodified lines87587687787887988088188288388488588688788888989089189230 unmodified lines923924925926927928929338 unmodified lines1268126912701271127212731274138 unmodified lines1413141414151416141714184 unmodified lines1423142414251426142714281429143014311432143319 unmodified lines14531454145514561457145814591460146153 unmodified lines151515161517151815191520152115 unmodified lines15371538153915401541154215431544154515461547154815491550155115521553155415551556155716 unmodified lines1574157515761577157815791580158115827 unmodified lines159015911592159315941595159615971598159916004 unmodified lines1605160616071608160916101611161216131614161516161617161816191620162116221623162416253 unmodified lines16291630163116321633163416351636163716381639164027 unmodified lines16681669167016711672167316741675167616771678167916801681168216833 unmodified lines16871688168916901691169216931694169516961697169816991700170117021703170417051706170710 unmodified lines17181719172017211722172317241725172617271728172917301731173 unmodified lines1905190619071908190919101911172 unmodified lines20842085208620872088208938 unmodified lines2128212921302131213221332134213521362137213821396 unmodified lines21462147214821492150215121522153215421552156215721584 unmodified lines216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218726 unmodified lines22142215221622172218221922202221222235 unmodified lines225822592260226122622263226422652266226722682269227051 unmodified lines232223232324232523262327232823298 unmodified lines23382339234023412342234322 unmodified lines23662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415337 unmodified lines275327542755275627572758275940 unmodified lines280028012802280328042805280651 unmodified lines285828592860286128622863286428656 unmodified lines287228732874287528762877287828792880288128822883288452 unmodified lines2937293829392940294129422943153 unmodified lines309730983099310031013102310312 unmodified linesexcept ImportError:pass# (Keep Constants as is)# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"# --- Basic Agent Definition ---# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------class BasicAgent:def __init__(self):import reimport base64import mimetypesimport litellmfrom smolagents import CodeAgent, LiteLLMModel, toollitellm.drop_params = Truelitellm.request_timeout = 12070 unmodified linesos.environ["HF_TOKEN"] = hf_keyos.environ["HUGGINGFACE_API_KEY"] = hf_keyimport threadingself._state_lock = threading.RLock()def _sync_provider_env(provider: str, key: str) -> None:67 unmodified linesself._rotate_api_key = _rotate_api_keyself._reset_key_indices = _reset_key_indicesself.gemini_flash_models = []@tooldef fetch_url_text(url: str) -> str:"""Fetches clean plain text from a given URL.45 unmodified linesif not clean_id:return "Error downloading file: missing task_id."os.makedirs(output_dir, exist_ok=True)safe_pref_name = os.path.basename((preferred_filename or "").strip())if safe_pref_name:cached_pref_path = os.path.join(output_dir, safe_pref_name)if os.path.isfile(cached_pref_path) and os.path.getsize(cached_pref_path) > 0:return cached_pref_path87 unmodified linesext = ext_map.get(content_type) or mimetypes.guess_extension(content_type) or ".bin"filename = f"{clean_id}{ext}"out_path = os.path.join(output_dir, filename)with open(out_path, "wb") as f:f.write(resp.content)return out_path137 unmodified linesexcept Exception as e:return f"Error reading file '{file_path}': {str(e)}"self._read_local_file = read_local_file@tooldef web_search(query: str) -> str:274 unmodified linescleaned_query = (query or "").strip()if not cleaned_query:return "Brak wyników."try:resp = requests.get(12 unmodified linesreturn "\n".join(wiki_lines)except Exception as wiki_exc:if "task time budget exhausted" in str(wiki_exc).lower():return "Brak wyników."try:ddg_resp = requests.post(17 unmodified linesexcept Exception:passreturn "Brak wyników."def _litellm_route_kwargs(model_name: str, api_key: str) -> dict:return {"model": model_name, "api_key": api_key}8 unmodified lines"quota exceeded",))@tooldef inspect_image(image_path: str, question: str) -> str:"""Analyzes a local image file using a multimodal vision model and answers a specific question about it.57 unmodified lines"openrouter/google/gemma-4-26b-a4b-it:free","openrouter/google/gemma-4-31b-it:free","openrouter/google/gemma-3-27b-it:free","openrouter/nvidia/nemotron-3.5-super-vl:free",])for m in getattr(self, "working_models", []):if m.startswith("openrouter/") and any(tag in m.lower() for tag in vision_tags):vision_candidates.append(m)if self.provider_keys.get("gemini"):vision_candidates.extend(self.gemini_flash_modelsor ["gemini/gemini-flash-latest","gemini/gemini-flash-lite-latest",])30 unmodified linescall_kwargs["num_retries"] = 0call_kwargs["max_retries"] = 0call_kwargs["max_tokens"] = 1024call_kwargs["timeout"] = _tool_timeout(22.0)if v_provider == "openrouter" or (v_provider == "gemini" and "gemma" not in v_model.lower()):call_kwargs["reasoning_effort"] = "low"338 unmodified lines]+ (self.gemini_flash_models or [])))[:3]while not video_analyzed:rate_limited_gemini = Falsefor g_model in gemini_models:138 unmodified linesif "task time budget exhausted" in str(groq_exc).lower():raisebreakwith open(audio_path, "rb") as f:b64_data = base64.b64encode(f.read()).decode("utf-8")4 unmodified linesaudio_models.extend(self.gemini_flash_modelsor ["gemini/gemini-flash-latest","gemini/gemini-flash-lite-latest",])audio_models = list(dict.fromkeys(audio_models))last_err = Nonewhile True:19 unmodified lines}],"generationConfig": {"maxOutputTokens": 2048,"thinkingConfig": {"thinkingBudget": 0},},},timeout=_tool_timeout(60.0),)53 unmodified lines"openrouter/qwen/qwen3-next-80b-a3b-instruct:free","openrouter/meta-llama/llama-3.3-70b-instruct:free","openrouter/google/gemma-3-27b-it:free","openrouter/nvidia/nemotron-3-nano-30b-a3b:free","openrouter/openrouter/free",]15 unmodified linesif live_free_models:curated_live = [m for m in priority_openrouter_models if m in live_free_models]extra_live = sorted(m for m in live_free_modelsif m not in curated_liveand not any(bad in m.lower()for bad in ("embed", "whisper", "tts", "audio", "image","550b", "ultra", "ernie", "omni", "lfm-3-1.7b",)))[:3]candidate_models.extend(curated_live or ["openrouter/openrouter/free"])candidate_models.extend(extra_live)else:candidate_models.extend(priority_openrouter_models)if self.provider_keys.get("gemini"):available_api_models = set()16 unmodified linesif not any(bad in low_idfor bad in ("2.5-flash","3.1-flash-lite","3.5-flash-lite","tts","image","imagen",7 unmodified lines"omni","exp","thinking","gemma-1","gemma-2","gemma-3-1b","gemma-3-4b","gemma-3-12b",)):available_api_models.add(full_id)4 unmodified linesif available_api_models:discovered_flash = sorted((m for m in available_api_models if "flash" in m.lower() or "gemma" in m.lower()),key=lambda name: (0 if name.lower() == "gemini/gemini-flash-latest" else 1,1 if "gemma" in name.lower() else 0,1 if "flash-lite" in name.lower() else 0,1 if "preview" in name.lower() else 0,name,),)self.gemini_flash_models = (discovered_flash or sorted(available_api_models))[:6]candidate_models.extend(self.gemini_flash_models)else:self.gemini_flash_models = ["gemini/gemini-flash-latest","gemini/gemini-flash-lite-latest",]candidate_models.extend(self.gemini_flash_models)print(f"[GEMINI MODELS] {self.gemini_flash_models}", flush=True)3 unmodified lines"groq/moonshotai/kimi-k2-instruct","groq/llama-3.3-70b-versatile","groq/openai/gpt-oss-120b","groq/meta-llama/llama-4-maverick-17b-128e-instruct","groq/meta-llama/llama-4-scout-17b-16e-instruct","groq/qwen/qwen3-32b","groq/qwen/qwen3.8-27b","groq/openai/gpt-oss-20b","groq/llama-3.1-8b-instant",]live_groq = []try:27 unmodified linesname,),)selected_groq = list(dict.fromkeys(curated_groq + extra_groq))candidate_models.extend(selected_groq)else:candidate_models.extend(preferred_groq)if self.provider_keys.get("huggingface"):candidate_models.extend(["huggingface/Qwen/Qwen2.5-72B-Instruct","huggingface/meta-llama/Llama-3.3-70B-Instruct",])priority_rank = {name: idx for idx, name in enumerate(priority_openrouter_models)}3 unmodified lineskey_missing = 0 if self._get_api_key(model_name) else 1if provider == "gemini":is_lite = "flash-lite" in lowis_preview = 1 if "preview" in low else 0ver_match = re.search(r"gemini-(\d+)(?:\.(\d+))?", low)major = int(ver_match.group(1)) if ver_match else 0minor = int(ver_match.group(2)) if (ver_match and ver_match.group(2)) else 0if low == "gemini/gemini-flash-latest":return (key_missing, 0, 0, (0, 0), model_name)if not is_lite and "flash" in low:return (key_missing, 0, 1 + is_preview, (-major, -minor), model_name)if low == "gemini/gemini-flash-lite-latest":return (key_missing, 0, 3, (0, 0), model_name)if is_lite:return (key_missing, 0, 4 + is_preview, (-major, -minor), model_name)return (key_missing, 0, 6 + is_preview, (-major, -minor), model_name)if provider == "groq":if "llama-3.3-70b" in low or "kimi" in low:10 unmodified linessub_rank = priority_rank.get(model_name, len(priority_rank))return (key_missing, 2, sub_rank, (0, 0), model_name)sub_rank = 0 if "72b" in low else 1return (key_missing, 3, sub_rank, (0, 0), model_name)self.working_models = sorted(dict.fromkeys(candidate_models),key=_model_priority,)if not self.working_models:raise RuntimeError("No models available for the configured API keys.")173 unmodified linesstripped_orphan_tags = re.sub(r"</?code[^>]*>", "", cleaned_text, flags=re.IGNORECASE).strip()if stripped_orphan_tags != cleaned_text.strip() and stripped_orphan_tags:return f"{open_t}\n{_extract_valid_python(stripped_orphan_tags)}\n{close_t}"if "final_answer(" in cleaned_text:extracted = _extract_valid_python(cleaned_text)172 unmodified linesf"final_answer({json.dumps(ans_val, ensure_ascii=False)})\n"f"{cls.close_tag}")if not cleaned.strip():raise RuntimeError(38 unmodified linesself.api_key = keyif isinstance(getattr(self, "kwargs", None), dict):self.kwargs["api_key"] = keyif model_name.startswith("groq/"):default_cap = 14.0elif model_name.startswith("openrouter/"):default_cap = 16.0else:default_cap = 24.0timeout = min(float(getattr(self, "timeout", None) or default_cap), default_cap)task_deadline = getattr(self, "deadline", None)if task_deadline is not None:6 unmodified linesself.kwargs["timeout"] = timeoutkwargs["timeout"] = timeoutlitellm.request_timeout = timeoutif model_name.startswith("groq/"):kwargs["max_tokens"] = 1536if isinstance(getattr(self, "kwargs", None), dict):self.kwargs["max_tokens"] = 1536if "qwen3" in model_name.lower():kwargs.setdefault("reasoning_effort", "none")kwargs.setdefault("reasoning_format", "hidden")if model_name.startswith("gemini/"):if "gemma" not in model_name.lower():kwargs.setdefault("reasoning_effort", "low")4 unmodified linesif isinstance(getattr(self, "kwargs", None), dict):self.kwargs.pop("temperature", None)if model_name.startswith("openrouter/"):kwargs["max_tokens"] = 1024if isinstance(getattr(self, "kwargs", None), dict):self.kwargs["max_tokens"] = 1024kwargs["reasoning_effort"] = "low"kwargs["num_retries"] = 0kwargs["max_retries"] = 0if "gpt-oss" in model_name.lower() and model_name.startswith("groq/"):tool_schemas = getattr(self, "_groq_tool_schemas", None)if tool_schemas:kwargs["tools"] = tool_schemaskwargs["tool_choice"] = "auto"else:kwargs.pop("tools", None)kwargs.pop("tool_choice", None)else:kwargs.pop("tools", None)kwargs.pop("tool_choice", None)return kwargsself._model_cls = SafeLiteLLMModeldef _build_model(model_name: str):26 unmodified lines"max_tokens": 4096,**common,}built = self._model_cls(**kwargs)built._groq_tool_schemas = getattr(self, "_groq_tool_schemas", None)return builtdef _probe_candidate(model_name: str) -> tuple[str, str, str]:import time35 unmodified linesfrom 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/")][:16]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()51 unmodified lines"- Do not wrap the answer in a dictionary like {'answer': ...}; pass the plain answer string directly.")from smolagents import MultiStepAgentaccepted_params = set(sig.parameters) | set(inspect.signature(MultiStepAgent.__init__).parameters)agent_kwargs = {"tools": [8 unmodified linestranscribe_audio,],"additional_authorized_imports": ["json","csv","pandas",22 unmodified lines"verbosity_level": 0,}def _build_openai_tool_schemas(tool_list) -> list[dict]:schemas = []for t_obj in tool_list:t_name = getattr(t_obj, "name", None) or getattr(t_obj, "__name__", "")raw_doc = getattr(t_obj, "description", None) or getattr(t_obj, "__doc__", "") or t_namet_desc = raw_doc.strip().splitlines()[0]t_inputs = getattr(t_obj, "inputs", None) or {}props = {}req = []for p_name, p_meta in t_inputs.items():p_type = str(p_meta.get("type", "string")).lower() if isinstance(p_meta, dict) else "string"if p_type not in {"string", "integer", "number", "boolean", "array", "object"}:p_type = "string"p_desc = str(p_meta.get("description", p_name)) if isinstance(p_meta, dict) else p_nameprops[p_name] = {"type": p_type, "description": p_desc}if not (isinstance(p_meta, dict) and p_meta.get("nullable")):req.append(p_name)if t_name:schemas.append({"type": "function","function": {"name": t_name,"description": t_desc[:200],"parameters": {"type": "object","properties": props,"required": req,},},})return schemasself._groq_tool_schemas = _build_openai_tool_schemas([web_search,search_wikipedia,ask_web,fetch_url_text,download_task_file,read_local_file,inspect_image,inspect_youtube,transcribe_audio,])def _create_code_agent(model_instance):def _step_guard(step_log, *args, **kwargs):llm_err = getattr(model_instance, "_last_llm_error", None)337 unmodified lines)):blocked_models.add(model_name)self._model_cooldowns[model_name] = time.monotonic() + 180.0breakis_context_overflow = any(marker in err_lower40 unmodified lines)):blocked_models.add(model_name)self._model_cooldowns[model_name] = time.monotonic() + 180.0breakif "connection error" in err_lower:if transient_retries < 1 and (deadline - time.monotonic()) > 10.0:51 unmodified linesFetches all questions, runs the BasicAgent on them, submits all answers,and displays the results."""# --- Determine HF Space Runtime URL and Repo URL ---space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the codeif profile:username = f"{profile.username}"6 unmodified linesquestions_url = f"{api_url}/questions"submit_url = f"{api_url}/submit"# 1. Instantiate Agent ( modify this part to create your agent)try:agent = BasicAgent()except Exception as e:print(f"Error instantiating agent: {e}")return f"Error initializing agent: {e}", None# In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)agent_code = (f"https://huggingface.co/spaces/{space_id.strip()}/tree/main"if space_id and space_id.strip()52 unmodified linesreturn "Fetched questions list is empty or invalid format.", Noneprint(f"Fetched {len(questions_data)} questions.")# 3. Run your Agentfrom concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeoutErrorimport jsonimport time153 unmodified linesrun_button = gr.Button("Run Evaluation & Submit All Answers")status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)# Removed max_rows=10 from DataFrame constructorresults_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)run_button.click(12 unmodified lines131415161718192021222324252627282930313270 unmodified lines10310410510610710867 unmodified lines17617717817918018118245 unmodified lines22822923023123223323423523623723887 unmodified lines326327328329330331332137 unmodified lines470471472473474475476274 unmodified lines75175275375475575675712 unmodified lines77077177277377477577617 unmodified lines7947957967977987998008 unmodified lines80981081181281381481557 unmodified lines87387487587687787887988088188288388488588630 unmodified lines917918919920921922923338 unmodified lines1262126312641265126612671268138 unmodified lines14071408140914101411141214134 unmodified lines1418141914201421142214231424142514261427142819 unmodified lines14481449145014511452145314541455145653 unmodified lines15101511151215131514151515 unmodified lines15311532153315341535153615371538153916 unmodified lines1556155715581559156015617 unmodified lines156915701571157215731574157515764 unmodified lines158115821583158415851586158715881589159015911592159315941595159615971598159916003 unmodified lines1604160516061607160816091610161116121613161427 unmodified lines16421643164416451646164716481649165016513 unmodified lines1655165616571658165916601661166216631664166510 unmodified lines1676167716781679168016811682168316841685168616871688173 unmodified lines18621863186418651866186718681869187018711872187318741875187618771878172 unmodified lines20512052205320542055205620572058205920602061206238 unmodified lines210121022103210421052106210721082109211021112112211321146 unmodified lines21212122212321242125212621272128212921302131213221332134213521364 unmodified lines2141214221432144214521462147214821492150215121522153215421552156215726 unmodified lines218421852186218721882189219035 unmodified lines22262227222822292230223122322233223422352236223751 unmodified lines2289229022912292229322948 unmodified lines2303230423052306230723082309231022 unmodified lines233323342335233623372338337 unmodified lines267626772678267926802681268240 unmodified lines272327242725272627272728272951 unmodified lines27812782278327842785278627876 unmodified lines279427952796279727982799280028012802280328042805280652 unmodified lines2859286028612862286328642865153 unmodified lines30193020302130223023302412 unmodified linesexcept ImportError:pass# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"# --- Basic Agent Definition ---class BasicAgent:def __init__(self):import reimport base64import mimetypesimport threadingimport litellmfrom smolagents import CodeAgent, LiteLLMModel, MultiStepAgent, toollitellm.drop_params = Truelitellm.request_timeout = 12070 unmodified linesos.environ["HF_TOKEN"] = hf_keyos.environ["HUGGINGFACE_API_KEY"] = hf_keyself._state_lock = threading.RLock()def _sync_provider_env(provider: str, key: str) -> None:67 unmodified linesself._rotate_api_key = _rotate_api_keyself._reset_key_indices = _reset_key_indicesself.gemini_flash_models = []@tooldef fetch_url_text(url: str) -> str:"""Fetches clean plain text from a given URL.45 unmodified linesif not clean_id:return "Error downloading file: missing task_id."safe_out_dir = (output_dir or "").strip() or "/tmp/gaia_files"os.makedirs(safe_out_dir, exist_ok=True)safe_pref_name = os.path.basename((preferred_filename or "").strip())if safe_pref_name:cached_pref_path = os.path.join(safe_out_dir, safe_pref_name)if os.path.isfile(cached_pref_path) and os.path.getsize(cached_pref_path) > 0:return cached_pref_path87 unmodified linesext = ext_map.get(content_type) or mimetypes.guess_extension(content_type) or ".bin"filename = f"{clean_id}{ext}"out_path = os.path.join(safe_out_dir, filename)with open(out_path, "wb") as f:f.write(resp.content)return out_path137 unmodified linesexcept Exception as e:return f"Error reading file '{file_path}': {str(e)}"self._read_local_file = read_local_file@tooldef web_search(query: str) -> str:274 unmodified linescleaned_query = (query or "").strip()if not cleaned_query:return "No results."try:resp = requests.get(12 unmodified linesreturn "\n".join(wiki_lines)except Exception as wiki_exc:if "task time budget exhausted" in str(wiki_exc).lower():return "No results."try:ddg_resp = requests.post(17 unmodified linesexcept Exception:passreturn "No results."def _litellm_route_kwargs(model_name: str, api_key: str) -> dict:return {"model": model_name, "api_key": api_key}8 unmodified lines"quota exceeded",))@tooldef inspect_image(image_path: str, question: str) -> str:"""Analyzes a local image file using a multimodal vision model and answers a specific question about it.57 unmodified lines"openrouter/google/gemma-4-26b-a4b-it:free","openrouter/google/gemma-4-31b-it:free","openrouter/google/gemma-3-27b-it:free",])if self.provider_keys.get("gemini"):vision_candidates.extend(self.gemini_flash_modelsor ["gemini/gemini-3-flash-preview","gemini/gemini-flash-latest",])30 unmodified linescall_kwargs["num_retries"] = 0call_kwargs["max_retries"] = 0call_kwargs["max_tokens"] = 1024call_kwargs["timeout"] = _tool_timeout(28.0)if v_provider == "openrouter" or (v_provider == "gemini" and "gemma" not in v_model.lower()):call_kwargs["reasoning_effort"] = "low"338 unmodified lines]+ (self.gemini_flash_models or [])))[:2]while not video_analyzed:rate_limited_gemini = Falsefor g_model in gemini_models:138 unmodified linesif "task time budget exhausted" in str(groq_exc).lower():raisebreakwith open(audio_path, "rb") as f:b64_data = base64.b64encode(f.read()).decode("utf-8")4 unmodified linesaudio_models.extend(self.gemini_flash_modelsor ["gemini/gemini-3-flash-preview","gemini/gemini-flash-latest",])audio_models = list(dict.fromkeys(audio_models))[:2]last_err = Nonewhile True:19 unmodified lines}],"generationConfig": {"maxOutputTokens": 2048,"thinkingConfig": {"thinkingBudget": 0},},},timeout=_tool_timeout(60.0),)53 unmodified lines"openrouter/qwen/qwen3-next-80b-a3b-instruct:free","openrouter/meta-llama/llama-3.3-70b-instruct:free","openrouter/google/gemma-3-27b-it:free","openrouter/openrouter/free",]15 unmodified linesif 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"])else:candidate_models.extend(priority_openrouter_models[:3])if self.provider_keys.get("gemini"):available_api_models = set()16 unmodified linesif not any(bad in low_idfor bad in ("tts","image","imagen",7 unmodified lines"omni","exp","thinking","gemma","flash-lite",)):available_api_models.add(full_id)4 unmodified linesif available_api_models:discovered_flash = sorted((m for m in available_api_models if "flash" in m.lower()),key=lambda name: (0 if name.lower() == "gemini/gemini-3-flash-preview" else 1,0 if name.lower() == "gemini/gemini-flash-latest" else 1,0 if name.lower() == "gemini/gemini-2.5-flash" else 1,name,),)self.gemini_flash_models = (discovered_flash or sorted(available_api_models))[:2]candidate_models.extend(self.gemini_flash_models)else:self.gemini_flash_models = ["gemini/gemini-3-flash-preview","gemini/gemini-flash-latest",]candidate_models.extend(self.gemini_flash_models)print(f"[GEMINI MODELS] {self.gemini_flash_models}", flush=True)3 unmodified lines"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/meta-llama/llama-4-maverick-17b-128e-instruct","groq/meta-llama/llama-4-scout-17b-16e-instruct","groq/openai/gpt-oss-20b",]live_groq = []try:27 unmodified linesname,),)selected_groq = list(dict.fromkeys(curated_groq + extra_groq))[:4]candidate_models.extend(selected_groq)else:candidate_models.extend(preferred_groq[:4])priority_rank = {name: idx for idx, name in enumerate(priority_openrouter_models)}3 unmodified lineskey_missing = 0 if self._get_api_key(model_name) else 1if 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:10 unmodified linessub_rank = priority_rank.get(model_name, len(priority_rank))return (key_missing, 2, sub_rank, (0, 0), model_name)return (key_missing, 3, 0, (0, 0), model_name)self.working_models = sorted(dict.fromkeys(candidate_models),key=_model_priority,)if not self.working_models:raise RuntimeError("No models available for the configured API keys.")173 unmodified linesstripped_orphan_tags = re.sub(r"</?code[^>]*>", "", cleaned_text, flags=re.IGNORECASE).strip()if stripped_orphan_tags != cleaned_text.strip() and stripped_orphan_tags:extracted_orphan = _extract_valid_python(stripped_orphan_tags)try:ast.parse(extracted_orphan)return f"{open_t}\n{extracted_orphan}\n{close_t}"except SyntaxError:if len(stripped_orphan_tags) <= 300 and "\n" not in stripped_orphan_tags:return (f"{open_t}\n"f"final_answer({json.dumps(stripped_orphan_tags, ensure_ascii=False)})\n"f"{close_t}")if "final_answer(" in cleaned_text:extracted = _extract_valid_python(cleaned_text)172 unmodified linesf"final_answer({json.dumps(ans_val, ensure_ascii=False)})\n"f"{cls.close_tag}")elif len(cleaned.strip()) <= 250 and "\n" not in cleaned.strip():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(38 unmodified linesself.api_key = keyif isinstance(getattr(self, "kwargs", None), dict):self.kwargs["api_key"] = keyif model_name.startswith("groq/"):default_cap = 35.0elif model_name.startswith("openrouter/"):default_cap = 35.0else:default_cap = 38.0timeout = min(float(getattr(self, "timeout", None) or default_cap), default_cap)task_deadline = getattr(self, "deadline", None)if task_deadline is not None:6 unmodified linesself.kwargs["timeout"] = timeoutkwargs["timeout"] = timeoutlitellm.request_timeout = timeoutif model_name.startswith("groq/"):kwargs["max_tokens"] = 2048if isinstance(getattr(self, "kwargs", None), dict):self.kwargs["max_tokens"] = 2048if "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")4 unmodified linesif isinstance(getattr(self, "kwargs", None), dict):self.kwargs.pop("temperature", None)if model_name.startswith("openrouter/"):kwargs["max_tokens"] = 1536if isinstance(getattr(self, "kwargs", None), dict):self.kwargs["max_tokens"] = 1536kwargs["reasoning_effort"] = "low"kwargs["num_retries"] = 0kwargs["max_retries"] = 0kwargs.pop("tools", None)kwargs.pop("tool_choice", None)return kwargsself._model_cls = SafeLiteLLMModeldef _build_model(model_name: str):26 unmodified lines"max_tokens": 4096,**common,}return self._model_cls(**kwargs)def _probe_candidate(model_name: str) -> tuple[str, str, str]:import time35 unmodified linesfrom concurrent.futures import ThreadPoolExecutor, wait as futures_waitprobe_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=20)for fut in done:try:p_name, p_state, p_info = fut.result()51 unmodified lines"- Do not wrap the answer in a dictionary like {'answer': ...}; pass the plain answer string directly.")accepted_params = set(sig.parameters) | set(inspect.signature(MultiStepAgent.__init__).parameters)agent_kwargs = {"tools": [8 unmodified linestranscribe_audio,],"additional_authorized_imports": ["os","pathlib","json","csv","pandas",22 unmodified lines"verbosity_level": 0,}def _create_code_agent(model_instance):def _step_guard(step_log, *args, **kwargs):llm_err = getattr(model_instance, "_last_llm_error", None)337 unmodified lines)):blocked_models.add(model_name)self._model_cooldowns[model_name] = time.monotonic() + 60.0breakis_context_overflow = any(marker in err_lower40 unmodified lines)):blocked_models.add(model_name)self._model_cooldowns[model_name] = time.monotonic() + 60.0breakif "connection error" in err_lower:if transient_retries < 1 and (deadline - time.monotonic()) > 10.0:51 unmodified linesFetches all questions, runs the BasicAgent on them, submits all answers,and displays the results."""space_id = os.getenv("SPACE_ID")if profile:username = f"{profile.username}"6 unmodified linesquestions_url = f"{api_url}/questions"submit_url = f"{api_url}/submit"# 1. Instantiate Agenttry:agent = BasicAgent()except Exception as e:print(f"Error instantiating agent: {e}")return f"Error initializing agent: {e}", Noneagent_code = (f"https://huggingface.co/spaces/{space_id.strip()}/tree/main"if space_id and space_id.strip()52 unmodified linesreturn "Fetched questions list is empty or invalid format.", Noneprint(f"Fetched {len(questions_data)} questions.")# 3. Run Agentfrom concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeoutErrorimport jsonimport time153 unmodified linesrun_button = gr.Button("Run Evaluation & Submit All Answers")status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)run_button.click(
app.py+87-166