Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files12 unmodified lines13141516161718192022212223242526272930282930313270 unmodified lines10310410510710810610710867 unmodified lines17617717818217918018118245 unmodified lines22822923023123423223323423723523623723887 unmodified lines326327328331329330331332137 unmodified lines470471472475473474475476274 unmodified lines75175275375675475575675712 unmodified lines77077177277577377477577617 unmodified lines7947957967997977987998008 unmodified lines80981081181481281381481557 unmodified lines87387487587887688088188287787887988088188288388988488588630 unmodified lines917918919926920921922923338 unmodified lines12621263126412711265126612671268138 unmodified lines14071408140914101411141214134 unmodified lines141814191420142114221427142314241430142514261427142819 unmodified lines14481449145014561457145814511452145314541455145653 unmodified lines151015111512151815131514151515 unmodified lines1531153215331540154115421543154415451546154715481549155015511534155215351554153615371538153916 unmodified lines1556155715581577157815791559156015617 unmodified lines15691570157115931594159515961597157215731574157515764 unmodified lines158115821583160815841585158615871611161216131588158915901591161715921593159415951596159716221598159916003 unmodified lines1604160516061632163316071608160916101611163716121613161427 unmodified lines1642164316441671164516461647167416751676167716781679168016481649165016513 unmodified lines165516561657169016911692169316941695169616581659169816991700170117021703170416601661166216631664166510 unmodified lines1676167716781721172216791680168116821683168417281685168616871688173 unmodified lines186218631864190818651866186718681869187018711872187318741875187618771878172 unmodified lines20512052205320542055205620572058205920602061206238 unmodified lines210121022103210421052132210621072134210821092136211021112112211321146 unmodified lines212121222123212421252150212621272152212821292154215521302131213221332134213521364 unmodified lines214121422143216621442145216821462147214821492150217221732174217521762177217821792151215221802181218221532184215421552156215726 unmodified lines218421852186221722182219218721882189219035 unmodified lines22262227222822612262222922302231223222332267223422352236223751 unmodified lines228922902291232523262292229322948 unmodified lines2303230423052306230723082309231022 unmodified lines23332334233523692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412233623372338337 unmodified lines2676267726782756267926802681268240 unmodified lines2723272427252803272627272728272951 unmodified lines2781278227832861286227842785278627876 unmodified lines27942795279628752797279827992800280128022881280328042805280652 unmodified lines28592860286129402862286328642865153 unmodified lines301930203021310030223023302412 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 re import base64 import mimetypes import threading import litellm from smolagents import CodeAgent, LiteLLMModel, tool from smolagents import CodeAgent, LiteLLMModel, MultiStepAgent, tool
litellm.drop_params = True litellm.request_timeout = 120
70 unmodified lines os.environ["HF_TOKEN"] = hf_key os.environ["HUGGINGFACE_API_KEY"] = hf_key
import threading
self._state_lock = threading.RLock()
def _sync_provider_env(provider: str, key: str) -> None:67 unmodified lines self._rotate_api_key = _rotate_api_key self._reset_key_indices = _reset_key_indices self.gemini_flash_models = []
@tool def fetch_url_text(url: str) -> str: """Fetches clean plain text from a given URL.45 unmodified lines if not clean_id: return "Error downloading file: missing task_id."
safe_out_dir = (output_dir or "").strip() or "/tmp/gaia_files" os.makedirs(output_dir, exist_ok=True) 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(output_dir, 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_path
87 unmodified lines ext = 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) out_path = os.path.join(safe_out_dir, filename) with open(out_path, "wb") as f: f.write(resp.content) return out_path137 unmodified lines except Exception as e: return f"Error reading file '{file_path}': {str(e)}"
self._read_local_file = read_local_file self._read_local_file = read_local_file
@tool def web_search(query: str) -> str:274 unmodified lines
cleaned_query = (query or "").strip() if not cleaned_query: return "Brak wyników." return "No results."
try: resp = requests.get(12 unmodified lines return "\n".join(wiki_lines) except Exception as wiki_exc: if "task time budget exhausted" in str(wiki_exc).lower(): return "Brak wyników." return "No results."
try: ddg_resp = requests.post(17 unmodified lines except Exception: pass
return "Brak wyników." return "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", ) )
@tool def 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_models or [ "gemini/gemini-3-flash-preview", "gemini/gemini-flash-latest", "gemini/gemini-flash-lite-latest", ] )
30 unmodified lines call_kwargs["num_retries"] = 0 call_kwargs["max_retries"] = 0 call_kwargs["max_tokens"] = 1024 call_kwargs["timeout"] = _tool_timeout(22.0) call_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 []) ) )[:3] )[:2] while not video_analyzed: rate_limited_gemini = False for g_model in gemini_models:138 unmodified lines if "task time budget exhausted" in str(groq_exc).lower(): raise break
with open(audio_path, "rb") as f: b64_data = base64.b64encode(f.read()).decode("utf-8")
4 unmodified lines audio_models.extend( self.gemini_flash_models or [ "gemini/gemini-3-flash-preview", "gemini/gemini-flash-latest", "gemini/gemini-flash-lite-latest", ] ) audio_models = list(dict.fromkeys(audio_models)) audio_models = list(dict.fromkeys(audio_models))[:2]
last_err = None while True:19 unmodified lines } ], "generationConfig": { "maxOutputTokens": 2048, "thinkingConfig": {"thinkingBudget": 0}, }, "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 lines
if 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_models if m not in curated_live and 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(curated_live[:3] or ["openrouter/openrouter/free"]) candidate_models.extend(extra_live) else: candidate_models.extend(priority_openrouter_models) candidate_models.extend(priority_openrouter_models[:3])
if self.provider_keys.get("gemini"): available_api_models = set()16 unmodified lines if not any( bad in low_id for 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", "gemma", "flash-lite", ) ): available_api_models.add(full_id)4 unmodified lines
if available_api_models: discovered_flash = sorted( (m for m in available_api_models if "flash" in m.lower() or "gemma" in m.lower()), (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, 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, 0 if name.lower() == "gemini/gemini-2.5-flash" else 1, name, ), ) self.gemini_flash_models = (discovered_flash or sorted(available_api_models))[:6] 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", "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/meta-llama/llama-4-maverick-17b-128e-instruct", "groq/meta-llama/llama-4-scout-17b-16e-instruct", "groq/openai/gpt-oss-20b", "groq/llama-3.1-8b-instant", ] live_groq = [] try:27 unmodified lines name, ), ) selected_groq = list(dict.fromkeys(curated_groq + extra_groq)) selected_groq = list(dict.fromkeys(curated_groq + extra_groq))[:4] 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", ]) candidate_models.extend(preferred_groq[:4])
priority_rank = {name: idx for idx, name in enumerate(priority_openrouter_models)}
3 unmodified lines key_missing = 0 if self._get_api_key(model_name) else 1
if provider == "gemini": is_lite = "flash-lite" in low is_preview = 1 if "preview" in low else 0 ver_match = re.search(r"gemini-(\d+)(?:\.(\d+))?", low) major = int(ver_match.group(1)) if ver_match else 0 minor = int(ver_match.group(2)) if (ver_match and ver_match.group(2)) else 0
if low == "gemini/gemini-flash-latest": if low == "gemini/gemini-3-flash-preview": 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 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 lines sub_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 1 return (key_missing, 3, 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 lines
stripped_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}" 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 lines f"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 lines self.api_key = key if isinstance(getattr(self, "kwargs", None), dict): self.kwargs["api_key"] = key
if model_name.startswith("groq/"): default_cap = 14.0 default_cap = 35.0 elif model_name.startswith("openrouter/"): default_cap = 16.0 default_cap = 35.0 else: default_cap = 24.0 default_cap = 38.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:6 unmodified lines self.kwargs["timeout"] = timeout kwargs["timeout"] = timeout litellm.request_timeout = timeout
if model_name.startswith("groq/"): kwargs["max_tokens"] = 1536 kwargs["max_tokens"] = 2048 if isinstance(getattr(self, "kwargs", None), dict): self.kwargs["max_tokens"] = 1536 self.kwargs["max_tokens"] = 2048 if "qwen3" in model_name.lower(): kwargs.setdefault("reasoning_effort", "none") kwargs.setdefault("reasoning_format", "hidden") 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 lines if isinstance(getattr(self, "kwargs", None), dict): self.kwargs.pop("temperature", None) if model_name.startswith("openrouter/"): kwargs["max_tokens"] = 1024 kwargs["max_tokens"] = 1536 if isinstance(getattr(self, "kwargs", None), dict): self.kwargs["max_tokens"] = 1024 self.kwargs["max_tokens"] = 1536 kwargs["reasoning_effort"] = "low"
kwargs["num_retries"] = 0 kwargs["max_retries"] = 0 if "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_schemas kwargs["tool_choice"] = "auto" else: kwargs.pop("tools", None) kwargs.pop("tool_choice", None) kwargs.pop("tools", None) kwargs.pop("tool_choice", None) else: kwargs.pop("tools", None) kwargs.pop("tool_choice", None) return kwargs
self._model_cls = SafeLiteLLMModel
def _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 built return self._model_cls(**kwargs)
def _probe_candidate(model_name: str) -> tuple[str, str, str]: import time35 unmodified lines
from concurrent.futures import ThreadPoolExecutor, wait as futures_wait
# 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/")][:16] 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 probe_targets] done, _ = futures_wait(probe_futures, timeout=30) 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." )
from smolagents import MultiStepAgent
accepted_params = set(sig.parameters) | set(inspect.signature(MultiStepAgent.__init__).parameters) agent_kwargs = { "tools": [8 unmodified lines transcribe_audio, ], "additional_authorized_imports": [ "os", "pathlib", "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_name t_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_name props[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 schemas self._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.0 self._model_cooldowns[model_name] = time.monotonic() + 60.0 break is_context_overflow = any( marker in err_lower40 unmodified lines ) ): blocked_models.add(model_name) self._model_cooldowns[model_name] = time.monotonic() + 180.0 self._model_cooldowns[model_name] = time.monotonic() + 60.0 break if "connection error" in err_lower: if transient_retries < 1 and (deadline - time.monotonic()) > 10.0:51 unmodified lines Fetches 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 code space_id = os.getenv("SPACE_ID")
if profile: username = f"{profile.username}"6 unmodified lines questions_url = f"{api_url}/questions" submit_url = f"{api_url}/submit"
# 1. Instantiate Agent ( modify this part to create your agent) # 1. Instantiate 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 lines return "Fetched questions list is empty or invalid format.", None print(f"Fetched {len(questions_data)} questions.")
# 3. Run your Agent # 3. Run Agent from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeoutError import json import time153 unmodified lines run_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 constructor results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
run_button.click(app.py+87-166