diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -17,6 +17,7 @@ except ImportError: # --- 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: @@ -175,70 +176,88 @@ class BasicAgent: def download_task_file(task_id: str, output_dir: str = "/tmp/gaia_files") -> str: """Downloads a task attachment from the course API by task_id and returns the local file path. Args: - task_id: The GAIA task identifier. - output_dir: Target directory where the downloaded file is saved. + task_id: Task identifier from the evaluation dataset. + output_dir: Local directory where the file should be saved. """ import re from urllib.parse import unquote - url = f"{DEFAULT_API_URL.rstrip('/')}/files/{task_id}" - try: - os.makedirs(output_dir, exist_ok=True) - response = requests.get( - url, - timeout=30, - headers={"User-Agent": "Mozilla/5.0"}, - ) - response.raise_for_status() + clean_id = (task_id or "").strip() + if not clean_id: + return "Error downloading file: missing task_id." + + os.makedirs(output_dir, exist_ok=True) + base_url = DEFAULT_API_URL.rstrip("/") + candidate_urls = [ + f"{base_url}/files/{clean_id}", + f"{base_url}/attachments/{clean_id}", + ] + + last_err = None + for url in candidate_urls: + try: + resp = requests.get( + url, + timeout=30, + headers={"User-Agent": "Mozilla/5.0"}, + ) + if resp.status_code == 404: + continue + resp.raise_for_status() + if not resp.content: + continue - content_disp = response.headers.get("Content-Disposition", "") - filename = "" + content_disp = resp.headers.get("Content-Disposition", "") + filename = "" - star_match = re.search( - r"filename\*\s*=\s*(?:[A-Za-z0-9_-]+''|\"[A-Za-z0-9_-]+'')?([^\";]+)", - content_disp, - flags=re.IGNORECASE, - ) - if star_match: - raw_star = star_match.group(1).strip().strip('"') - if "''" in raw_star: - raw_star = raw_star.split("''", 1)[1] - filename = os.path.basename(unquote(raw_star)) - - if not filename: - std_match = re.search( - r'filename\s*=\s*"?([^";]+)"?', + star_match = re.search( + r"filename\*\s*=\s*(?:[A-Za-z0-9_-]+''|\"[A-Za-z0-9_-]+'')?([^\";]+)", content_disp, flags=re.IGNORECASE, ) - if std_match: - filename = os.path.basename(unquote(std_match.group(1).strip())) - - if not filename: - content_type = response.headers.get("Content-Type", "").split(";")[0].strip().lower() - ext_map = { - "text/plain": ".txt", - "text/csv": ".csv", - "application/json": ".json", - "application/pdf": ".pdf", - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ".xlsx", - "application/vnd.ms-excel": ".xls", - "image/png": ".png", - "image/jpeg": ".jpg", - "audio/mpeg": ".mp3", - "audio/wav": ".wav", - "text/x-python": ".py", - } - ext = ext_map.get(content_type) or mimetypes.guess_extension(content_type) or ".bin" - filename = f"{task_id}{ext}" - - file_path = os.path.join(output_dir, filename) - with open(file_path, "wb") as f: - f.write(response.content) - - return file_path - except Exception as e: - return f"Error downloading file for task '{task_id}': {str(e)}" + if star_match: + raw_star = star_match.group(1).strip().strip('"') + if "''" in raw_star: + raw_star = raw_star.split("''", 1)[1] + filename = os.path.basename(unquote(raw_star)) + + if not filename: + std_match = re.search( + r'filename\s*=\s*"?([^";]+)"?', + content_disp, + flags=re.IGNORECASE, + ) + if std_match: + filename = os.path.basename(unquote(std_match.group(1).strip())) + + if not filename: + content_type = resp.headers.get("Content-Type", "").split(";")[0].strip().lower() + ext_map = { + "text/plain": ".txt", + "text/csv": ".csv", + "application/json": ".json", + "application/pdf": ".pdf", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ".xlsx", + "application/vnd.ms-excel": ".xls", + "image/png": ".png", + "image/jpeg": ".jpg", + "audio/mpeg": ".mp3", + "audio/wav": ".wav", + "text/x-python": ".py", + } + 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) + with open(out_path, "wb") as f: + f.write(resp.content) + return out_path + except Exception as exc: + last_err = exc + + if last_err is not None: + return f"Error downloading file for task '{clean_id}': {str(last_err)}" + return f"No attachment available for task '{clean_id}' (404 Not Found)." @tool def read_local_file(file_path: str) -> str: @@ -382,7 +401,7 @@ class BasicAgent: if not results_out: return f"No web results found for '{clean_q}'. Try search_wikipedia(query) or fetch_url_text(url)." - return _trim_tool_output("\n\n".join(results_out)) + return "\n\n".join(results_out) wiki_cache = {} @@ -519,7 +538,7 @@ class BasicAgent: header_info += f"\nOther matching pages: {', '.join(other_titles)}" output = f"{header_info}\n\n{text}" if text else f"{header_info}\n\nEmpty article text." wiki_cache[cache_key] = output - return _trim_tool_output(output) + return output except Exception as e: return f"Wikipedia error for '{query}': {str(e)}" @@ -577,7 +596,7 @@ class BasicAgent: pass return "Brak wyników." - + @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. @@ -648,44 +667,13 @@ class BasicAgent: vision_candidates.append(m) if self.provider_keys.get("gemini"): - available_api_models = [] - for g_key in self.provider_key_pools.get("gemini") or [gemini_key]: - if not g_key: - continue - try: - models_resp = requests.get( - "https://generativelanguage.googleapis.com/v1beta/models", - params={"key": g_key}, - timeout=45, - ) - if models_resp.status_code == 200: - for m in models_resp.json().get("models", []): - if "generateContent" in m.get("supportedGenerationMethods", []): - raw_name = m.get("name", "") - if raw_name.startswith("models/"): - full_id = "gemini/" + raw_name[len("models/"):] - low_id = full_id.lower() - if "2.5-flash-lite" in low_id: - continue - if not any( - bad in low_id - for bad in ("tts", "image", "embedding", "aqa", "audio") - ): - available_api_models.append(full_id) - if available_api_models: - break - except Exception as list_exc: - print(f"Warning: could not list Gemini models via REST: {list_exc}") - - if available_api_models: - self.gemini_flash_models = sorted( - available_api_models, - key=lambda name: (0 if "flash" in name.lower() else 1, name), - reverse=True, - ) - candidate_models.extend(self.gemini_flash_models) - else: - self.gemini_flash_models = [] + vision_candidates.extend( + self.gemini_flash_models + or [ + "gemini/gemini-3.5-flash-lite", + "gemini/gemini-3.5-flash", + ] + ) if self.provider_keys.get("groq"): vision_candidates.append("groq/meta-llama/llama-4-scout-17b-16e-instruct") @@ -849,7 +837,7 @@ class BasicAgent: sections.append(f"Page fetch note: {e}") return "\n\n".join(sections) - + @tool def transcribe_audio( audio_path: str, @@ -981,7 +969,11 @@ class BasicAgent: key_failed_hard = True break if key_failed_hard: - if not rate_limited_gemini and hasattr(self, "_rotate_api_key") and self._rotate_api_key("gemini"): + if ( + not rate_limited_gemini + and hasattr(self, "_rotate_api_key") + and self._rotate_api_key("gemini") + ): continue break break @@ -1001,10 +993,19 @@ class BasicAgent: return f"Error transcribing audio '{audio_path}': {str(e)}" candidate_models = [] - model_timestamps = {} + priority_openrouter_models = [ + "openrouter/openrouter/free", + "openrouter/google/gemma-4-26b-a4b-it:free", + "openrouter/google/gemma-4-31b-it:free", + "openrouter/nvidia/nemotron-3-nano-30b-a3b:free", + "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/liquid/lfm-2.5-2.6b:free", + ] if self.provider_keys.get("openrouter"): - live_free_entries = [] + live_free_models = set() try: or_resp = requests.get( "https://openrouter.ai/api/v1/models", @@ -1015,22 +1016,24 @@ class BasicAgent: for item in or_resp.json().get("data", []): m_id = str(item.get("id", "")).strip() if m_id == "openrouter/free" or m_id.endswith(":free"): - full_id = f"openrouter/{m_id}" - if not any(bad in full_id.lower() for bad in ("embed", "whisper", "tts", "audio", "image")): - created_ts = int(item.get("created") or 0) - model_timestamps[full_id] = created_ts - live_free_entries.append((created_ts, full_id)) + live_free_models.add(f"openrouter/{m_id}") except Exception as or_exc: print(f"Warning: could not list OpenRouter models: {or_exc}") - if live_free_entries: - live_free_entries.sort(key=lambda pair: (pair[0], pair[1] == "openrouter/openrouter/free"), reverse=True) - candidate_models.extend(m for _, m in live_free_entries[:8]) + 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")) + )[:6] + candidate_models.extend(curated_live or ["openrouter/openrouter/free"]) + candidate_models.extend(extra_live) else: - candidate_models.append("openrouter/openrouter/free") + candidate_models.extend(priority_openrouter_models) if self.provider_keys.get("gemini"): - available_api_models = [] + available_api_models = set() for g_key in self.provider_key_pools.get("gemini") or [gemini_key]: if not g_key: continue @@ -1048,23 +1051,53 @@ class BasicAgent: full_id = "gemini/" + raw_name[len("models/"):] if not any( bad in full_id.lower() - for bad in ("tts", "image", "embedding", "aqa", "audio") + for bad in ( + "tts", + "image", + "embedding", + "aqa", + "audio", + "robotics", + "computer-use", + "deep-research", + ) ): - available_api_models.append(full_id) + available_api_models.add(full_id) if available_api_models: break except Exception as list_exc: print(f"Warning: could not list Gemini models via REST: {list_exc}") if available_api_models: - self.gemini_flash_models = sorted( - available_api_models, - key=lambda name: (0 if "flash" in name.lower() else 1, name), - reverse=True, + fallback_gemini_flash = [ + "gemini/gemini-3.5-flash-lite", + "gemini/gemini-3.5-flash", + ] + discovered_flash = sorted( + ( + m for m in available_api_models + if "flash" in m.lower() + and not any(bad in m.lower() for bad in ("exp", "thinking")) + ), + key=lambda name: ( + 0 if "2.5" not in name.lower() else 1, + 0 if "lite" in name.lower() else 1, + 1 if "preview" in name.lower() or "latest" in name.lower() else 0, + name, + ), + ) + self.gemini_flash_models = ( + discovered_flash + or [m for m in fallback_gemini_flash if m in available_api_models] + or sorted(available_api_models)[:4] ) candidate_models.extend(self.gemini_flash_models) else: - self.gemini_flash_models = [] + self.gemini_flash_models = [ + "gemini/gemini-3.5-flash-lite", + "gemini/gemini-3.5-flash", + ] + candidate_models.extend(self.gemini_flash_models) if self.provider_keys.get("groq"): candidate_models.extend([ @@ -1078,30 +1111,25 @@ class BasicAgent: "huggingface/meta-llama/Llama-3.1-8B-Instruct", ]) - def _model_priority(model_name: str) -> tuple[int, int, int, int, int, tuple[int, int], str]: + priority_rank = {name: idx for idx, name in enumerate(priority_openrouter_models)} + + def _model_priority(model_name: str) -> tuple[int, int, int, str]: provider = model_name.split("/", 1)[0].lower() if "/" in model_name else "gemini" low = model_name.lower() - key_missing = 0 if self._get_api_key(model_name) else 1 - if provider == "gemini": - 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 - is_omni = 1 if "omni" in low else 0 - is_lite = 1 if "lite" in low else 0 - is_unstable = 1 if ("preview" in low or "latest" in low) else 0 - return (key_missing, 0, is_omni, is_lite, is_unstable, (-major, -minor), model_name) - - if provider == "groq": - sub_rank = 0 if any(tag in low for tag in ("70b", "120b")) else 1 - return (key_missing, 1, 0, sub_rank, 0, (0, 0), model_name) - - if provider == "openrouter": + group = 0 + sub_rank = 0 if "flash-lite" in low else 1 + elif provider == "groq": + group = 1 + sub_rank = 0 if "20b" in low else 1 + elif provider == "openrouter": + group = 2 sub_rank = priority_rank.get(model_name, len(priority_rank)) - return (key_missing, 2, 0, sub_rank, 0, (0, 0), model_name) - - sub_rank = 0 if any(tag in low for tag in ("72b", "70b")) else 1 - return (key_missing, 3, 0, sub_rank, 0, (0, 0), model_name) + else: + group = 3 + sub_rank = 0 if "8b" in low else 1 + key_missing = 0 if self._get_api_key(model_name) else 1 + return (key_missing, group, sub_rank, model_name) self.working_models = sorted( dict.fromkeys(candidate_models), @@ -1170,6 +1198,11 @@ class BasicAgent: if stripped_orphan_tags != cleaned_text.strip() and stripped_orphan_tags: return f"\n{_extract_valid_python(stripped_orphan_tags)}\n" + if "final_answer(" in cleaned_text: + extracted = _extract_valid_python(cleaned_text) + if "final_answer(" in extracted: + return f"\n{extracted}\n" + return cleaned_text @classmethod @@ -1219,7 +1252,11 @@ class BasicAgent: content_str = _extract_text_from_blocks(getattr(msg, "content", None)) if not content_str and raw_msg is not None: - raw_msg_content = raw_msg.get("content") if isinstance(raw_msg, dict) else getattr(raw_msg, "content", None) + raw_msg_content = ( + raw_msg.get("content") + if isinstance(raw_msg, dict) + else getattr(raw_msg, "content", None) + ) content_str = _extract_text_from_blocks(raw_msg_content) reasoning_sources = [ @@ -1324,7 +1361,7 @@ class BasicAgent: elif model_name.startswith("gemini/"): os.environ["GEMINI_API_KEY"] = key os.environ["GOOGLE_API_KEY"] = key - kwargs.setdefault("timeout", 30) + kwargs.setdefault("timeout", 45) if model_name.startswith("openrouter/"): kwargs["max_tokens"] = 4096 return kwargs @@ -1338,15 +1375,6 @@ class BasicAgent: kwargs = self._prepare_call_kwargs(dict(kwargs)) return self._validate_message(super().__call__(*args, **kwargs)) - # Upewnij się, że poniższy blok jest na poziomie 8 spacji (równo z `def _model_priority`), a NIE wewnątrz `_model_priority`: - 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.") - self._model_cls = SafeLiteLLMModel self.model_id = self.working_models[0] print(f"Using primary LLM model: {self.model_id} (fallbacks: {self.working_models[1:]})") @@ -1426,30 +1454,6 @@ class BasicAgent: raise RuntimeError("BasicAgent.__init__ failed to bind _build_model or self.agent.") print("CodeAgent initialized with LiteLLMModel.") - def generate(self, messages, stop_sequences=None, grammar=None, tools_to_call_from=None, **kwargs): - call_kwargs = dict(kwargs) - call_kwargs.setdefault("timeout", 12) - if tools_to_call_from: - call_kwargs["tools"] = tools_to_call_from - if stop_sequences: - call_kwargs["stop"] = stop_sequences - - response = super().generate(messages, **call_kwargs) - content = getattr(response, "content", None) - if content is None or (isinstance(content, str) and not content.strip()): - raise RuntimeError("empty model response (content=None)") - - if isinstance(content, str) and "" not in content and "final_answer(" in content: - lines = [ - line for line in content.splitlines() - if not line.lstrip().startswith(("#", "1.", "2.", "3.", "Based ", "The Wikipedia", "There were")) - ] - code_block = "\n".join(lines).strip() - if "final_answer(" in code_block: - response.content = f"\n{code_block}\n" - - return response - @staticmethod def _clean_exact_match_answer(raw_answer) -> str: import re @@ -1588,13 +1592,22 @@ class BasicAgent: return "AGENT ERROR: All candidate models failed." +def _trim_tool_output(text: str, max_chars: int = 4000) -> str: + if not isinstance(text, str): + return str(text) + cleaned = "\n".join(line.strip() for line in text.splitlines() if line.strip()) + if len(cleaned) <= max_chars: + return cleaned + return cleaned[:max_chars] + "\n...[truncated]..." + + def run_and_submit_all(profile: gr.OAuthProfile | None): """ 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") # Get the SPACE_ID for sending link to the code if profile: username = f"{profile.username}" @@ -1615,11 +1628,11 @@ def run_and_submit_all(profile: gr.OAuthProfile | None): 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}/tree/main" + f"[https://huggingface.co/spaces/](https://huggingface.co/spaces/){space_id}/tree/main" if space_id else ( os.getenv("AGENT_CODE_URL") - or f"https://huggingface.co/spaces/{username.strip()}/Final_Assignment_Template/tree/main" + or f"[https://huggingface.co/spaces/](https://huggingface.co/spaces/){username.strip()}/Final_Assignment_Template/tree/main" ).strip() ) print(agent_code) @@ -1653,6 +1666,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None): results_log = [] answers_payload = [] partial_path = "/tmp/gaia_partial_results.json" + cached_by_task_id = {} cached_by_question = {} try: if os.path.isfile(partial_path): @@ -1662,30 +1676,42 @@ def run_and_submit_all(profile: gr.OAuthProfile | None): for c_item in cached_items: if not isinstance(c_item, dict): continue + c_tid = c_item.get("Task ID") c_q = c_item.get("Question") c_ans = c_item.get("Submitted Answer") if ( - isinstance(c_q, str) - and isinstance(c_ans, str) + isinstance(c_ans, str) and c_ans.strip() and not c_ans.strip().startswith("AGENT ERROR:") ): - cached_by_question[c_q] = c_ans.strip() + clean_cached = c_ans.strip() + if isinstance(c_tid, str) and c_tid.strip(): + cached_by_task_id[c_tid.strip()] = clean_cached + if isinstance(c_q, str) and c_q.strip(): + cached_by_question[c_q.strip()] = clean_cached except Exception: + cached_by_task_id = {} cached_by_question = {} print(f"Running agent on {len(questions_data)} questions...") + ran_fresh_query = False for idx, item in enumerate(questions_data): task_id = item.get("task_id") question_text = item.get("question") if not task_id or question_text is None: print(f"Skipping item with missing task_id or question: {item}") continue - if question_text in cached_by_question: - submitted_answer = cached_by_question[question_text] + + clean_tid = str(task_id).strip() + clean_q = str(question_text).strip() + if clean_tid in cached_by_task_id: + submitted_answer = cached_by_task_id[clean_tid] + elif clean_q in cached_by_question: + submitted_answer = cached_by_question[clean_q] else: - if len(results_log) > 0: + if ran_fresh_query: time.sleep(3) + ran_fresh_query = True try: with ThreadPoolExecutor(max_workers=1) as executor: future = executor.submit(agent, question_text, task_id=task_id) @@ -1754,1634 +1780,6 @@ def run_and_submit_all(profile: gr.OAuthProfile | None): return status_message, results_df -# --- Build Gradio Interface using Blocks --- -with gr.Blocks() as demo: - gr.Markdown("# Basic Agent Evaluation Runner") - gr.Markdown( - """ - **Instructions:** - -1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ... -2. Log in to your Hugging Face account using the button below. This uses your HF username for submission. -3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score. - - --- - **Disclaimers:** - Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions). - This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async. - """ - ) - - gr.LoginButton() - - 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( - fn=run_and_submit_all, - outputs=[status_output, results_table] - ) - -import os -import gradio as gr -import requests -import inspect -import pandas as pd - -try: - import spaces - - @spaces.GPU - def _register_zerogpu(): - return None -except 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 litellm - from smolagents import CodeAgent, LiteLLMModel, tool - - litellm.drop_params = True - litellm.request_timeout = 25 - - provider_env_prefixes = { - "openrouter": ("OPENROUTER_API_KEY", "OPENROUTER_TOKEN", "OPENROUTER_KEY"), - "gemini": ("GEMINI_API_KEY", "GOOGLE_API_KEY", "GEMINI_TOKEN", "GOOGLE_GEMINI_API_KEY"), - "groq": ("GROQ_API_KEY", "GROQ_TOKEN"), - "huggingface": ("HF_TOKEN", "HUGGINGFACE_API_KEY", "HUGGINGFACEHUB_API_TOKEN", "HUGGINGFACE_TOKEN"), - } - raw_pools = {p: [] for p in provider_env_prefixes} - - def _classify_token(token: str, default_provider: str) -> str: - if token.startswith("sk-or-"): - return "openrouter" - if token.startswith("AIza"): - return "gemini" - if token.startswith("gsk_"): - return "groq" - if token.startswith("hf_"): - return "huggingface" - return default_provider - - for raw_name, raw_val in os.environ.items(): - if not raw_val: - continue - env_name = raw_name.upper().strip() - matched_provider = next( - ( - prov - for prov, prefixes in provider_env_prefixes.items() - if any(env_name == pref or env_name.startswith(pref + "_") for pref in prefixes) - ), - None, - ) - if not matched_provider: - continue - for part in re.split(r"[\s,;]+", raw_val): - tok = part.strip(" '\"\n\r\t[]") - if tok: - target_prov = _classify_token(tok, matched_provider) - raw_pools[target_prov].append(tok) - - self.provider_key_pools = { - prov: list(dict.fromkeys(tokens)) for prov, tokens in raw_pools.items() - } - self._provider_key_idx = {prov: 0 for prov in self.provider_key_pools} - - openrouter_key = self.provider_key_pools["openrouter"][0] if self.provider_key_pools["openrouter"] else "" - groq_key = self.provider_key_pools["groq"][0] if self.provider_key_pools["groq"] else "" - hf_key = self.provider_key_pools["huggingface"][0] if self.provider_key_pools["huggingface"] else "" - gemini_key = self.provider_key_pools["gemini"][0] if self.provider_key_pools["gemini"] else "" - - self.provider_keys = { - "openrouter": openrouter_key, - "groq": groq_key, - "huggingface": hf_key, - "gemini": gemini_key, - } - if not any(self.provider_keys.values()): - raise ValueError( - "Missing API key in Space secrets. Add at least one of: " - "OPENROUTER_API_KEY, GROQ_API_KEY, HF_TOKEN, or GEMINI_API_KEY." - ) - - self.gemini_key = gemini_key - if gemini_key: - os.environ["GEMINI_API_KEY"] = gemini_key - os.environ["GOOGLE_API_KEY"] = gemini_key - if openrouter_key: - os.environ["OPENROUTER_API_KEY"] = openrouter_key - if groq_key: - os.environ["GROQ_API_KEY"] = groq_key - if hf_key: - os.environ["HF_TOKEN"] = hf_key - os.environ["HUGGINGFACE_API_KEY"] = hf_key - - def _get_api_key(model_name: str) -> str | None: - provider = model_name.split("/", 1)[0].lower() if "/" in model_name else "gemini" - pool = self.provider_key_pools.get(provider) or [] - idx = self._provider_key_idx.get(provider, 0) - if idx < len(pool): - key = pool[idx] - self.provider_keys[provider] = key - return key - self.provider_keys[provider] = "" - return None - - def _rotate_api_key(provider: str) -> bool: - pool = self.provider_key_pools.get(provider) or [] - next_idx = self._provider_key_idx.get(provider, 0) + 1 - self._provider_key_idx[provider] = next_idx - if next_idx < len(pool): - new_key = pool[next_idx] - self.provider_keys[provider] = new_key - if provider == "openrouter": - os.environ["OPENROUTER_API_KEY"] = new_key - elif provider == "groq": - os.environ["GROQ_API_KEY"] = new_key - elif provider == "huggingface": - os.environ["HF_TOKEN"] = new_key - os.environ["HUGGINGFACE_API_KEY"] = new_key - elif provider == "gemini": - self.gemini_key = new_key - os.environ["GEMINI_API_KEY"] = new_key - os.environ["GOOGLE_API_KEY"] = new_key - return True - self.provider_keys[provider] = "" - return False - - self._get_api_key = _get_api_key - self._rotate_api_key = _rotate_api_key - self.gemini_flash_models = [] - - @tool - def fetch_url_text(url: str) -> str: - """Fetches clean plain text from a given URL. - Args: - url: The HTTP/HTTPS URL to fetch. - """ - import re - from html import unescape - - try: - response = requests.get( - url, - timeout=45, - headers={"User-Agent": "Mozilla/5.0"}, - ) - response.raise_for_status() - raw_html = re.sub( - r"(?is)<(script|style|noscript|svg|header|footer|nav).*?>.*?", - " ", - response.text, - ) - plain_text = re.sub(r"(?s)<[^>]+>", " ", raw_html) - cleaned = re.sub(r"\s+", " ", unescape(plain_text)).strip() - if not cleaned: - return "Empty text response." - if len(cleaned) <= 24000: - return cleaned - return cleaned[:12000] + "\n...\n" + cleaned[-12000:] - except Exception as e: - return f"Error fetching URL '{url}': {str(e)}" - - @tool - def download_task_file(task_id: str, output_dir: str = "/tmp/gaia_files") -> str: - """Downloads a task attachment from the course API by task_id and returns the local file path. - - Args: - task_id: Task identifier from the evaluation dataset. - output_dir: Local directory where the file should be saved. - """ - clean_id = (task_id or "").strip() - if not clean_id: - return "Error downloading file: missing task_id." - - os.makedirs(output_dir, exist_ok=True) - base_url = DEFAULT_API_URL.rstrip("/") - candidate_urls = [ - f"{base_url}/files/{clean_id}", - f"{base_url}/attachments/{clean_id}", - ] - - for url in candidate_urls: - try: - resp = requests.get(url, timeout=15) - if resp.status_code == 404: - continue - resp.raise_for_status() - if not resp.content: - continue - - filename = f"{clean_id}.bin" - content_disp = resp.headers.get("content-disposition", "") - if "filename=" in content_disp: - raw_name = content_disp.split("filename=", 1)[1].strip().strip('"').strip("'") - if raw_name: - filename = os.path.basename(raw_name) - else: - ext = mimetypes.guess_extension(resp.headers.get("content-type", "").split(";")[0].strip()) - if ext: - 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_path - except Exception as exc: - last_err = exc - - return f"No attachment available for task '{clean_id}' (404 Not Found)." - - @tool - def read_local_file(file_path: str) -> str: - """Reads text, PDF, ZIP archive, or spreadsheet content from a local file downloaded by download_task_file. - Args: - file_path: Local path to the downloaded file. - """ - import zipfile - - def _read_single(path: str, max_chars: int) -> str: - f_ext = os.path.splitext(path)[1].lower() - if f_ext in {".xlsx", ".xls"}: - sheets = pd.read_excel(path, sheet_name=None) - if not sheets: - return "Empty Excel workbook." - text = "\n\n".join( - f"=== Sheet: {s_name} ===\n{df.to_csv(index=False)}" - for s_name, df in sheets.items() - ) - elif f_ext == ".pdf": - try: - from pypdf import PdfReader - - reader = PdfReader(path) - pages = [ - f"=== Page {i + 1} ===\n{(p.extract_text() or '').strip()}" - for i, p in enumerate(reader.pages) - ] - text = "\n\n".join(p for p in pages if p.strip()) or "Empty PDF text." - except Exception as pdf_exc: - return f"Error reading PDF '{path}': {str(pdf_exc)}" - elif f_ext in {".png", ".jpg", ".jpeg", ".webp", ".gif"}: - return f"Binary image file '{path}'. Use inspect_image(image_path='{path}', question=...)." - elif f_ext in {".mp3", ".wav", ".m4a", ".ogg", ".flac"}: - return f"Binary audio file '{path}'. Use transcribe_audio(audio_path='{path}', question=...)." - else: - with open(path, "r", encoding="utf-8", errors="replace") as f: - text = f.read() - - if len(text) <= max_chars: - return text - half = max_chars // 2 - return text[:half] + "\n...\n" + text[-half:] - - try: - if not os.path.isfile(file_path): - return f"File not found: '{file_path}'" - ext = os.path.splitext(file_path)[1].lower() - if ext == ".zip" or zipfile.is_zipfile(file_path): - extract_dir = os.path.join( - os.path.dirname(file_path), - f"extracted_{os.path.basename(file_path)}", - ) - os.makedirs(extract_dir, exist_ok=True) - base_extract = os.path.realpath(extract_dir) - sections = [] - with zipfile.ZipFile(file_path, "r") as zf: - members = [m for m in zf.namelist() if not m.endswith("/")] - sections.append( - f"=== ZIP Archive ({len(members)} files) ===\nFiles: {', '.join(members)}" - ) - for member in members: - target_path = os.path.realpath(os.path.join(extract_dir, member)) - if not (target_path == base_extract or target_path.startswith(base_extract + os.sep)): - sections.append(f"=== {member} ===\nSkipped unsafe path.") - continue - os.makedirs(os.path.dirname(target_path), exist_ok=True) - with zf.open(member, "r") as src, open(target_path, "wb") as dst: - dst.write(src.read()) - try: - content_str = _read_single(target_path, max_chars=24000) - sections.append(f"=== {member} (extracted to {target_path}) ===\n{content_str}") - except Exception as m_exc: - sections.append(f"=== {member} (extracted to {target_path}) ===\nRead error: {m_exc}") - joined_zip = "\n\n".join(sections) - if len(joined_zip) <= 48000: - return joined_zip - return joined_zip[:24000] + "\n...\n" + joined_zip[-24000:] - - return _read_single(file_path, max_chars=48000) - except Exception as e: - return f"Error reading file '{file_path}': {str(e)}" - - @tool - def web_search(query: str) -> str: - """Searches the web for a query and returns top results with titles, URLs, and snippets. - Args: - query: The search query string. - """ - import re - from html import unescape - - clean_q = (query or "").strip() - if not clean_q: - return "Empty search query." - - results_out = [] - try: - try: - from ddgs import DDGS - except ImportError: - from duckduckgo_search import DDGS - - raw_results = DDGS().text(clean_q, max_results=5) or [] - for item in raw_results: - if not isinstance(item, dict): - continue - title = str(item.get("title", "")).strip() - href = str(item.get("href", "")).strip() - body = str(item.get("body", "")).strip() - if title or href or body: - results_out.append(f"- {title}\n URL: {href}\n Snippet: {body}") - except Exception: - pass - - if not results_out: - try: - resp = requests.post( - "https://html.duckduckgo.com/html/", - data={"q": clean_q}, - headers={"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36"}, - timeout=25, - ) - resp.raise_for_status() - links = re.findall( - r'(?is)]+class="result__a"[^>]+href="([^"]+)"[^>]*>(.*?)', - resp.text, - ) - snippets = re.findall( - r'(?is)]+class="result__snippet"[^>]*>(.*?)', - resp.text, - ) - for idx, (href, raw_title) in enumerate(links[:5]): - title = re.sub(r"\s+", " ", unescape(re.sub(r"(?s)<[^>]+>", " ", raw_title))).strip() - raw_snip = snippets[idx] if idx < len(snippets) else "" - snip = re.sub(r"\s+", " ", unescape(re.sub(r"(?s)<[^>]+>", " ", raw_snip))).strip() - if title or href or snip: - results_out.append(f"- {title}\n URL: {href}\n Snippet: {snip}") - except Exception: - pass - - if not results_out: - return f"No web results found for '{clean_q}'. Try search_wikipedia(query) or fetch_url_text(url)." - return "\n\n".join(results_out) - - wiki_cache = {} - - @tool - def search_wikipedia(query: str) -> str: - """Searches English Wikipedia and returns clean plain text (including tables) of the best matching article. - Args: - query: Search query or exact Wikipedia article title. - """ - import re - import time - from html import unescape - - cache_key = query.strip().lower() - if cache_key in wiki_cache: - return wiki_cache[cache_key] - - headers = {"User-Agent": "HF-Agents-Course-Bot/1.0"} - api_endpoint = "https://en.wikipedia.org/w/api.php" - use_2022 = "2022" in cache_key - clean_query = re.sub(r"\b2022\b", "", query).strip() or query.strip() - try: - search_resp = None - for attempt in range(3): - search_resp = requests.get( - api_endpoint, - params={ - "action": "query", - "list": "search", - "srsearch": clean_query, - "format": "json", - "srlimit": 5, - }, - headers=headers, - timeout=45, - ) - if search_resp.status_code == 429 and attempt < 2: - time.sleep(1.5 * (attempt + 1)) - continue - break - search_resp.raise_for_status() - results = search_resp.json().get("query", {}).get("search", []) - if not results: - out_empty = f"No Wikipedia results for '{query}'." - wiki_cache[cache_key] = out_empty - return out_empty - - query_norm = clean_query.lower() - selected = next( - (r for r in results if r["title"].strip().lower() == query_norm), - results[0], - ) - title = selected["title"] - other_titles = [r["title"] for r in results if r["title"] != title] - - rev_id = None - if use_2022: - rev_resp = requests.get( - api_endpoint, - params={ - "action": "query", - "titles": title, - "prop": "revisions", - "rvlimit": 1, - "rvdir": "older", - "rvstart": "2023-01-01T00:00:00Z", - "format": "json", - }, - headers=headers, - timeout=30, - ) - if rev_resp.status_code == 200: - pages = rev_resp.json().get("query", {}).get("pages", {}) - for p_data in pages.values(): - revs = p_data.get("revisions") or [] - if revs and revs[0].get("revid"): - rev_id = revs[0]["revid"] - break - - parse_params = { - "action": "parse", - "prop": "text", - "redirects": 1, - "format": "json", - } - if rev_id: - parse_params["oldid"] = rev_id - else: - parse_params["page"] = title - - parse_resp = None - for attempt in range(3): - parse_resp = requests.get( - api_endpoint, - params=parse_params, - headers=headers, - timeout=45, - ) - if parse_resp.status_code == 429 and attempt < 2: - time.sleep(1.5 * (attempt + 1)) - continue - break - parse_resp.raise_for_status() - parse_data = parse_resp.json().get("parse", {}) - raw_html = parse_data.get("text", {}).get("*", "") - resolved_title = parse_data.get("title", title) - - if raw_html: - cleaned_html = re.sub( - r"(?is)<(script|style|noscript|svg).*?>.*?", - " ", - raw_html, - ) - cleaned_html = re.sub(r"(?i)", "\n", cleaned_html) - cleaned_html = re.sub(r"(?i)", " | ", cleaned_html) - plain_text = unescape(re.sub(r"(?s)<[^>]+>", " ", cleaned_html)) - lines = [re.sub(r"[ \t]+", " ", ln).strip() for ln in plain_text.splitlines()] - text = "\n".join(ln for ln in lines if ln) - else: - text = "" - - if len(text) > 22000: - disc_match = re.search(r"(?i)\bdiscography\b", text) - if disc_match: - start_pos = max(0, disc_match.start() - 500) - text = text[:3000] + "\n...\n" + text[start_pos : start_pos + 19000] - else: - text = text[:11000] + "\n...\n" + text[-11000:] - - header_info = f"Title: {resolved_title}" - if rev_id: - header_info += f" (revid: {rev_id}, pre-2023)" - if other_titles: - header_info += f"\nOther matching pages: {', '.join(other_titles)}" - output = f"{header_info}\n\n{text}" if text else f"{header_info}\n\nEmpty article text." - wiki_cache[cache_key] = output - return _trim_tool_output(output) - except Exception as e: - return f"Wikipedia error for '{query}': {str(e)}" - - @tool - def ask_web(query: str) -> str: - """Searches Wikipedia first and falls back to DuckDuckGo web search if needed. - Args: - query: Search query string. - """ - import re - from html import unescape - - cleaned_query = (query or "").strip() - if not cleaned_query: - return "Brak wyników." - - try: - resp = requests.get( - "https://en.wikipedia.org/w/api.php", - params={"action": "opensearch", "search": cleaned_query, "limit": 3, "format": "json"}, - headers={"User-Agent": "BasicAgent/1.0"}, - timeout=15, - ) - resp.raise_for_status() - data = resp.json() - titles = data[1] if len(data) > 1 else [] - descs = data[2] if len(data) > 2 else [] - urls = data[3] if len(data) > 3 else [] - wiki_lines = [f"{t}: {d} ({u})" for t, d, u in zip(titles, descs, urls) if t or d] - if wiki_lines: - return "\n".join(wiki_lines) - except Exception: - pass - - try: - ddg_resp = requests.post( - "https://html.duckduckgo.com/html/", - data={"q": cleaned_query}, - headers={"User-Agent": "Mozilla/5.0"}, - timeout=15, - ) - ddg_resp.raise_for_status() - matches = re.findall( - r'(?is)]+class="result__a"[^>]+href="([^"]+)"[^>]*>(.*?)', - ddg_resp.text, - ) - out = [] - for href, raw_title in matches[:3]: - title = re.sub(r"\s+", " ", unescape(re.sub(r"(?s)<[^>]+>", " ", raw_title))).strip() - if title: - out.append(f"{title} ({href})") - if out: - return "\n".join(out) - except Exception: - pass - - return "Brak wyników." - - @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. - Args: - image_path: Local path to the image file (.png, .jpg, .jpeg, .webp). - question: Specific question or instruction about what to extract from the image. - """ - import io - - try: - if not os.path.isfile(image_path): - return f"Image file not found: '{image_path}'" - - mime_type, _ = mimetypes.guess_type(image_path) - if not mime_type or not mime_type.startswith("image/"): - mime_type = "image/png" - - with open(image_path, "rb") as f: - raw_bytes = f.read() - - payload_bytes = raw_bytes - if len(raw_bytes) > 3_500_000: - try: - from PIL import Image - - img = Image.open(io.BytesIO(raw_bytes)) - img.thumbnail((1600, 1600)) - buf = io.BytesIO() - save_fmt = "JPEG" if mime_type in ("image/jpeg", "image/jpg") else "PNG" - if save_fmt == "JPEG" and img.mode in ("RGBA", "P"): - img = img.convert("RGB") - img.save(buf, format=save_fmt, optimize=True, quality=85) - payload_bytes = buf.getvalue() - mime_type = "image/jpeg" if save_fmt == "JPEG" else "image/png" - except Exception: - payload_bytes = raw_bytes - - b64_data = base64.b64encode(payload_bytes).decode("utf-8") - - vision_tags = ( - "gemma-3", - "gemma-4", - "gemini", - "vision", - "-vl", - "scout", - "maverick", - "pixtral", - "qwen2.5-vl", - "qwen3-vl", - ) - vision_candidates = [] - current_model = getattr(self, "model_id", "") - current_model_low = current_model.lower() - - 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"): - 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", - "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.5-flash-lite", - "gemini/gemini-3.5-flash", - ] - ) - - if self.provider_keys.get("groq"): - vision_candidates.append("groq/meta-llama/llama-4-scout-17b-16e-instruct") - - for m in getattr(self, "working_models", []): - if m not in vision_candidates and any(tag in m.lower() for tag in vision_tags): - vision_candidates.append(m) - - unique_vision = list(dict.fromkeys(vision_candidates)) - last_err = None - - 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( - model=v_model, - api_key=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=45, - ) - 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 any( - marker in err_low - for marker in ( - "401", - "402", - "403", - "authentication", - "missing authentication header", - "insufficient permissions", - "does not have sufficient permissions", - "free-models-per-day", - "quota", - "resource_exhausted", - ) - ): - if hasattr(self, "_rotate_api_key") and self._rotate_api_key(v_provider): - continue - break - if any(marker in err_low for marker in ("429", "rate limit exceeded")): - rate_limited_providers.add(v_provider) - break - 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 - - raise RuntimeError(str(last_err) if last_err else "No vision model available.") - except Exception as e: - return f"Error inspecting image '{image_path}': {str(e)}" - - @tool - def inspect_youtube(url: str) -> str: - """Fetches YouTube video title, author, description, and available captions/transcripts for a given YouTube URL or video ID. - Args: - url: YouTube video URL or 11-character video ID. - """ - import re - from html import unescape - - raw = (url or "").strip() - vid_match = re.search( - r"(?:v=|/shorts/|/embed/|youtu\.be/)([A-Za-z0-9_-]{11})", - raw, - ) - video_id = vid_match.group(1) if vid_match else (raw if re.fullmatch(r"[A-Za-z0-9_-]{11}", raw) else "") - if not video_id: - return f"Invalid YouTube URL or video ID: '{url}'" - - watch_url = f"https://www.youtube.com/watch?v={video_id}" - headers = { - "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", - } - sections = [f"Video ID: {video_id}", f"URL: {watch_url}"] - - try: - oembed_resp = requests.get( - "https://www.youtube.com/oembed", - params={"url": watch_url, "format": "json"}, - headers=headers, - timeout=20, - ) - if oembed_resp.status_code == 200: - oembed = oembed_resp.json() - if oembed.get("title"): - sections.append(f"Title: {oembed['title']}") - if oembed.get("author_name"): - sections.append(f"Channel: {oembed['author_name']}") - except Exception: - pass - - try: - page_resp = requests.get(watch_url, headers=headers, timeout=25) - if page_resp.status_code == 200: - html_text = page_resp.text - desc_match = re.search(r'"shortDescription"\s*:\s*"((?:\\.|[^"\\])*)"', html_text) - if desc_match: - try: - desc_val = desc_match.group(1).encode("utf-8").decode("unicode_escape") - except Exception: - desc_val = unescape(desc_match.group(1)) - sections.append(f"Description:\n{desc_val[:2000]}") - - cap_match = re.search(r'"captionTracks"\s*:\s*(\[[^\]]*\])', html_text) - if cap_match: - import json - - try: - tracks = json.loads(cap_match.group(1)) - for tr in tracks[:3]: - base_url = tr.get("baseUrl") - if not base_url: - continue - tr_resp = requests.get(unescape(base_url), headers=headers, timeout=20) - if tr_resp.status_code == 200 and tr_resp.text: - raw_cues = re.findall(r"(?is)]*>(.*?)", tr_resp.text) - cues = [ - re.sub(r"\s+", " ", unescape(re.sub(r"(?s)<[^>]+>", " ", c))).strip() - for c in raw_cues - ] - transcript = " ".join(c for c in cues if c) - if transcript: - lang = tr.get("languageCode", "unknown") - sections.append(f"Transcript ({lang}):\n{transcript[:8000]}") - break - except Exception: - pass - except Exception as e: - sections.append(f"Page fetch note: {e}") - - return "\n\n".join(sections) - - @tool - def transcribe_audio( - audio_path: str, - question: str = "Transcribe all spoken words verbatim and answer any question about the audio.", - ) -> str: - """Transcribes or analyzes a local audio file (.mp3, .wav, .m4a, .ogg) using available audio/multimodal models. - Args: - audio_path: Local path to the downloaded audio file. - question: Specific transcription or analysis instruction for the audio. - """ - try: - if not os.path.isfile(audio_path): - return f"Audio file not found: '{audio_path}'" - ext = os.path.splitext(audio_path)[1].lower().lstrip(".") - mime_map = { - "mp3": "audio/mp3", - "wav": "audio/wav", - "m4a": "audio/mp4", - "ogg": "audio/ogg", - "flac": "audio/flac", - } - mime_type = mime_map.get(ext, "audio/mp3") - - while True: - groq_key = self._get_api_key("groq/whisper-large-v3-turbo") - if not groq_key: - break - try: - with open(audio_path, "rb") as audio_f: - groq_resp = requests.post( - "https://api.groq.com/openai/v1/audio/transcriptions", - 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=45, - ) - if groq_resp.status_code == 200: - transcript = groq_resp.text.strip() - if transcript: - return transcript - break - err_body = groq_resp.text.lower() - if groq_resp.status_code in (401, 402, 403) or "quota" in err_body: - if hasattr(self, "_rotate_api_key") and self._rotate_api_key("groq"): - continue - break - if groq_resp.status_code == 429: - groq_pool = self.provider_key_pools.get("groq") or [] - if ( - hasattr(self, "_rotate_api_key") - and self._provider_key_idx.get("groq", 0) + 1 < len(groq_pool) - and self._rotate_api_key("groq") - ): - continue - break - except Exception: - break - - with open(audio_path, "rb") as f: - b64_data = base64.b64encode(f.read()).decode("utf-8") - data_uri = f"data:{mime_type};base64,{b64_data}" - - audio_models = [] - if "gemini/" in getattr(self, "model_id", ""): - audio_models.append(self.model_id) - if self.provider_keys.get("gemini"): - audio_models.extend( - self.gemini_flash_models - or [ - "gemini/gemini-3.5-flash-lite", - "gemini/gemini-3.5-flash", - ] - ) - audio_models = list(dict.fromkeys(audio_models)) - - last_err = None - while True: - rate_limited_gemini = False - for a_model in audio_models: - while True: - a_key = self._get_api_key(a_model) - if not a_key: - break - key_failed_hard = False - for part in ( - {"type": "image_url", "image_url": {"url": data_uri}}, - {"type": "file", "file": {"file_data": data_uri}}, - ): - try: - response = litellm.completion( - model=a_model, - api_key=a_key, - messages=[ - { - "role": "user", - "content": [ - {"type": "text", "text": question}, - part, - ], - } - ], - max_tokens=2048, - timeout=45, - ) - out = (response.choices[0].message.content or "").strip() - if out: - return out - except Exception as exc: - last_err = exc - err_low = str(exc).lower() - if any( - marker in err_low - for marker in ( - "401", - "402", - "403", - "authentication", - "missing authentication header", - "insufficient permissions", - "does not have sufficient permissions", - "quota", - "resource_exhausted", - ) - ): - key_failed_hard = True - break - if any(marker in err_low for marker in ("429", "rate limit exceeded")): - rate_limited_gemini = True - key_failed_hard = True - break - if key_failed_hard: - if not rate_limited_gemini and hasattr(self, "_rotate_api_key") and self._rotate_api_key("gemini"): - continue - break - break - - gemini_pool = self.provider_key_pools.get("gemini") or [] - if ( - rate_limited_gemini - and hasattr(self, "_rotate_api_key") - and self._provider_key_idx.get("gemini", 0) + 1 < len(gemini_pool) - and self._rotate_api_key("gemini") - ): - continue - break - - raise RuntimeError(str(last_err) if last_err else "No audio transcription model available.") - except Exception as e: - return f"Error transcribing audio '{audio_path}': {str(e)}" - - candidate_models = [] - priority_openrouter_models = [ - "openrouter/openrouter/free", - "openrouter/google/gemma-4-26b-a4b-it:free", - "openrouter/google/gemma-4-31b-it:free", - "openrouter/nvidia/nemotron-3-nano-30b-a3b:free", - "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/liquid/lfm-2.5-2.6b:free", - ] - - if self.provider_keys.get("openrouter"): - live_free_models = set() - try: - or_resp = requests.get( - "https://openrouter.ai/api/v1/models", - timeout=15, - headers={"User-Agent": "HF-Agents-Course-Bot/1.0"}, - ) - if or_resp.status_code == 200: - for item in or_resp.json().get("data", []): - m_id = str(item.get("id", "")).strip() - if m_id == "openrouter/free" or m_id.endswith(":free"): - live_free_models.add(f"openrouter/{m_id}") - except Exception as or_exc: - print(f"Warning: could not list OpenRouter models: {or_exc}") - - 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")) - )[:6] - 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() - for g_key in self.provider_key_pools.get("gemini") or [gemini_key]: - if not g_key: - continue - try: - models_resp = requests.get( - "https://generativelanguage.googleapis.com/v1beta/models", - params={"key": g_key}, - timeout=45, - ) - if models_resp.status_code == 200: - for m in models_resp.json().get("models", []): - if "generateContent" in m.get("supportedGenerationMethods", []): - raw_name = m.get("name", "") - if raw_name.startswith("models/"): - available_api_models.add("gemini/" + raw_name[len("models/"):]) - if available_api_models: - break - except Exception as list_exc: - print(f"Warning: could not list Gemini models via REST: {list_exc}") - - if available_api_models: - fallback_gemini_flash = [ - "gemini/gemini-3.5-flash-lite", - "gemini/gemini-3.5-flash", - ] - discovered_flash = sorted( - ( - m for m in available_api_models - if "flash" in m.lower() - and "2.5" not in m.lower() - and not any( - bad in m.lower() - for bad in ("tts", "image", "embedding", "aqa", "audio", "exp", "thinking") - ) - ), - key=lambda name: ( - 0 if "lite" in name.lower() else 1, - 1 if "preview" in name.lower() or "latest" in name.lower() else 0, - name, - ), - ) - self.gemini_flash_models = ( - discovered_flash - or [m for m in fallback_gemini_flash if m in available_api_models] - or sorted(available_api_models)[:3] - ) - candidate_models.extend(self.gemini_flash_models) - else: - self.gemini_flash_models = [ - "gemini/gemini-3.5-flash-lite", - "gemini/gemini-3.5-flash", - ] - candidate_models.extend(self.gemini_flash_models) - - if self.provider_keys.get("groq"): - candidate_models.extend([ - "groq/openai/gpt-oss-120b", - "groq/openai/gpt-oss-20b", - ]) - - if self.provider_keys.get("huggingface"): - candidate_models.extend([ - "huggingface/Qwen/Qwen2.5-72B-Instruct", - "huggingface/meta-llama/Llama-3.1-8B-Instruct", - ]) - - priority_rank = {name: idx for idx, name in enumerate(priority_openrouter_models)} - - def _model_priority(model_name: str) -> tuple[int, int, int, str]: - provider = model_name.split("/", 1)[0].lower() if "/" in model_name else "gemini" - low = model_name.lower() - if provider == "gemini": - group = 0 - sub_rank = 0 if "flash-lite" in low else 1 - elif provider == "groq": - group = 1 - sub_rank = 0 if "20b" in low else 1 - elif provider == "openrouter": - group = 2 - sub_rank = priority_rank.get(model_name, len(priority_rank)) - else: - group = 3 - sub_rank = 0 if "8b" in low else 1 - key_missing = 0 if self._get_api_key(model_name) else 1 - return (key_missing, group, sub_rank, 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.") - - class SafeLiteLLMModel(LiteLLMModel): - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self._explicit_api_key = kwargs.get("api_key") - - @staticmethod - def _sanitize_code_tags(text: str) -> str: - import ast - import re - - def _extract_valid_python(raw: str) -> str: - lines = [] - for line in raw.splitlines(): - stripped = line.lstrip() - if re.match(r"^(?:thoughts?|thinking)\s*:", stripped, flags=re.IGNORECASE): - lines.append("# " + stripped) - else: - lines.append(line) - - n = len(lines) - for start in range(n): - if not lines[start].strip(): - continue - for end in range(n, start, -1): - candidate = "\n".join(lines[start:end]).strip() - if not candidate: - continue - try: - ast.parse(candidate) - return candidate - except SyntaxError: - continue - return "\n".join(lines).strip() - - cleaned_text = re.sub(r"<\|[^|]+\|>", "", text) - cleaned_text = re.sub(r"]*>\s*```", "\n", cleaned_text, flags=re.IGNORECASE) - cleaned_text = re.sub(r"```\s*]*>", "\n", cleaned_text, flags=re.IGNORECASE) - - html_match = re.search(r"(.*?)", cleaned_text, flags=re.DOTALL | re.IGNORECASE) - if html_match: - inner = html_match.group(1) - inner = re.sub(r"```(?:py|python)?\s*\n?", "", inner, flags=re.IGNORECASE) - inner = re.sub(r"\n?```", "", inner) - inner = re.sub(r"]*>", "", inner, flags=re.IGNORECASE) - return f"\n{_extract_valid_python(inner)}\n" - - md_match = re.search( - r"```(?:py|python)?\s*\n(.*?)```", - cleaned_text, - flags=re.DOTALL | re.IGNORECASE, - ) - if md_match: - inner = re.sub(r"]*>", "", md_match.group(1), flags=re.IGNORECASE) - return f"\n{_extract_valid_python(inner)}\n" - - stripped_orphan_tags = re.sub(r"]*>", "", cleaned_text, flags=re.IGNORECASE).strip() - if stripped_orphan_tags != cleaned_text.strip() and stripped_orphan_tags: - return f"\n{_extract_valid_python(stripped_orphan_tags)}\n" - - return cleaned_text - - @classmethod - def _validate_message(cls, msg): - import json - import re - - if msg is None: - raise RuntimeError( - "Error in generating model output: empty model response (content=None)" - ) - - raw_content = getattr(msg, "content", None) - if isinstance(raw_content, list): - text_parts = [] - for part in raw_content: - if isinstance(part, dict): - if part.get("type") in ("text", "output_text", "reasoning", None) and ( - part.get("text") or part.get("thinking") - ): - text_parts.append(str(part.get("text") or part.get("thinking"))) - else: - p_type = getattr(part, "type", None) - p_text = getattr(part, "text", None) or getattr(part, "thinking", None) - if p_text and p_type in ("text", "output_text", "reasoning", None): - text_parts.append(str(p_text)) - content_str = "\n".join(text_parts).strip() - elif raw_content is None: - content_str = "" - else: - content_str = str(raw_content).strip() - - reasoning = ( - getattr(msg, "reasoning_content", None) - or getattr(msg, "reasoning", None) - or "" - ) - if isinstance(reasoning, list): - reasoning_str = "\n".join( - str(r.get("text", r) if isinstance(r, dict) else r).strip() - for r in reasoning - if r - ).strip() - else: - reasoning_str = str(reasoning).strip() if reasoning else "" - - tool_calls = getattr(msg, "tool_calls", None) - - if not content_str and tool_calls: - rendered_calls = [] - for tc in tool_calls: - fn_obj = getattr(tc, "function", None) - if fn_obj is None and isinstance(tc, dict): - fn_obj = tc.get("function") - fn_name = getattr(fn_obj, "name", None) if fn_obj is not None else None - if fn_name is None and isinstance(fn_obj, dict): - fn_name = fn_obj.get("name") - fn_args = getattr(fn_obj, "arguments", None) if fn_obj is not None else None - if fn_args is None and isinstance(fn_obj, dict): - fn_args = fn_obj.get("arguments") - if not fn_name: - continue - if isinstance(fn_args, str): - try: - parsed_args = json.loads(fn_args) if fn_args.strip() else {} - except Exception: - parsed_args = {"query": fn_args} - else: - parsed_args = fn_args or {} - if isinstance(parsed_args, dict): - rendered_calls.append( - f"print({fn_name}(**{json.dumps(parsed_args, ensure_ascii=False)}))" - ) - if rendered_calls: - content_str = "\n" + "\n".join(rendered_calls) + "\n" - - if not content_str and reasoning_str: - code_match = re.search( - r"(.*?|```(?:py|python)?\s*\n.*?```)", - reasoning_str, - flags=re.DOTALL | re.IGNORECASE, - ) - if code_match: - content_str = code_match.group(1).strip() - else: - first_line = reasoning_str.splitlines()[0].replace('"', "'") - content_str = f'\nprint(ask_web("{first_line[:120]}")) # fallback from reasoning\n' - - if not content_str: - raise RuntimeError( - "Error in generating model output: empty model response (content=None)" - ) - - cleaned = cls._sanitize_code_tags(content_str) - if not cleaned.strip(): - raise RuntimeError( - "Error in generating model output: empty model response after sanitization" - ) - - try: - msg.content = cleaned - except Exception: - pass - return msg - - def _prepare_call_kwargs(self, kwargs: dict) -> dict: - key = getattr(self, "_explicit_api_key", None) or kwargs.pop("api_key", None) - model_name = str(getattr(self, "model_id", "") or "") - if key: - if model_name.startswith("openrouter/"): - os.environ["OPENROUTER_API_KEY"] = key - elif model_name.startswith("groq/"): - os.environ["GROQ_API_KEY"] = key - elif model_name.startswith("huggingface/"): - os.environ["HF_TOKEN"] = key - os.environ["HUGGINGFACE_API_KEY"] = key - elif model_name.startswith("gemini/"): - os.environ["GEMINI_API_KEY"] = key - os.environ["GOOGLE_API_KEY"] = key - kwargs.setdefault("timeout", 30) - if model_name.startswith("openrouter/"): - kwargs["max_tokens"] = 4096 - return kwargs - - if hasattr(LiteLLMModel, "generate"): - def generate(self, *args, **kwargs): - kwargs = self._prepare_call_kwargs(dict(kwargs)) - return self._validate_message(super().generate(*args, **kwargs)) - else: - def __call__(self, *args, **kwargs): - kwargs = self._prepare_call_kwargs(dict(kwargs)) - return self._validate_message(super().__call__(*args, **kwargs)) - - self._model_cls = SafeLiteLLMModel - self.model_id = self.working_models[0] - print(f"Using primary LLM model: {self.model_id} (fallbacks: {self.working_models[1:]})") - - def _build_model(model_name: str): - is_openrouter = model_name.startswith("openrouter/") - kwargs = { - "model_id": model_name, - "api_key": self._get_api_key(model_name), - "max_tokens": 2048 if is_openrouter else 8192, - "num_retries": 0, - "timeout": 30, - } - if model_name.startswith("gemini/"): - kwargs["reasoning_effort"] = "none" - elif model_name.startswith("groq/"): - kwargs["tool_choice"] = "auto" - kwargs["parallel_tool_calls"] = False - model_instance = self._model_cls(**kwargs) - if model_name.startswith("groq/"): - for attr_name in ("kwargs", "completion_kwargs", "model_kwargs"): - target_dict = getattr(model_instance, attr_name, None) - if isinstance(target_dict, dict): - target_dict["tool_choice"] = "auto" - return model_instance - - @staticmethod - def _clean_exact_match_answer(raw_answer) -> str: - import re - - if raw_answer is None: - return "" - if isinstance(raw_answer, (list, tuple)): - text = ", ".join(str(item).strip() for item in raw_answer if str(item).strip()) - else: - text = str(raw_answer).strip() - - if not text or text.startswith("AGENT ERROR:"): - return text - - text = re.sub(r"^```(?:[a-zA-Z0-9_-]+)?\s*\n?", "", text) - text = re.sub(r"\n?```\s*$", "", text).strip() - - text = re.sub(r"(?im)^\s*(final\s*answer|answer)\s*:\s*", "", text).strip() - lines = [line.strip() for line in text.splitlines() if line.strip()] - if lines: - text = lines[-1] - - if len(text) >= 2 and ((text[0] == '"' and text[-1] == '"') or (text[0] == "'" and text[-1] == "'")): - text = text[1:-1].strip() - - if len(text) > 1 and text.endswith(".") and not re.search(r"(?:\d|\b[A-Za-z]\.[A-Za-z])\.$", text): - text = text[:-1].strip() - - return text - - def __call__(self, question: str, task_id: str = "") -> str: - prompt = question.strip() - if task_id: - prompt += ( - f"\n\nTask ID: {task_id}. If the question references an attached file " - f"or image, use download_task_file(task_id='{task_id}') to inspect it." - ) - - blocked_models = getattr(self, "_blocked_models", None) - if blocked_models is None: - blocked_models = set() - self._blocked_models = blocked_models - - blocked_providers = getattr(self, "_blocked_providers", None) - if blocked_providers is None: - blocked_providers = set() - self._blocked_providers = blocked_providers - - models_to_try = list(getattr(self, "working_models", []) or [self.model_id]) - if self.model_id and self.model_id not in models_to_try: - models_to_try.append(self.model_id) - - while True: - rate_limited_models = set() - rate_limited_providers = set() - - for model_name in models_to_try: - if not hasattr(self, "_build_model") or not hasattr(self, "agent"): - return "AGENT ERROR: Agent not initialized." - provider = model_name.split("/", 1)[0].lower() if "/" in model_name else "gemini" - while True: - if ( - model_name in blocked_models - or model_name in rate_limited_models - or provider in blocked_providers - ): - break - if not self._get_api_key(model_name): - blocked_providers.add(provider) - break - try: - self.model_id = model_name - self.agent.model = self._build_model(model_name) - result = self.agent.run(prompt) - cleaned = self._clean_exact_match_answer("" if result is None else str(result).strip()) - if cleaned and not cleaned.startswith("AGENT ERROR:"): - return cleaned - blocked_models.add(model_name) - break - except Exception as exc: - err_text = str(exc) - err_lower = err_text.lower() - print(f"[AGENT ERROR] task_id={task_id} model={model_name}: {err_text}") - if any( - marker in err_lower - for marker in ( - "401", - "402", - "403", - "authentication", - "missing authentication header", - "insufficient permissions", - "does not have sufficient permissions", - "free-models-per-day", - "quota", - "resource_exhausted", - ) - ): - if hasattr(self, "_rotate_api_key") and self._rotate_api_key(provider): - continue - blocked_providers.add(provider) - blocked_models.add(model_name) - break - if any(marker in err_lower for marker in ("429", "rate limit exceeded")): - rate_limited_models.add(model_name) - rate_limited_providers.add(provider) - break - if any( - marker in err_lower - for marker in ( - "400", - "404", - "not a valid model id", - "no endpoints found", - "provider returned error", - "context length", - "empty model response", - "unavailable for free", - ) - ): - blocked_models.add(model_name) - break - break - - rotated_any = False - if hasattr(self, "_rotate_api_key"): - for prov in rate_limited_providers: - if prov not in blocked_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 - - return "AGENT ERROR: All candidate models failed." - - -def _trim_tool_output(text: str, max_chars: int = 4000) -> str: - if not isinstance(text, str): - return str(text) - cleaned = "\n".join(line.strip() for line in text.splitlines() if line.strip()) - if len(cleaned) <= max_chars: - return cleaned - return cleaned[:max_chars] + "\n...[truncated]..." - - -def run_and_submit_all(profile: gr.OAuthProfile | None): - """ - 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 - - if profile: - username = f"{profile.username}" - print(f"User logged in: {username}") - else: - print("User not logged in.") - return "Please Login to Hugging Face with the button.", None - - api_url = DEFAULT_API_URL - questions_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}/tree/main" - if space_id - else ( - os.getenv("AGENT_CODE_URL") - or f"https://huggingface.co/spaces/{username.strip()}/Final_Assignment_Template/tree/main" - ).strip() - ) - print(agent_code) - - # 2. Fetch Questions - print(f"Fetching questions from: {questions_url}") - try: - response = requests.get(questions_url, timeout=45) - response.raise_for_status() - questions_data = response.json() - if not questions_data: - print("Fetched questions list is empty.") - return "Fetched questions list is empty or invalid format.", None - print(f"Fetched {len(questions_data)} questions.") - except requests.exceptions.RequestException as e: - print(f"Error fetching questions: {e}") - return f"Error fetching questions: {e}", None - except requests.exceptions.JSONDecodeError as e: - print(f"Error decoding JSON response from questions endpoint: {e}") - print(f"Response text: {response.text[:500]}") - return f"Error decoding server response for questions: {e}", None - except Exception as e: - print(f"An unexpected error occurred fetching questions: {e}") - return f"An unexpected error occurred fetching questions: {e}", None - - # 3. Run your Agent - from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeoutError - import json - import time - - results_log = [] - answers_payload = [] - partial_path = "/tmp/gaia_partial_results.json" - print(f"Running agent on {len(questions_data)} questions...") - for idx, item in enumerate(questions_data): - task_id = item.get("task_id") - question_text = item.get("question") - if not task_id or question_text is None: - print(f"Skipping item with missing task_id or question: {item}") - continue - if idx > 0: - time.sleep(3) - try: - with ThreadPoolExecutor(max_workers=1) as executor: - future = executor.submit(agent, question_text, task_id=task_id) - submitted_answer = future.result(timeout=120) - except FutureTimeoutError: - print(f"Timeout running agent on task {task_id} after 120s.") - submitted_answer = "AGENT ERROR: Task timed out after 120s." - except Exception as e: - print(f"Error running agent on task {task_id}: {e}") - submitted_answer = f"AGENT ERROR: {e}" - - answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer}) - results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer}) - try: - with open(partial_path, "w", encoding="utf-8") as f_part: - json.dump(results_log, f_part, ensure_ascii=False, indent=2) - except Exception: - pass - - if not answers_payload: - print("Agent did not produce any answers to submit.") - return "Agent did not produce any answers to submit.", pd.DataFrame(results_log) - - # 4. Prepare Submission - submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload} - status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..." - print(status_update) - - # 5. Submit - print(f"Submitting {len(answers_payload)} answers to: {submit_url}") - try: - response = requests.post(submit_url, json=submission_data, timeout=45) - response.raise_for_status() - result_data = response.json() - final_status = ( - f"Submission Successful!\n" - f"User: {result_data.get('username')}\n" - f"Overall Score: {result_data.get('score', 'N/A')}% " - f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n" - f"Message: {result_data.get('message', 'No message received.')}" - ) - print("Submission successful.") - results_df = pd.DataFrame(results_log) - return final_status, results_df - except requests.exceptions.HTTPError as e: - error_detail = f"Server responded with status {e.response.status_code}." - try: - error_json = e.response.json() - error_detail += f" Detail: {error_json.get('detail', e.response.text)}" - except requests.exceptions.JSONDecodeError: - error_detail += f" Response: {e.response.text[:500]}" - status_message = f"Submission Failed: {error_detail}" - print(status_message) - results_df = pd.DataFrame(results_log) - return status_message, results_df - except requests.exceptions.Timeout: - status_message = "Submission Failed: The request timed out." - print(status_message) - results_df = pd.DataFrame(results_log) - return status_message, results_df - except requests.exceptions.RequestException as e: - status_message = f"Submission Failed: Network error - {e}" - print(status_message) - results_df = pd.DataFrame(results_log) - return status_message, results_df - except Exception as e: - status_message = f"An unexpected error occurred during submission: {e}" - print(status_message) - results_df = pd.DataFrame(results_log) - return status_message, results_df - - # --- Build Gradio Interface using Blocks --- with gr.Blocks() as demo: gr.Markdown("# Basic Agent Evaluation Runner") @@ -3414,10 +1812,10 @@ with gr.Blocks() as demo: ) if __name__ == "__main__": - print("\n" + "-"*30 + " App Starting " + "-"*30) + print("\n" + "-" * 30 + " App Starting " + "-" * 30) # Check for SPACE_HOST and SPACE_ID at startup for information space_host_startup = os.getenv("SPACE_HOST") - space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup + space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup if space_host_startup: print(f"✅ SPACE_HOST found: {space_host_startup}") @@ -3425,14 +1823,14 @@ if __name__ == "__main__": else: print("ℹ️ SPACE_HOST environment variable not found (running locally?).") - if space_id_startup: # Print repo URLs if SPACE_ID is found + if space_id_startup: # Print repo URLs if SPACE_ID is found print(f"✅ SPACE_ID found: {space_id_startup}") - print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}") - print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main") + print(f" Repo URL: [https://huggingface.co/spaces/](https://huggingface.co/spaces/){space_id_startup}") + print(f" Repo Tree URL: [https://huggingface.co/spaces/](https://huggingface.co/spaces/){space_id_startup}/tree/main") else: print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.") - print("-"*(60 + len(" App Starting ")) + "\n") + print("-" * (60 + len(" App Starting ")) + "\n") print("Launching Gradio Interface for Basic Agent Evaluation...") demo.launch(debug=True, share=False) \ No newline at end of file