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 # --- Constants --- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space" # --- Basic Agent Definition --- class BasicAgent: def __init__(self): import re import base64 import mimetypes import threading import litellm from smolagents import CodeAgent, LiteLLMModel, MultiStepAgent, 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"), "nvidia_nim": ("NVIDIA_API_KEY", "NVIDIA_NIM_API_KEY", "NIM_API_KEY"), } 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" if token.startswith("nvapi-"): return "nvidia_nim" 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 "" nvidia_key = self.provider_key_pools["nvidia_nim"][0] if self.provider_key_pools["nvidia_nim"] else "" self.provider_keys = { "openrouter": openrouter_key, "groq": groq_key, "huggingface": hf_key, "gemini": gemini_key, "nvidia_nim": nvidia_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, GEMINI_API_KEY, or NVIDIA_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 if nvidia_key: os.environ["NVIDIA_API_KEY"] = nvidia_key os.environ["NVIDIA_NIM_API_KEY"] = nvidia_key self._state_lock = threading.RLock() def _sync_provider_env(provider: str, key: str) -> None: with self._state_lock: self.provider_keys[provider] = key if not key: return if provider == "openrouter": os.environ["OPENROUTER_API_KEY"] = key elif provider == "groq": os.environ["GROQ_API_KEY"] = key elif provider == "huggingface": os.environ["HF_TOKEN"] = key os.environ["HUGGINGFACE_API_KEY"] = key elif provider == "gemini": self.gemini_key = key os.environ["GEMINI_API_KEY"] = key os.environ["GOOGLE_API_KEY"] = key elif provider == "nvidia_nim": os.environ["NVIDIA_API_KEY"] = key os.environ["NVIDIA_NIM_API_KEY"] = key def _get_api_key(model_name: str) -> str | None: with self._state_lock: 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] _sync_provider_env(provider, key) return key _sync_provider_env(provider, "") return None def _rotate_api_key(provider: str, permanent: bool = False) -> bool: with self._state_lock: pool = self.provider_key_pools.get(provider) or [] cur_idx = self._provider_key_idx.get(provider, 0) if permanent and 0 <= cur_idx < len(pool): pool.pop(cur_idx) next_idx = cur_idx else: next_idx = cur_idx + 1 self._provider_key_idx[provider] = next_idx if next_idx < len(pool): _sync_provider_env(provider, pool[next_idx]) return True _sync_provider_env(provider, "") return False def _reset_key_indices() -> None: with self._state_lock: for prov, pool in self.provider_key_pools.items(): self._provider_key_idx[prov] = 0 _sync_provider_env(prov, pool[0] if pool else "") def _tool_timeout(default_timeout: float, min_timeout: float = 4.0) -> float: import time local_state = getattr(self, "_local_state", None) deadline = getattr(local_state, "deadline", None) if local_state is not None else None if deadline is None: deadline = getattr(self, "_task_deadline", None) if deadline is None: return default_timeout remaining = deadline - time.monotonic() if remaining <= 2.5: raise RuntimeError("Task time budget exhausted") return max(min_timeout, min(default_timeout, remaining - 2.0)) self._tool_timeout = _tool_timeout self._sync_provider_env = _sync_provider_env self._get_api_key = _get_api_key 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. Args: url: The HTTP/HTTPS URL to fetch. """ import re from html import unescape try: response = requests.get( url, timeout=_tool_timeout(15.0), 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", preferred_filename: str = "", ) -> 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. preferred_filename: Optional original attachment filename from the task metadata. """ import re import time from urllib.parse import unquote clean_id = (task_id or "").strip() if 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_path 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: resp = None for attempt in range(3): try: resp = requests.get( url, timeout=(8.0, _tool_timeout(25.0, min_timeout=5.0)), headers={"User-Agent": "Mozilla/5.0"}, ) if resp.status_code in {429, 502, 503, 504} and attempt < 2: _tool_timeout(4.0, min_timeout=1.0) time.sleep(1.5 * (attempt + 1)) continue break except Exception as exc: last_err = exc if "task time budget exhausted" in str(exc).lower(): return f"Error downloading file for task '{clean_id}': {str(exc)}" if attempt < 2: try: _tool_timeout(4.0, min_timeout=1.0) time.sleep(1.5 * (attempt + 1)) continue except Exception: resp = None break resp = None break if resp is None or resp.status_code == 404: continue try: resp.raise_for_status() except Exception as exc: last_err = exc continue if not resp.content: continue content_disp = resp.headers.get("Content-Disposition", "") filename = safe_pref_name if not 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*"?([^";]+)"?', 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(safe_out_dir, filename) with open(out_path, "wb") as f: f.write(resp.content) return out_path 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)." self._download_task_file = download_task_file @tool def read_local_file(file_path: str) -> str: """Reads text, PDF, DOCX, PPTX, ZIP archive, or spreadsheet content from a local file downloaded by download_task_file. Args: file_path: Local path to the downloaded file. """ import re import xml.etree.ElementTree as ET import zipfile def _read_single(path: str, max_chars: int) -> str: f_ext = os.path.splitext(path)[1].lower() if f_ext in {".xlsx", ".xlsm", ".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 == ".docx": try: with zipfile.ZipFile(path, "r") as zf: if "word/document.xml" not in zf.namelist(): return f"Invalid DOCX archive '{path}': missing word/document.xml." root = ET.fromstring(zf.read("word/document.xml")) paragraphs = [] for p_elem in root.iter(): if p_elem.tag.endswith("}p"): runs = [ t_elem.text for t_elem in p_elem.iter() if t_elem.tag.endswith("}t") and t_elem.text ] line = "".join(runs).strip() if line: paragraphs.append(line) text = "\n".join(paragraphs) or "Empty DOCX document." except Exception as docx_exc: return f"Error reading DOCX '{path}': {str(docx_exc)}" elif f_ext == ".pptx": try: with zipfile.ZipFile(path, "r") as zf: slide_names = [ name for name in zf.namelist() if re.fullmatch(r"ppt/slides/slide\d+\.xml", name) ] slide_names.sort( key=lambda n: int(re.search(r"slide(\d+)\.xml$", n).group(1)) ) slides_out = [] for idx, s_name in enumerate(slide_names, start=1): root = ET.fromstring(zf.read(s_name)) s_lines = [] for p_elem in root.iter(): if p_elem.tag.endswith("}p"): runs = [ t_elem.text for t_elem in p_elem.iter() if t_elem.tag.endswith("}t") and t_elem.text ] line = "".join(runs).strip() if line: s_lines.append(line) slides_out.append(f"=== Slide {idx} ===\n" + ("\n".join(s_lines) or "(empty)")) text = "\n\n".join(slides_out) or "Empty PPTX presentation." except Exception as pptx_exc: return f"Error reading PPTX '{path}': {str(pptx_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() office_zip_exts = {".xlsx", ".xlsm", ".xls", ".docx", ".pptx"} if ext == ".zip" or (ext not in office_zip_exts and 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)}" self._read_local_file = read_local_file @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. """ from concurrent.futures import ThreadPoolExecutor import re from html import unescape from urllib.parse import parse_qs, unquote, urlparse clean_q = (query or "").strip() if not clean_q: return "Empty search query." def _clean_ddg_href(raw_href: str) -> str: h = unescape((raw_href or "").strip()) if h.startswith("//"): h = "https:" + h if "duckduckgo.com/l/?" in h or h.startswith("/l/?"): parsed = urlparse(h) uddg = parse_qs(parsed.query).get("uddg") if uddg and uddg[0]: return unquote(uddg[0]) return h results_out = [] try: ddgs_timeout = _tool_timeout(7.0, min_timeout=3.0) def _run_ddgs(): try: from ddgs import DDGS except ImportError: from duckduckgo_search import DDGS try: client = DDGS(timeout=int(ddgs_timeout)) except TypeError: client = DDGS() return client.text(clean_q, max_results=5) or [] ddgs_pool = ThreadPoolExecutor(max_workers=1) ddgs_fut = ddgs_pool.submit(_run_ddgs) try: raw_results = ddgs_fut.result(timeout=ddgs_timeout) finally: ddgs_pool.shutdown(wait=False, cancel_futures=True) for item in raw_results: if not isinstance(item, dict): continue title = str(item.get("title", "")).strip() href = _clean_ddg_href(str(item.get("href", ""))) 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 as ddgs_exc: if "task time budget exhausted" in str(ddgs_exc).lower(): return f"Web search aborted: {ddgs_exc}" 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 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36", "Accept-Language": "en-US,en;q=0.9", }, timeout=_tool_timeout(7.0, min_timeout=3.0), ) resp.raise_for_status() link_matches = re.findall( r"(?is)]*\bclass=['\"][^'\"]*result__a[^'\"]*['\"][^>]*)>(.*?)", resp.text, ) snippets = re.findall( r"(?is)<(?:a|div)\b[^>]*\bclass=['\"][^'\"]*result__snippet[^'\"]*['\"][^>]*>(.*?)", resp.text, ) for idx, (tag_attrs, raw_title) in enumerate(link_matches[:5]): href_m = re.search(r"\bhref=['\"]([^'\"]+)['\"]", tag_attrs, flags=re.IGNORECASE) href = _clean_ddg_href(href_m.group(1)) if href_m else "" 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 as html_exc: if "task time budget exhausted" in str(html_exc).lower(): return f"Web search aborted: {html_exc}" if not results_out: try: lite_resp = requests.post( "https://lite.duckduckgo.com/lite/", data={"q": clean_q}, 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", }, timeout=_tool_timeout(7.0, min_timeout=3.0), ) lite_resp.raise_for_status() lite_links = re.findall( r"(?is)]*\bclass=['\"][^'\"]*result-link[^'\"]*['\"][^>]*)>(.*?)", lite_resp.text, ) lite_snippets = re.findall( r"(?is)]*\bclass=['\"][^'\"]*result-snippet[^'\"]*['\"][^>]*>(.*?)", lite_resp.text, ) for idx, (tag_attrs, raw_title) in enumerate(lite_links[:5]): href_m = re.search(r"\bhref=['\"]([^'\"]+)['\"]", tag_attrs, flags=re.IGNORECASE) href = _clean_ddg_href(href_m.group(1)) if href_m else "" title = re.sub(r"\s+", " ", unescape(re.sub(r"(?s)<[^>]+>", " ", raw_title))).strip() raw_snip = lite_snippets[idx] if idx < len(lite_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 as lite_exc: if "task time budget exhausted" in str(lite_exc).lower(): return f"Web search aborted: {lite_exc}" 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 headers = {"User-Agent": "HF-Agents-Course-Bot/1.0"} api_endpoint = "https://en.wikipedia.org/w/api.php" use_2022 = ("2022" in query.lower()) or bool(getattr(self, "_prefer_2022_wiki", False)) clean_query = re.sub(r"\b2022\b", "", query).strip() or query.strip() cache_key = f"{clean_query.lower()}|2022={use_2022}" if cache_key in wiki_cache: return wiki_cache[cache_key] try: search_resp = None for attempt in range(2): search_resp = requests.get( api_endpoint, params={ "action": "query", "list": "search", "srsearch": clean_query, "format": "json", "srlimit": 5, }, headers=headers, timeout=_tool_timeout(8.0, min_timeout=2.5), ) if search_resp.status_code == 429 and attempt < 1: _tool_timeout(3.0, min_timeout=1.0) time.sleep(0.5) 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=_tool_timeout(6.0, min_timeout=2.0), ) 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(2): parse_resp = requests.get( api_endpoint, params=parse_params, headers=headers, timeout=_tool_timeout(8.0, min_timeout=2.5), ) if parse_resp.status_code == 429 and attempt < 1: _tool_timeout(3.0, min_timeout=1.0) time.sleep(0.5) 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) > 4800: disc_match = re.search(r"(?i)\bdiscography\b", text) if disc_match: start_pos = max(0, disc_match.start() - 300) text = text[:1200] + "\n...\n" + text[start_pos : start_pos + 3600] else: text = text[:2400] + "\n...\n" + text[-2400:] 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 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 "No results." 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=_tool_timeout(7.0, min_timeout=2.5), ) 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 as wiki_exc: if "task time budget exhausted" in str(wiki_exc).lower(): return "No results." try: ddg_resp = requests.post( "https://html.duckduckgo.com/html/", data={"q": cleaned_query}, headers={"User-Agent": "Mozilla/5.0"}, timeout=_tool_timeout(7.0, min_timeout=2.5), ) 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 "No results." def _litellm_route_kwargs(model_name: str, api_key: str) -> dict: return {"model": model_name, "api_key": api_key} def _is_daily_quota_exhausted(err_lower: str) -> bool: return any( marker in err_lower for marker in ( "free-models-per-day", "rate limit exceeded: free-models-per-day", "daily limit", "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. 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("groq") or self.provider_key_pools.get("groq"): vision_candidates.extend([ "groq/meta-llama/llama-4-scout-17b-16e-instruct", "groq/meta-llama/llama-4-maverick-17b-128e-instruct", ]) if self.provider_keys.get("gemini"): vision_candidates.extend( self.gemini_flash_models or [ "gemini/gemini-3-flash-preview", "gemini/gemini-flash-latest", ] ) 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", ]) if self.provider_keys.get("nvidia_nim"): vision_candidates.extend([ "nvidia_nim/moonshotai/kimi-k3_1-pro", "nvidia_nim/nvidia/nemotron-3-ultra-550b-a55b", ]) 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 rate_limited_providers = set() dead_models = getattr(self, "_dead_models", None) if dead_models is None: dead_models = set() self._dead_models = dead_models for v_model in unique_vision: if v_model in dead_models: continue v_provider = v_model.split("/", 1)[0].lower() if "/" in v_model else "gemini" if v_provider in rate_limited_providers: continue while True: v_key = self._get_api_key(v_model) if not v_key: break try: call_kwargs = _litellm_route_kwargs(v_model, v_key) call_kwargs["num_retries"] = 0 call_kwargs["max_retries"] = 0 call_kwargs["max_tokens"] = 1024 call_kwargs["timeout"] = _tool_timeout(20.0) if v_provider == "openrouter" or (v_provider == "gemini" and "gemma" not in v_model.lower()): call_kwargs["reasoning_effort"] = "low" response = litellm.completion( **call_kwargs, messages=[ { "role": "user", "content": [ {"type": "text", "text": question}, { "type": "image_url", "image_url": {"url": f"data:{mime_type};base64,{b64_data}"}, }, ], } ], ) msg_content = response.choices[0].message.content if isinstance(msg_content, list): out = "\n".join( str(p.get("text", "")).strip() for p in msg_content if isinstance(p, dict) and p.get("text") ).strip() else: out = (msg_content or "").strip() if out: return out break except Exception as exc: last_err = exc err_low = str(exc).lower() if "task time budget exhausted" in err_low: raise if any( marker in err_low for marker in ( "400", "badrequesterror", "reasoning is mandatory", "cannot be disabled", "404", "not found", "model_not_found", "decommissioned", "unsupported", ) ): dead_models.add(v_model) break if any( marker in err_low for marker in ( "401", "402", "403", "authentication", "invalid api key", "permission_denied", "insufficient permissions", ) ): if hasattr(self, "_rotate_api_key") and self._rotate_api_key( v_provider, permanent=True ): continue rate_limited_providers.add(v_provider) break if any( marker in err_low for marker in ( "429", "rate limit", "free-models-per-day", "quota", "resource_exhausted", ) ): if hasattr(self, "_rotate_api_key") and self._rotate_api_key(v_provider): continue if _is_daily_quota_exhausted(err_low): rate_limited_providers.add(v_provider) else: with self._state_lock: pool = self.provider_key_pools.get(v_provider) or [] self._provider_key_idx[v_provider] = 0 if hasattr(self, "_sync_provider_env"): self._sync_provider_env(v_provider, pool[0] if pool else "") break break raise RuntimeError(str(last_err) if last_err else "No vision model available.") except Exception as e: print(f"[IMAGE ERR] path={image_path}: {type(e).__name__}: {e}", flush=True) raise RuntimeError(f"Error inspecting image '{image_path}': {str(e)}") from e @tool def inspect_youtube( url: str, question: str = "Provide a detailed account of all visual scenes, on-screen text, counts, actions, and spoken audio in this video.", ) -> str: """Fetches YouTube video metadata, captions/transcripts, and multimodal visual/audio analysis for a given YouTube URL or video ID. Args: url: YouTube video URL or 11-character video ID. question: Specific question or instruction about what to look for or extract from the video. """ import json import re from html import unescape def _extract_json_array_after(source: str, key_marker: str): idx = source.find(key_marker) if idx == -1: return None start = source.find("[", idx + len(key_marker)) if start == -1: return None depth = 0 in_str = False escape = False for pos in range(start, len(source)): ch = source[pos] if in_str: if escape: escape = False elif ch == "\\": escape = True elif ch == '"': in_str = False continue if ch == '"': in_str = True elif ch == "[": depth += 1 elif ch == "]": depth -= 1 if depth == 0: try: return json.loads(source[start : pos + 1]) except Exception: return None return None try: 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", "Cookie": "SOCS=CAI", } sections = [f"Video ID: {video_id}", f"URL: {watch_url}"] has_title = False has_desc = False has_transcript = False caption_tracks = [] try: oembed_resp = requests.get( "https://www.youtube.com/oembed", params={"url": watch_url, "format": "json"}, headers=headers, timeout=_tool_timeout(8.0, min_timeout=2.0), ) if oembed_resp.status_code == 200: oembed = oembed_resp.json() if oembed.get("title"): sections.append(f"Title: {oembed['title']}") has_title = True if oembed.get("author_name"): sections.append(f"Channel: {oembed['author_name']}") except Exception as req_exc: if "task time budget exhausted" in str(req_exc).lower(): raise innertube_clients = [ ( "ANDROID", "19.09.37", "com.google.android.youtube/19.09.37 (Linux; U; Android 11) gzip", ), ( "IOS", "19.29.1", "com.google.ios.youtube/19.29.1 (iPhone16,2; U; CPU iOS 17_5_1 like Mac OS X;)", ), ] for client_name, client_ver, client_ua in innertube_clients: if has_desc and caption_tracks: break try: player_resp = requests.post( "https://www.youtube.com/youtubei/v1/player", params={"prettyPrint": "false"}, headers={ "Content-Type": "application/json", "User-Agent": client_ua, }, json={ "context": { "client": { "clientName": client_name, "clientVersion": client_ver, "hl": "en", "gl": "US", } }, "videoId": video_id, }, timeout=_tool_timeout(8.0, min_timeout=2.0), ) if player_resp.status_code == 200: player_data = player_resp.json() v_details = player_data.get("videoDetails") or {} if not has_title and v_details.get("title"): sections.append(f"Title: {v_details['title']}") has_title = True if not has_desc and v_details.get("shortDescription"): sections.append(f"Description:\n{str(v_details['shortDescription'])[:2000]}") has_desc = True if not caption_tracks: tracks = ( (player_data.get("captions") or {}) .get("playerCaptionsTracklistRenderer", {}) .get("captionTracks") ) if isinstance(tracks, list) and tracks: caption_tracks = tracks except Exception as req_exc: if "task time budget exhausted" in str(req_exc).lower(): raise if not has_desc or not caption_tracks: try: page_resp = requests.get( watch_url, headers=headers, timeout=_tool_timeout(10.0, min_timeout=2.0), ) if page_resp.status_code == 200: html_text = page_resp.text if not has_desc: desc_match = re.search(r'"shortDescription"\s*:\s*"((?:\\.|[^"\\])*)"', html_text) if desc_match: try: desc_val = json.loads(f'"{desc_match.group(1)}"') except Exception: desc_val = unescape(desc_match.group(1)) sections.append(f"Description:\n{desc_val[:2000]}") has_desc = True if not caption_tracks: parsed_tracks = _extract_json_array_after(html_text, '"captionTracks"') if isinstance(parsed_tracks, list) and parsed_tracks: caption_tracks = parsed_tracks except Exception as e: if "task time budget exhausted" in str(e).lower(): raise if caption_tracks: sorted_tracks = sorted( caption_tracks, key=lambda t: ( 0 if str(t.get("languageCode", "")).lower().startswith("en") else 1, 1 if str(t.get("kind", "")).lower() == "asr" else 0, ), ) for tr in sorted_tracks[:3]: base_url = tr.get("baseUrl") if not base_url: continue try: tr_resp = requests.get( unescape(base_url), headers=headers, timeout=_tool_timeout(8.0, min_timeout=2.0), ) 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]}") has_transcript = True break except Exception as tr_exc: if "task time budget exhausted" in str(tr_exc).lower(): raise continue visual_markers = ( "visual", "scene", "appear", "color", "colour", "wear", "wearing", "shirt", "count", "how many", "bird", "species", "animal", "screen", "shown", "show", "frame", "background", "sign", "logo", "action", "doing", "see", "look", "watch", ) needs_video_analysis = (not has_transcript) or any( marker in (question or "").lower() for marker in visual_markers ) video_analyzed = False gemini_pool = self.provider_key_pools.get("gemini") or [] if gemini_pool and needs_video_analysis: gemini_models = list( dict.fromkeys( [ "gemini/gemini-flash-latest", "gemini/gemini-2.5-flash", ] + (self.gemini_flash_models or []) ) )[:2] while not video_analyzed: rate_limited_gemini = False for g_model in gemini_models: raw_model = g_model[len("gemini/"):] if g_model.startswith("gemini/") else g_model while True: g_key = self._get_api_key(g_model) if not g_key: break try: gm_resp = requests.post( f"https://generativelanguage.googleapis.com/v1beta/models/{raw_model}:generateContent", params={"key": g_key}, headers={"Content-Type": "application/json"}, json={ "contents": [ { "parts": [ {"file_data": {"file_uri": watch_url}}, {"text": question}, ] } ], "generationConfig": { "maxOutputTokens": 2048, "thinkingConfig": {"thinkingBudget": 0}, }, }, timeout=_tool_timeout(20.0, min_timeout=4.0), ) if gm_resp.status_code == 200: candidates = gm_resp.json().get("candidates") or [] if candidates: parts = (candidates[0].get("content") or {}).get("parts") or [] analysis_text = "\n".join( str(p.get("text", "")).strip() for p in parts if isinstance(p, dict) and p.get("text") ).strip() if analysis_text: sections.append(f"Multimodal Video Analysis:\n{analysis_text}") video_analyzed = True break break err_low = gm_resp.text.lower() if gm_resp.status_code in (401, 402, 403): if hasattr(self, "_rotate_api_key") and self._rotate_api_key( "gemini", permanent=True ): continue break if ( gm_resp.status_code == 429 or "quota" in err_low or "resource_exhausted" in err_low ): rate_limited_gemini = True break break except Exception as gm_exc: if "task time budget exhausted" in str(gm_exc).lower(): raise break if video_analyzed: break if ( not video_analyzed and 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 if not has_transcript and not video_analyzed: sections.append( "Transcript/Video Analysis Status: unavailable. " "Use web_search or search_wikipedia with the video title, channel, or quoted dialogue." ) return _trim_tool_output("\n\n".join(sections), max_chars=12000) except Exception as e: return f"Error inspecting YouTube '{url}': {str(e)}" @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=_tool_timeout(20.0), ) 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): if hasattr(self, "_rotate_api_key") and self._rotate_api_key("groq", permanent=True): continue break if groq_resp.status_code == 429 or "quota" in err_body or "resource_exhausted" in err_body: 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", permanent=False) ): continue break except Exception as groq_exc: 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") audio_models = [] if getattr(self, "model_id", "").startswith("gemini/"): audio_models.append(self.model_id) if self.provider_key_pools.get("gemini"): audio_models.extend( self.gemini_flash_models or [ "gemini/gemini-3-flash-preview", "gemini/gemini-flash-latest", ] ) audio_models = list(dict.fromkeys(audio_models))[:2] last_err = None while True: rate_limited_gemini = False for a_model in audio_models: raw_model = a_model[len("gemini/"):] if a_model.startswith("gemini/") else a_model while True: a_key = self._get_api_key(a_model) if not a_key: break try: gm_resp = requests.post( f"https://generativelanguage.googleapis.com/v1beta/models/{raw_model}:generateContent", params={"key": a_key}, headers={"Content-Type": "application/json"}, json={ "contents": [ { "parts": [ {"inline_data": {"mime_type": mime_type, "data": b64_data}}, {"text": question}, ] } ], "generationConfig": { "maxOutputTokens": 2048, "thinkingConfig": {"thinkingBudget": 0}, }, }, timeout=_tool_timeout(30.0), ) if gm_resp.status_code == 200: candidates = gm_resp.json().get("candidates") or [] if candidates: parts = (candidates[0].get("content") or {}).get("parts") or [] out = "\n".join( str(p.get("text", "")).strip() for p in parts if isinstance(p, dict) and p.get("text") ).strip() if out: return out break err_low = gm_resp.text.lower() if gm_resp.status_code in (401, 402, 403): if hasattr(self, "_rotate_api_key") and self._rotate_api_key( "gemini", permanent=True ): continue break if ( gm_resp.status_code == 429 or "quota" in err_low or "resource_exhausted" in err_low ): rate_limited_gemini = True break break except Exception as exc: if "task time budget exhausted" in str(exc).lower(): raise last_err = exc 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)}" self._transcribe_audio = transcribe_audio candidate_models = [] priority_openrouter_models = [ "openrouter/meta-llama/llama-3.3-70b-instruct:free", "openrouter/qwen/qwen3-next-80b-a3b-instruct:free", "openrouter/google/gemma-3-27b-it:free", "openrouter/mistralai/mistral-small-3.1-24b-instruct:free", "openrouter/openrouter/free", ] if self.provider_keys.get("openrouter"): live_free_models = set() try: or_resp = requests.get( "https://openrouter.ai/api/v1/models", timeout=10, 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] candidate_models.extend(curated_live[:2] or ["openrouter/openrouter/free"]) else: candidate_models.extend(priority_openrouter_models[:2]) 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=15, ) 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 not any( bad in low_id for bad in ( "tts", "image", "imagen", "veo", "embedding", "aqa", "audio", "robotics", "computer-use", "deep-research", "omni", "exp", "thinking", "gemma", "flash-lite", ) ): 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: 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) if self.provider_keys.get("groq"): # Wykluczono gpt-oss-* z CodeAgent (zawsze wywołują natywne narzędzia i wywalają tool_choice=none) preferred_groq = [ "groq/llama-3.3-70b-versatile", "groq/moonshotai/kimi-k2-instruct", "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/llama-3.1-8b-instant", ] live_groq = [] try: groq_resp = requests.get( "https://api.groq.com/openai/v1/models", headers={"Authorization": f"Bearer {self.provider_keys['groq']}"}, timeout=10, ) if groq_resp.status_code == 200: for item in groq_resp.json().get("data", []): g_id = str(item.get("id", "")).strip() if g_id and not any( bad in g_id.lower() for bad in ( "whisper", "tts", "orpheus", "guard", "safeguard", "embed", "compound", "allam", "gpt-oss", ) ): live_groq.append(f"groq/{g_id}") except Exception as groq_exc: print(f"Warning: could not list Groq models: {groq_exc}") print(f"[GROQ LIVE MODELS] {live_groq}", flush=True) if live_groq: live_set = set(live_groq) curated_groq = [m for m in preferred_groq if m in live_set] extra_groq = sorted( (m for m in live_groq if m not in curated_groq), key=lambda name: ( 0 if any(k in name.lower() for k in ("kimi", "70b", "maverick", "scout", "32b", "27b")) else 1, name, ), ) selected_groq = list(dict.fromkeys(curated_groq + extra_groq))[:4] candidate_models.extend(selected_groq) else: candidate_models.extend(preferred_groq[:4]) if self.provider_keys.get("huggingface"): candidate_models.extend([ "huggingface/Qwen/Qwen2.5-72B-Instruct", "huggingface/meta-llama/Llama-3.3-70B-Instruct", ]) if self.provider_keys.get("nvidia_nim"): candidate_models.extend([ "nvidia_nim/moonshotai/kimi-k3_1-pro", "nvidia_nim/nvidia/nemotron-3-ultra-550b-a55b", ]) priority_rank = {name: idx for idx, name in enumerate(priority_openrouter_models)} def _model_priority(model_name: str) -> tuple[int, int, int, tuple[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 == "nvidia_nim": if "nemotron" in low or "550b" in low: sub_rank = 0 elif "kimi" in low: sub_rank = 1 else: sub_rank = 2 return (key_missing, 0, sub_rank, (0, 0), model_name) if provider == "openrouter": sub_rank = priority_rank.get(model_name, len(priority_rank)) return (key_missing, 1, sub_rank, (0, 0), model_name) if provider == "gemini": if low == "gemini/gemini-3-flash-preview": return (key_missing, 2, 0, (0, 0), model_name) if low == "gemini/gemini-flash-latest": return (key_missing, 2, 1, (0, 0), model_name) return (key_missing, 2, 2, (0, 0), model_name) if provider == "groq": if "llama-3.3-70b" in low or "kimi" in low: sub_rank = 0 elif "maverick" in low or "scout" in low: sub_rank = 1 elif "32b" in low or "27b" in low: sub_rank = 2 else: sub_rank = 3 return (key_missing, 3, sub_rank, (0, 0), model_name) if provider == "huggingface": return (key_missing, 4, 0, (0, 0), model_name) return (key_missing, 5, 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.") sig = inspect.signature(CodeAgent.__init__) supports_custom_tags = "code_block_tags" in sig.parameters code_open_tag, code_close_tag = ("", "") if supports_custom_tags else ("```py", "```") class SafeLiteLLMModel(LiteLLMModel): open_tag = code_open_tag close_tag = code_close_tag def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._explicit_api_key = kwargs.get("api_key") self._explicit_api_base = kwargs.get("api_base") self._last_llm_error = None if self._explicit_api_key: self.api_key = self._explicit_api_key if self._explicit_api_base: self.api_base = self._explicit_api_base if hasattr(LiteLLMModel, "generate"): def generate(self, *args, **kwargs): from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeoutError import copy import time litellm.suppress_debug_info = True litellm.num_retries = 0 t0 = time.monotonic() def _trim_messages(raw_msgs): if not isinstance(raw_msgs, list): return raw_msgs selected = ([raw_msgs[0]] + raw_msgs[-3:]) if len(raw_msgs) > 4 else list(raw_msgs) out = [] for m in selected: m_copy = copy.copy(m) if isinstance(m_copy, dict): content = m_copy.get("content") if isinstance(content, str) and len(content) > 2500: m_copy["content"] = content[:1200] + "\n...[trimmed]...\n" + content[-1200:] else: content = getattr(m_copy, "content", None) if isinstance(content, str) and len(content) > 2500: try: setattr( m_copy, "content", content[:1200] + "\n...[trimmed]...\n" + content[-1200:], ) except Exception: pass out.append(m_copy) return out if "messages" in kwargs: kwargs["messages"] = _trim_messages(kwargs["messages"]) elif len(args) >= 1: new_args = list(args) new_args[0] = _trim_messages(new_args[0]) args = tuple(new_args) call_kwargs = self._prepare_call_kwargs(dict(kwargs)) call_kwargs["num_retries"] = 0 call_kwargs["max_retries"] = 0 req_timeout = min( float(call_kwargs.get("timeout") or getattr(self, "timeout", None) or 14.0), 14.0, ) call_kwargs["timeout"] = req_timeout litellm.request_timeout = req_timeout hard_timeout = req_timeout + 2.0 executor = ThreadPoolExecutor(max_workers=1) future = executor.submit(super().generate, *args, **call_kwargs) try: raw_msg = future.result(timeout=hard_timeout) msg = self._validate_message(raw_msg) self._last_llm_error = None return msg except FutureTimeoutError: timeout_exc = TimeoutError( f"LLM call timed out after {hard_timeout:.1f}s for {self.model_id}" ) self._last_llm_error = timeout_exc raise timeout_exc except Exception as exc: self._last_llm_error = exc raise finally: executor.shutdown(wait=False, cancel_futures=True) print(f"[LLM] {self.model_id}: {time.monotonic() - t0:.1f}s", flush=True) @classmethod def _sanitize_code_tags(cls, text: str) -> str: import ast import json import re open_t = cls.open_tag close_t = cls.close_tag # Usuń ewentualne bloki ... przed ekstrakcją kodu text = re.sub(r".*?", "", text, flags=re.DOTALL | re.IGNORECASE).strip() def _convert_xml_tool_calls(raw: str) -> str | None: qwen_calls = re.findall( r"\s*(.*?)\s*", raw, flags=re.DOTALL | re.IGNORECASE, ) if qwen_calls: py_lines = [] for fn_name, params_blob in qwen_calls: params = re.findall( r"(.*?)", params_blob, flags=re.DOTALL | re.IGNORECASE, ) kwargs_parts = [] for p_name, p_val in params: val_clean = p_val.strip() try: parsed_val = json.loads(val_clean) kwargs_parts.append(f"{p_name}={repr(parsed_val)}") except Exception: kwargs_parts.append(f"{p_name}={json.dumps(val_clean, ensure_ascii=False)}") if fn_name in ("python_interpreter", "python", "code"): code_arg = next((v.strip() for k, v in params if k in ("code", "arguments", "script")), "") if code_arg: py_lines.append(code_arg) else: py_lines.append(f"print({fn_name}({', '.join(kwargs_parts)}))") if py_lines: return "\n".join(py_lines) dsml_blocks = re.findall( r"<[||]DSML[||]\s*invoke\s+name=['\"]([^'\"]+)['\"]\s*>(.*?)", raw, flags=re.DOTALL | re.IGNORECASE, ) if dsml_blocks: py_lines = [] for inv_name, inv_body in dsml_blocks: dsml_params = re.findall( r"<[||]DSML[||]\s*parameter\s+name=['\"]([^'\"]+)['\"][^>]*>(.*?)", inv_body, flags=re.DOTALL | re.IGNORECASE, ) if inv_name in ("python_interpreter", "python", "code"): code_arg = next((v.strip() for k, v in dsml_params if k in ("arguments", "code", "script")), "") if code_arg: py_lines.append(code_arg) else: kwargs_parts = [ f"{k}={json.dumps(v.strip(), ensure_ascii=False)}" for k, v in dsml_params ] py_lines.append(f"print({inv_name}({', '.join(kwargs_parts)}))") if py_lines: return "\n".join(py_lines) return None def _extract_valid_python(raw: str) -> str: converted = _convert_xml_tool_calls(raw) if converted is not None: raw = converted 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() converted_top = _convert_xml_tool_calls(text) if converted_top is not None: return f"{open_t}\n{_extract_valid_python(converted_top)}\n{close_t}" 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"{open_t}\n{_extract_valid_python(inner)}\n{close_t}" 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"{open_t}\n{_extract_valid_python(inner)}\n{close_t}" stripped_orphan_tags = re.sub(r"]*>", "", 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) if "final_answer(" in extracted: return f"{open_t}\n{extracted}\n{close_t}" 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)" ) def _extract_text_from_blocks(val) -> str: if val is None: return "" if isinstance(val, str): return val.strip() if isinstance(val, list): parts = [] for part in val: if isinstance(part, dict): txt = part.get("text") or part.get("thinking") or part.get("content") if txt: parts.append(str(txt)) else: txt = ( getattr(part, "text", None) or getattr(part, "thinking", None) or getattr(part, "content", None) ) if txt: parts.append(str(txt)) return "\n".join(parts).strip() return str(val).strip() raw_obj = getattr(msg, "raw", None) raw_msg = None finish_reason = "" if raw_obj is not None: choices = raw_obj.get("choices") if isinstance(raw_obj, dict) else getattr(raw_obj, "choices", None) if choices: first_choice = choices[0] finish_reason = str( ( first_choice.get("finish_reason") if isinstance(first_choice, dict) else getattr(first_choice, "finish_reason", "") ) or "" ).lower() raw_msg = ( first_choice.get("message") if isinstance(first_choice, dict) else getattr(first_choice, "message", None) ) content_str = _extract_text_from_blocks(getattr(msg, "content", None)) reasoning_sources = [ getattr(msg, "reasoning_content", None), getattr(msg, "reasoning", None), ] if raw_msg is not None: if isinstance(raw_msg, dict): reasoning_sources.extend([ raw_msg.get("reasoning_content"), raw_msg.get("reasoning"), raw_msg.get("thinking_blocks"), ]) else: reasoning_sources.extend([ getattr(raw_msg, "reasoning_content", None), getattr(raw_msg, "reasoning", None), getattr(raw_msg, "thinking_blocks", None), ]) reasoning_str = next( (txt for src in reasoning_sources if (txt := _extract_text_from_blocks(src))), "", ) tool_calls = getattr(msg, "tool_calls", None) if not tool_calls and raw_msg is not None: tool_calls = ( raw_msg.get("tool_calls") if isinstance(raw_msg, dict) else getattr(raw_msg, "tool_calls", None) ) if not content_str and not tool_calls and not reasoning_str and "malformed_function_call" in finish_reason: raise RuntimeError( "Error in generating model output: malformed_function_call with empty content" ) 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 = f"{cls.open_tag}\n" + "\n".join(rendered_calls) + f"\n{cls.close_tag}" if not content_str and reasoning_str: code_matches = re.findall( r"(.*?|```(?:py|python)?\s*\n.*?```)", reasoning_str, flags=re.DOTALL | re.IGNORECASE, ) if code_matches: content_str = code_matches[-1].strip() elif re.search(r"\bfinal_answer\s*\(", reasoning_str): content_str = reasoning_str else: fa_matches = re.findall( r"(?im)^\s*(?:final\s*answer|answer)\s*:\s*(.+)$", reasoning_str, ) if fa_matches and fa_matches[-1].strip(): ans_val = fa_matches[-1].strip() content_str = ( f"{cls.open_tag}\n" f"final_answer({json.dumps(ans_val, ensure_ascii=False)})\n" f"{cls.close_tag}" ) else: raise RuntimeError( "Error in generating model output: reasoning-only response without code block or final_answer()" ) if not content_str: print( f"[EMPTY] finish_reason={finish_reason!r} raw={repr(raw_obj)[:800]}", flush=True, ) raise RuntimeError( "Error in generating model output: empty model response (content=None)" ) cleaned = cls._sanitize_code_tags(content_str) if cls.open_tag not in cleaned and cls.close_tag not in cleaned: fa_direct = re.findall( r"(?im)^\s*(?:final\s*answer|answer)\s*:\s*(.+)$", cleaned, ) if fa_direct and fa_direct[-1].strip(): ans_val = fa_direct[-1].strip() cleaned = ( f"{cls.open_tag}\n" f"final_answer({json.dumps(ans_val, ensure_ascii=False)})\n" f"{cls.close_tag}" ) elif len(cleaned.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( "Error in generating model output: empty model response after sanitization" ) try: msg.content = cleaned msg.tool_calls = None except Exception: pass if getattr(msg, "content", None) != cleaned or getattr(msg, "tool_calls", None) is not None: try: from smolagents.models import ChatMessage except ImportError: from smolagents import ChatMessage cm_kwargs = { "role": getattr(msg, "role", "assistant"), "content": cleaned, "tool_calls": None, "raw": getattr(msg, "raw", None), "token_usage": getattr(msg, "token_usage", None), } cm_sig = inspect.signature(ChatMessage.__init__) msg = ChatMessage( **{k: v for k, v in cm_kwargs.items() if k != "self" and k in cm_sig.parameters} ) return msg def _prepare_call_kwargs(self, kwargs: dict) -> dict: import time key = kwargs.pop("api_key", None) or getattr(self, "_explicit_api_key", None) api_base = kwargs.pop("api_base", None) or getattr(self, "_explicit_api_base", None) model_name = str(getattr(self, "model_id", "") or "") if api_base: self.api_base = api_base if isinstance(getattr(self, "kwargs", None), dict): self.kwargs["api_base"] = api_base if key: self.api_key = key if isinstance(getattr(self, "kwargs", None), dict): self.kwargs["api_key"] = key default_cap = 10.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: remaining = task_deadline - time.monotonic() if remaining <= 3.0: raise RuntimeError("Task time budget exhausted") timeout = max(5.0, min(timeout, remaining - 2.0)) if isinstance(getattr(self, "kwargs", None), dict): self.kwargs["timeout"] = timeout kwargs["timeout"] = timeout litellm.request_timeout = timeout if model_name.startswith("gemini/"): if "gemma" not in model_name.lower(): kwargs.setdefault("reasoning_effort", "none") else: kwargs.pop("reasoning_effort", None) if "gemini-3" in model_name.lower(): kwargs.pop("temperature", None) if isinstance(getattr(self, "kwargs", None), dict): self.kwargs.pop("temperature", None) kwargs["max_tokens"] = 512 if isinstance(getattr(self, "kwargs", None), dict): self.kwargs["max_tokens"] = 512 if model_name.startswith("openrouter/"): kwargs["max_tokens"] = 512 if isinstance(getattr(self, "kwargs", None), dict): self.kwargs["max_tokens"] = 512 kwargs["reasoning_effort"] = "none" if model_name.startswith("groq/"): kwargs["max_tokens"] = 384 if isinstance(getattr(self, "kwargs", None), dict): self.kwargs["max_tokens"] = 384 if "qwen3" in model_name.lower(): kwargs["reasoning_effort"] = "none" if model_name.startswith("nvidia_nim/"): kwargs["max_tokens"] = 450 if isinstance(getattr(self, "kwargs", None), dict): self.kwargs["max_tokens"] = 450 kwargs["num_retries"] = 0 kwargs["max_retries"] = 0 kwargs.pop("tools", None) kwargs.pop("tool_choice", None) return kwargs self._model_cls = SafeLiteLLMModel def _build_model(model_name: str): api_key = self._get_api_key(model_name) common = {"num_retries": 0, "max_retries": 0, "timeout": 16.0} if model_name.startswith("gemini/"): kwargs = { "model_id": model_name, "api_key": api_key, "max_tokens": 2048, **common, } if "gemma" not in model_name.lower(): kwargs["reasoning_effort"] = "low" if "gemini-3" not in model_name.lower() and "latest" not in model_name.lower(): kwargs["temperature"] = 0.1 elif model_name.startswith("huggingface/"): raw_hf = model_name[len("huggingface/"):] kwargs = { "model_id": f"openai/{raw_hf}", "api_base": "https://router.huggingface.co/v1", "api_key": api_key, "max_tokens": 2048, **common, } elif model_name.startswith("groq/") and "qwen3" in model_name.lower(): kwargs = { "model_id": model_name, "api_key": api_key, "max_tokens": 1024, "reasoning_effort": "none", **common, } else: kwargs = { "model_id": model_name, "api_key": api_key, "max_tokens": 2048, **common, } return self._model_cls(**kwargs) def _probe_candidate(model_name: str) -> tuple[str, str, str]: import time api_key = self._get_api_key(model_name) if not api_key: return (model_name, "dead", "no api key") t0 = time.monotonic() try: kw = {"model": model_name, "api_key": api_key} if model_name.startswith("gemini/"): kw["reasoning_effort"] = "low" elif model_name.startswith("groq/") and "qwen3" in model_name.lower(): kw["reasoning_effort"] = "none" kw["reasoning_format"] = "hidden" elif model_name.startswith("huggingface/"): kw = { "model": "openai/" + model_name[len("huggingface/"):], "api_base": "https://router.huggingface.co/v1", "api_key": api_key, } litellm.completion( **kw, messages=[{"role": "user", "content": "Reply with the single word OK."}], max_tokens=32, timeout=8, num_retries=0, max_retries=0, ) return (model_name, "ok", f"{time.monotonic() - t0:.1f}s") except Exception as exc: text = f"{type(exc).__name__}: {exc}" low = text.lower() short = " ".join(text.split())[:220] transient_markers = ( "429", "403", "401", "quota", "rate limit", "resource_exhausted", "timeout", "timed out", "connection", "503", "502", "overloaded", "unavailable", ) if any(m in low for m in transient_markers): return (model_name, "busy", short) return (model_name, "dead", short) from concurrent.futures import ThreadPoolExecutor, wait as futures_wait probe_targets = [m for m in self.working_models if not m.startswith("openrouter/")][:6] 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=12) for fut in done: try: p_name, p_state, p_info = fut.result() probe_status[p_name] = p_state print(f"[PREFLIGHT] {p_state.upper():4} {p_name} :: {p_info}", flush=True) except Exception: pass finally: probe_pool.shutdown(wait=False, cancel_futures=True) tested_providers = { m.split("/", 1)[0].lower() for m in probe_status if "/" in m } for prov in tested_providers: prov_states = [ st for m, st in probe_status.items() if m.startswith(f"{prov}/") ] if prov_states and all(st == "dead" for st in prov_states): self.provider_key_pools[prov] = [] self._sync_provider_env(prov, "") dead_models = {m for m, st in probe_status.items() if st == "dead"} ok_models = [m for m in self.working_models if probe_status.get(m) == "ok"] untested_non_or = [ m for m in self.working_models if m not in probe_status and not m.startswith("openrouter/") ] busy_models = [m for m in self.working_models if probe_status.get(m) == "busy"] openrouter_models = [ m for m in self.working_models if m.startswith("openrouter/") and m not in dead_models ] # OpenRouter wchodzi przed chwilowo przeciążone (busy) modele, a martwe (dead) są całkowicie odrzucane reordered = (ok_models + untested_non_or + openrouter_models + busy_models)[:4] if reordered: self.working_models = reordered self.model_id = self.working_models[0] print(f"Using primary LLM model: {self.model_id} (fallbacks: {self.working_models[1:]})") self._build_model = _build_model model = self._build_model(self.model_id) exact_match_rule = ( f"Write Python inside {code_open_tag} and {code_close_tag} only. No 'Thought:' or markdown fences. " "Use only provided tools and allowed Python modules; never use subprocess/os.system/open() or import tools. " "Never name variables 'log' or 'print'. Keep code fast (<15s), no nested network loops. " "If inspect_youtube returns 'Transcript/Video Analysis Status: unavailable', switch immediately to web_search or search_wikipedia. " "If Task ID has an attachment, use download_task_file, read_local_file, inspect_image, or transcribe_audio. " "Call final_answer(value) with ONLY the plain answer value (number, date, name, short phrase, or comma-separated list) — no units, no sentences, no dict, no 'FINAL ANSWER'." ) accepted_params = set(sig.parameters) | set(inspect.signature(MultiStepAgent.__init__).parameters) agent_kwargs = { "tools": [ web_search, search_wikipedia, fetch_url_text, download_task_file, read_local_file, inspect_image, inspect_youtube, transcribe_audio, ], "additional_authorized_imports": [ "os", "pathlib", "json", "csv", "pandas", "numpy", "urllib.request", "urllib.parse", "urllib.error", "html", "decimal", "fractions", "string", "re", "time", "math", "cmath", "statistics", "datetime", "collections", "itertools", "operator", "openpyxl", ], "instructions": exact_match_rule, "code_block_tags": (code_open_tag, code_close_tag), "max_steps": 6, "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) if llm_err is not None: raise llm_err obs = getattr(step_log, "observations", None) if isinstance(obs, str) and len(obs) > 4500: step_log.observations = obs[:2200] + "\n...[trimmed]...\n" + obs[-2200:] local_kwargs = dict(agent_kwargs) local_kwargs["model"] = model_instance local_kwargs["step_callbacks"] = [_step_guard] filtered_local = {k: v for k, v in local_kwargs.items() if k in accepted_params} return CodeAgent(**filtered_local) self._create_code_agent = _create_code_agent self.agent = _create_code_agent(model) if not hasattr(self, "_build_model") or not hasattr(self, "agent"): raise RuntimeError("BasicAgent.__init__ failed to bind _build_model or self.agent.") print("CodeAgent initialized with LiteLLMModel.") def _clean_exact_match_answer(self, text: str) -> str: import re if text is None: return "" cleaned = str(text).strip() if not cleaned or cleaned.startswith("AGENT ERROR:"): return cleaned cleaned = re.sub(r"]*>", "", cleaned, flags=re.IGNORECASE).strip() fa_call = re.fullmatch( r"final_answer\(\s*(?:answer\s*=\s*)?(.*?)\s*\)", cleaned, flags=re.DOTALL, ) if fa_call: cleaned = fa_call.group(1).strip() if cleaned.startswith("```") and cleaned.endswith("```"): lines = cleaned.splitlines() if len(lines) >= 3: cleaned = "\n".join(lines[1:-1]).strip() else: cleaned = cleaned.strip("`").strip() lines = [ln.strip() for ln in cleaned.splitlines() if ln.strip()] if len(lines) > 1: for ln in reversed(lines): m_final = re.match( r"^(?:\*\*)?(?:final\s+answer|answer|result|output)(?:\*\*)?\s*:\s*(.+)$", ln, flags=re.IGNORECASE, ) if m_final: cleaned = m_final.group(1).strip() break else: cleaned = lines[-1] prefix_match = re.match( r"^(?:\*\*)?(?:final\s+answer|the\s+final\s+answer\s+is|the\s+answer\s+is|answer|result|output)(?:\*\*)?\s*:?\s+(.+)$", cleaned, flags=re.IGNORECASE, ) had_prefix = False if prefix_match: cleaned = prefix_match.group(1).strip() had_prefix = True trailing_bold = re.search(r"\*\*([^*]+?)\*\*[.!?]?\s*$", cleaned) if trailing_bold: candidate = trailing_bold.group(1).strip() prefix_part = cleaned[: trailing_bold.start()].strip().lower() if ( candidate and len(candidate) <= 120 and ( not prefix_part or prefix_part.startswith( ("according to", "based on", "under ", "in ", "from ", "the ", "this ", "it is", "it was") ) ) ): cleaned = candidate had_prefix = True if len(cleaned) >= 2 and ( (cleaned.startswith("**") and cleaned.endswith("**")) or (cleaned.startswith("__") and cleaned.endswith("__")) or (cleaned.startswith("`") and cleaned.endswith("`")) or (cleaned.startswith('"') and cleaned.endswith('"')) or (cleaned.startswith("'") and cleaned.endswith("'")) ): cleaned = cleaned[2:-2].strip() if cleaned.startswith(("**", "__")) else cleaned[1:-1].strip() num_only = re.fullmatch( r"(?:there\s+(?:are|is)\s+|a\s+total\s+of\s+|total\s*:\s*)?(\d+)(?:\s+(?:studio\s+albums?|albums?|bird\s+species|species|items?))?[.!]?", cleaned.strip(), flags=re.IGNORECASE, ) if num_only: return num_only.group(1) if had_prefix and cleaned.endswith(".") and not re.search(r"\b(?:Mr|Mrs|Ms|Dr|St|Jr|Sr|Inc|Ltd|vs|etc)\.$", cleaned): cleaned = cleaned[:-1].strip() if re.match( r"^(?:title|channel|transcript|description|duration|views|url|source|file\s*path|status|error|no\s+transcript)\s*:", cleaned, flags=re.IGNORECASE, ): return "" return cleaned def __call__(self, question: str, task_id: str = "", file_name: str = "") -> str: import time import threading if not hasattr(self, "_local_state"): self._local_state = threading.local() if not hasattr(self, "_dead_models"): self._dead_models = set() if not hasattr(self, "_model_cooldowns"): self._model_cooldowns = {} if hasattr(self, "_reset_key_indices"): self._reset_key_indices() deadline = time.monotonic() + 185.0 self._local_state.deadline = deadline self._task_deadline = deadline try: prompt = question.strip() self._prefer_2022_wiki = "2022" in prompt.lower() clean_file_name = (file_name or "").strip() tools_map = getattr(getattr(self, "agent", None), "tools", {}) or {} if task_id: prefetched_path = "" if hasattr(self, "_download_task_file"): for _attempt in range(2): try: res_path = self._download_task_file( task_id=task_id, preferred_filename=clean_file_name, ) if ( isinstance(res_path, str) and not res_path.startswith(("Error ", "No attachment")) and os.path.isfile(res_path) ): prefetched_path = res_path break except Exception as dl_exc: print(f"[DOWNLOAD WARN] task_id={task_id} attempt={_attempt + 1}: {dl_exc}", flush=True) if not clean_file_name: break time.sleep(1.0) if prefetched_path: ext = os.path.splitext(prefetched_path)[1].lower() if ext in {".mp3", ".wav", ".m4a", ".ogg", ".flac"}: tool_hint = f"Call transcribe_audio(audio_path='{prefetched_path}', question=...) if more detail is needed." transcribe_fn = getattr(self, "_transcribe_audio", None) or tools_map.get("transcribe_audio") if transcribe_fn is not None: try: tr_preview = transcribe_fn( audio_path=prefetched_path, question=question.strip(), ) if ( isinstance(tr_preview, str) and tr_preview.strip() and not tr_preview.startswith(("Error ", "Audio file not found")) ): prompt += ( f"\n\nTask ID: {task_id}. Audio file '{prefetched_path}' transcription:\n" f"{tr_preview.strip()[:8000]}" ) tool_hint = "" except Exception as tr_exc: print(f"[PRE-TRANSCRIBE WARN] task_id={task_id}: {tr_exc}", flush=True) if tool_hint: prompt += ( f"\n\nTask ID: {task_id}. The task attachment is downloaded at '{prefetched_path}'. " f"{tool_hint}" ) elif ext in {".png", ".jpg", ".jpeg", ".webp", ".gif"}: prompt += ( f"\n\nTask ID: {task_id}. The task attachment is downloaded at '{prefetched_path}'. " f"Call inspect_image(image_path='{prefetched_path}', question=...) immediately." ) else: tool_hint = f"Call read_local_file(file_path='{prefetched_path}') immediately." read_fn = getattr(self, "_read_local_file", None) or tools_map.get("read_local_file") if read_fn is not None: try: file_preview = read_fn(file_path=prefetched_path) if ( isinstance(file_preview, str) and file_preview.strip() and not file_preview.startswith(("Error ", "File not found")) ): prompt += ( f"\n\nTask ID: {task_id}. Attachment '{prefetched_path}' content:\n" f"{file_preview.strip()[:12000]}" ) tool_hint = "" except Exception as rd_exc: print(f"[PRE-READ WARN] task_id={task_id}: {rd_exc}", flush=True) if tool_hint: prompt += ( f"\n\nTask ID: {task_id}. The task attachment is downloaded at '{prefetched_path}'. " f"{tool_hint}" ) else: prompt += f"\n\nTask ID: {task_id}" if clean_file_name: prompt += f" (expected attachment filename: '{clean_file_name}')" prompt += ( ". If this task refers to an attached file, image, spreadsheet, audio, or document, " f"call download_task_file(task_id='{task_id}', preferred_filename='{clean_file_name}') first." ) blocked_models = set(self._dead_models) blocked_providers = set() now = time.monotonic() all_candidates = list(getattr(self, "working_models", []) or [self.model_id]) if self.model_id and self.model_id not in all_candidates: all_candidates.append(self.model_id) models_to_try = [ m for m in all_candidates if m not in self._dead_models and self._model_cooldowns.get(m, 0.0) <= now ] if not models_to_try: models_to_try = [m for m in all_candidates if m not in self._dead_models] or all_candidates backoff_rounds = 0 while time.monotonic() < deadline: rate_limited_models = set() rate_limited_providers = set() for model_name in models_to_try: remaining = deadline - time.monotonic() if remaining <= 6.0: break if not hasattr(self, "_build_model") or not hasattr(self, "_create_code_agent"): return "AGENT ERROR: Agent not initialized." provider = model_name.split("/", 1)[0].lower() if "/" in model_name else "gemini" transient_retries = 0 while time.monotonic() < deadline: 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 built_model = None step_t0 = time.monotonic() try: rem_now = deadline - step_t0 if rem_now <= 6.0: break call_timeout = max(6.0, min(14.0, rem_now - 2.0)) print( f"[TRACE] task_id={task_id} model={model_name} provider={provider} " f"rem={rem_now:.1f}s timeout={call_timeout:.1f}s start", flush=True, ) built_model = self._build_model(model_name) built_model.model_id = getattr(built_model, "model_id", model_name) built_model.timeout = call_timeout built_model.deadline = deadline run_agent = self._create_code_agent(built_model) run_agent.max_steps = 3 if rem_now > 25.0 else 2 result = run_agent.run(prompt) print( f"[TRACE] task_id={task_id} model={model_name} " f"elapsed={time.monotonic() - step_t0:.1f}s returned={type(result).__name__}", flush=True, ) raw_result = "" if result is None else str(result).strip() if raw_result.lower().startswith("error in generating"): raise RuntimeError(raw_result) cleaned = self._clean_exact_match_answer(raw_result) if cleaned and not cleaned.startswith("AGENT ERROR:"): return cleaned blocked_models.add(model_name) break except Exception as exc: llm_err = getattr(built_model, "_last_llm_error", None) if llm_err is not None and llm_err is not exc: exc = llm_err err_text = str(exc) err_lower = err_text.lower() print(f"[AGENT ERROR] task_id={task_id} model={model_name}: {err_text}", flush=True) if "task time budget exhausted" in err_lower: break http_status = getattr(exc, "status_code", None) if http_status in (401, 402, 403) or any( marker in err_lower for marker in ( "authentication", "invalid api key", "api key not valid", "permission_denied", "insufficient permissions", ) ): if hasattr(self, "_rotate_api_key") and self._rotate_api_key( provider, permanent=True ): continue for m in models_to_try: if m.startswith(f"{provider}/"): blocked_models.add(m) blocked_providers.add(provider) break if any( marker in err_lower for marker in ( "free-models-per-day", "quota", "resource_exhausted", "429", "rate limit exceeded", ) ): if hasattr(self, "_rotate_api_key") and self._rotate_api_key(provider): continue cooldown_until = time.monotonic() + 20.0 rate_limited_models.add(model_name) self._model_cooldowns[model_name] = cooldown_until rate_limited_providers.add(provider) break if any( marker in err_lower for marker in ( "timeout", "timed out", ) ): blocked_models.add(model_name) self._model_cooldowns[model_name] = time.monotonic() + 60.0 break is_context_overflow = any( marker in err_lower for marker in ( "context length", "context_length", "maximum context", "too many tokens", "token limit", "reduce the length", "request too large", ) ) if ( http_status in (400, 404) or any( marker in err_lower for marker in ( "badrequesterror", "bad request", "invalid_request_error", "reasoning is mandatory", "cannot be disabled", "does not support", "404", "not found", "model_not_found", "decommissioned", "unsupported", ) ) ): blocked_models.add(model_name) if not is_context_overflow: self._dead_models.add(model_name) break if any( marker in err_lower for marker in ( "503", "service unavailable", "high demand", "overloaded", ) ): blocked_models.add(model_name) 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: transient_retries += 1 time.sleep(0.5) continue blocked_models.add(model_name) self._model_cooldowns[model_name] = time.monotonic() + 60.0 break blocked_models.add(model_name) break if time.monotonic() >= deadline: 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: rem_after_pass = deadline - time.monotonic() if rate_limited_models and backoff_rounds < 2 and rem_after_pass > 18.0: backoff_rounds += 1 for prov in rate_limited_providers: if prov not in blocked_providers: pool = self.provider_key_pools.get(prov) or [] self._provider_key_idx[prov] = 0 if hasattr(self, "_sync_provider_env"): self._sync_provider_env(prov, pool[0] if pool else "") time.sleep(min(12.0, max(3.0, rem_after_pass - 15.0))) continue break finally: self._local_state.deadline = None self._task_deadline = None 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. """ space_id = os.getenv("SPACE_ID") 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 try: agent = BasicAgent() except Exception as e: print(f"Error instantiating agent: {e}") return f"Error initializing agent: {e}", None agent_code = ( f"https://huggingface.co/spaces/{space_id.strip()}/tree/main" if space_id and space_id.strip() else ( (os.getenv("AGENT_CODE_URL") or "").strip() or f"https://huggingface.co/spaces/{username.strip()}/Final_Assignment_Template/tree/main" ) ) print(agent_code) # 2. Fetch Questions import json import time print(f"Fetching questions from: {questions_url}") questions_cache_path = "/tmp/gaia_questions.json" questions_data = None last_fetch_exc = None for attempt in range(3): try: response = requests.get(questions_url, timeout=(15, 90)) if response.status_code in {429, 502, 503, 504} and attempt < 2: time.sleep(3 * (attempt + 1)) continue response.raise_for_status() questions_data = response.json() if questions_data: try: with open(questions_cache_path, "w", encoding="utf-8") as f_q: json.dump(questions_data, f_q, ensure_ascii=False) except Exception: pass break except requests.exceptions.RequestException as e: last_fetch_exc = e if attempt < 2: time.sleep(3 * (attempt + 1)) continue except Exception as e: last_fetch_exc = e break if questions_data is None and os.path.isfile(questions_cache_path): try: with open(questions_cache_path, "r", encoding="utf-8") as f_q: questions_data = json.load(f_q) print("Loaded questions from local cache after network error.") except Exception: questions_data = None if questions_data is None: print(f"Error fetching questions: {last_fetch_exc}") return f"Error fetching questions: {last_fetch_exc}", None 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.") # 3. Run Agent from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeoutError import json import time 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): with open(partial_path, "r", encoding="utf-8") as f_cache: cached_items = json.load(f_cache) if isinstance(cached_items, list): 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_ans, str) and c_ans.strip() and not c_ans.strip().startswith("AGENT ERROR:") and "" not in c_ans.lower() and "without access to" not in c_ans.lower() ): clean_cached = c_ans.strip() if isinstance(c_tid, str) and c_tid.strip(): 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") file_name = str(item.get("file_name") or "").strip() if not task_id or question_text is None: print(f"Skipping item with missing task_id or question: {item}") continue clean_tid = str(task_id).strip() clean_q = str(question_text).strip() force_refresh = os.getenv("FORCE_REFRESH_TASKS", "").strip().lower() in {"1", "true", "yes"} if not force_refresh and clean_tid in cached_by_task_id: submitted_answer = cached_by_task_id[clean_tid] elif not force_refresh and clean_q in cached_by_question: submitted_answer = cached_by_question[clean_q] else: if ran_fresh_query: time.sleep(2) ran_fresh_query = True executor = ThreadPoolExecutor(max_workers=1) future = executor.submit(agent, question_text, task_id=task_id, file_name=file_name) try: submitted_answer = future.result(timeout=210) except FutureTimeoutError: print(f"Timeout running agent on task {task_id} after 210s.") submitted_answer = "AGENT ERROR: Task timed out after 210s." except Exception as e: print(f"Error running agent on task {task_id}: {e}") submitted_answer = f"AGENT ERROR: {e}" finally: executor.shutdown(wait=False, cancel_futures=True) 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 # 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}") results_df = pd.DataFrame(results_log) try: response = None for attempt in range(3): try: response = requests.post(submit_url, json=submission_data, timeout=(15, 90)) if response.status_code in {429, 502, 503, 504} and attempt < 2: time.sleep(3 * (attempt + 1)) continue response.raise_for_status() break except (requests.exceptions.Timeout, requests.exceptions.ConnectionError): if attempt < 2: time.sleep(3 * (attempt + 1)) continue raise 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.") 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) return status_message, results_df except requests.exceptions.Timeout: status_message = "Submission Failed: The request timed out." print(status_message) return status_message, results_df except requests.exceptions.RequestException as e: status_message = f"Submission Failed: Network error - {e}" print(status_message) return status_message, results_df except Exception as e: status_message = f"An unexpected error occurred during submission: {e}" print(status_message) 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) results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True) run_button.click( fn=run_and_submit_all, outputs=[status_output, results_table] ) if __name__ == "__main__": print("\n" + "-" * 30 + " App Starting " + "-" * 30) space_host_startup = os.getenv("SPACE_HOST") space_id_startup = os.getenv("SPACE_ID") if space_host_startup: print(f"✅ SPACE_HOST found: {space_host_startup}") runtime_url = ( space_host_startup if space_host_startup.startswith("http") else ( f"https://{space_host_startup}" if space_host_startup.endswith(".hf.space") else f"https://{space_host_startup}.hf.space" ) ) print(f" Runtime URL should be: {runtime_url}") else: print("ℹ️ SPACE_HOST environment variable not found (running locally?).") if space_id_startup: 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") else: print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.") print("-" * (60 + len(" App Starting ")) + "\n") print("Launching Gradio Interface for Basic Agent Evaluation...") demo.queue() demo.launch(debug=True, share=False, ssr_mode=False)