StudentWAT's picture
Update app.py
c51b8b4 verified
Raw History Blame Contribute Delete
192 kB
import os import gradio as gr import requests import inspect import pandas as pd import posixpath 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.suppress_debug_info = 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).*?>.*?</\1>", " ", 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) <= 45000: return cleaned return cleaned[:45000] + "\n...[truncated]..." 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 = "", file_url: str = "", ) -> str: """Downloads a task attachment from the course API (or direct URL) 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. file_url: Optional direct URL if mentioned in the task prompt. """ import re import time from urllib.parse import unquote clean_id = (task_id or "").strip() clean_url = (file_url or "").strip() if not clean_id and not clean_url: return "Error downloading file: missing task_id and file_url." 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()) # Sprawdź najpierw czy plik już istnieje w output_dir lub podkatalogach roboczych search_names = [n for n in (safe_pref_name, f"{clean_id}.bin", clean_id) if n] for s_name in search_names: direct_cand = os.path.join(safe_out_dir, s_name) if os.path.isfile(direct_cand) and os.path.getsize(direct_cand) > 0: return direct_cand if clean_id: for fname in os.listdir(safe_out_dir): f_full = os.path.join(safe_out_dir, fname) if os.path.isfile(f_full) and os.path.getsize(f_full) > 0: if fname.startswith(clean_id) or (safe_pref_name and fname == safe_pref_name): return f_full base_url = DEFAULT_API_URL.rstrip("/") candidate_urls = [] if clean_url.startswith(("http://", "https://")): candidate_urls.append(clean_url) if clean_id: candidate_urls.extend([ f"{base_url}/files/{clean_id}", f"{base_url}/attachments/{clean_id}", f"{base_url}/tasks/{clean_id}/file", ]) 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"}, allow_redirects=True, ) 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", "application/zip": ".zip", "image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp", "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 or 'attachment'}{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, CSV/JSON, or spreadsheet content from a local file. Args: file_path: Local path to the downloaded file. """ import json 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." parts_out = [] for s_name, df in sheets.items(): summary = ( f"=== Sheet: {s_name} (rows={len(df)}, cols={list(df.columns)}) ===\n" f"{df.to_csv(index=False)}" ) parts_out.append(summary) text = "\n\n".join(parts_out) elif f_ext == ".csv": df = pd.read_csv(path) text = f"=== CSV (rows={len(df)}, cols={list(df.columns)}) ===\n{df.to_csv(index=False)}" elif f_ext == ".json": with open(path, "r", encoding="utf-8", errors="replace") as f: raw_j = f.read() try: parsed_j = json.loads(raw_j) text = json.dumps(parsed_j, ensure_ascii=False, indent=2) except Exception: text = raw_j 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=...) or analyze_chessboard(image_path='{path}')." 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: resolved = file_path if not os.path.isfile(resolved): base_name = os.path.basename(file_path or "") for cand_dir in ("/tmp/gaia_files", "."): cand_p = os.path.join(cand_dir, base_name) if base_name and os.path.isfile(cand_p): resolved = cand_p break if not os.path.isfile(resolved): return f"File not found: '{file_path}'" ext = os.path.splitext(resolved)[1].lower() office_zip_exts = {".xlsx", ".xlsm", ".xls", ".docx", ".pptx"} if ext == ".zip" or (ext not in office_zip_exts and zipfile.is_zipfile(resolved)): extract_dir = os.path.join( os.path.dirname(resolved), f"extracted_{os.path.basename(resolved)}", ) os.makedirs(extract_dir, exist_ok=True) base_extract = os.path.realpath(extract_dir) sections = [] with zipfile.ZipFile(resolved, "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)}" ) per_member_cap = max(4000, min(24000, 44000 // max(1, len(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=per_member_cap) 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(resolved, 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)<a\b([^>]*\bclass=['\"][^'\"]*result__a[^'\"]*['\"][^>]*)>(.*?)</a>", resp.text, ) snippets = re.findall( r"(?is)<(?:a|div)\b[^>]*\bclass=['\"][^'\"]*result__snippet[^'\"]*['\"][^>]*>(.*?)</(?:a|div)>", 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)<a\b([^>]*\bclass=['\"][^'\"]*result-link[^'\"]*['\"][^>]*)>(.*?)</a>", lite_resp.text, ) lite_snippets = re.findall( r"(?is)<td\b[^>]*\bclass=['\"][^'\"]*result-snippet[^'\"]*['\"][^>]*>(.*?)</td>", 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).*?>.*?</\1>", " ", raw_html, ) cleaned_html = re.sub(r"(?i)</(tr|p|li|h[1-6]|div|br)>", "\n", cleaned_html) cleaned_html = re.sub(r"(?i)</(td|th)>", " | ", 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 = "" body_text = re.split( r"(?im)^(?:references|external links|further reading|notes)\s*$", text, maxsplit=1, )[0].strip() or text if len(body_text) > 8500: section_match = re.search( r"(?i)\b(?:discography|studio albums|participating national olympic committees|" r"participating nations|recipients|laureates|winners|medal table)\b", body_text, ) if section_match: start = max(0, section_match.start() - 250) focus_section = body_text[start:start + 6800] text = body_text[:1400] + "\n...\n" + focus_section else: text = body_text[:4200] + "\n...\n" + body_text[-4200:] else: text = body_text display_title = resolved_title or title header_lines = [f"Wikipedia: {display_title}"] if rev_id: header_lines[0] += f" (2022 revision {rev_id})" if other_titles: header_lines.append(f"Other search matches: {', '.join(other_titles[:4])}") body_out = text if text else "No readable article text found." result_str = "\n".join(header_lines) + "\n\n" + body_out wiki_cache[cache_key] = result_str return result_str 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)<a[^>]+class="result__a"[^>]+href="([^"]+)"[^>]*>(.*?)</a>', 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: route = {"model": model_name, "api_key": api_key} if model_name.startswith("huggingface/"): raw_hf = model_name[len("huggingface/") :] route["model"] = f"openai/{raw_hf}" route["api_base"] = "https://router.huggingface.co/v1" return route 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-maverick-17b-128e-instruct", "groq/meta-llama/llama-4-scout-17b-16e-instruct", ]) if self.provider_keys.get("gemini"): vision_candidates.extend( self.gemini_flash_models or [ "gemini/gemini-2.5-flash", "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") or self.provider_key_pools.get("nvidia_nim"): vision_candidates.extend([ "nvidia_nim/meta/llama-3.2-90b-vision-instruct", "nvidia_nim/nvidia/nemotron-nano-12b-v2-vl", "nvidia_nim/moonshotai/kimi-k2.5", ]) 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) 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 analyze_chessboard(image_path: str, side_to_move: str = "black") -> str: """Extracts a structured chessboard position from an image and evaluates candidate legal moves for the side to move. Args: image_path: Local path to the chessboard image (.png, .jpg, .jpeg, .webp). side_to_move: Side whose turn it is ('black' or 'white'). """ chess_prompt = ( "Carefully examine this chessboard image rank by rank from rank 8 down to rank 1, " "and file by file from file 'a' to file 'h' (standard algebraic coordinates where a1 is White's " "leftmost square and h8 is Black's leftmost square, regardless of visual rotation—state which rank " "is at the bottom of the image).\n" "List EVERY piece currently on the board with its exact square:\n" "- White pieces (K, Q, R, B, N, P)\n" "- Black pieces (k, q, r, b, n, p)\n" "Also provide the exact FEN placement string (8 ranks separated by '/') and list all immediate " "checks, captures, forks, pins, and mating threats available to " f"{(side_to_move or 'black').upper()}, plus the best winning move in Standard Algebraic Notation (SAN)." ) vision_summary = inspect_image(image_path=image_path, question=chess_prompt) # Jeśli zainstalowana jest biblioteka python-chess, spróbuj zweryfikować legalne ruchy z podanego FEN-a try: import re import chess fen_match = re.search( r"\b([rnbqkprnbqkprnbqkprnbqkprnbqkprnbqkprnbqkp1-8]{1,8}(?:/[rnbqkprnbqkprnbqkprnbqkprnbqkprnbqkprnbqkp1-8]{1,8}){7})\b", vision_summary, flags=re.IGNORECASE, ) if fen_match: raw_placement = fen_match.group(1) turn_char = "b" if (side_to_move or "black").strip().lower().startswith("b") else "w" board = chess.Board(f"{raw_placement} {turn_char} - - 0 1") legal_sans = [board.san(mv) for mv in board.legal_moves] forcing_sans = [ board.san(mv) for mv in board.legal_moves if board.gives_check(mv) or board.is_capture(mv) ] return ( f"{vision_summary}\n\n" f"[Verified FEN]: {board.fen()}\n" f"[Legal moves count]: {len(legal_sans)}\n" f"[Checks / Captures]: {', '.join(forcing_sans[:25]) or 'none'}\n" f"[All legal SANs]: {', '.join(legal_sans[:40])}" ) except Exception: pass return vision_summary @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)<text[^>]*>(.*?)</text>", 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[:5000]}") 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 video_analysis_error = "" 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: video_analysis_error = "no gemini api 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 video_analysis_error = "gemini returned empty candidate" break err_low = gm_resp.text.lower() video_analysis_error = f"gemini status {gm_resp.status_code}: {gm_resp.text[:200]}" 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 video_analysis_error = f"gemini exception: {type(gm_exc).__name__}: {gm_exc}" 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: reason = f" ({video_analysis_error})" if video_analysis_error else "" sections.append( "Transcript/Video Analysis Status: unavailable" f"{reason}. " "Use web_search or search_wikipedia with the video title, channel, or quoted dialogue. " "Do NOT guess visual counts from the question alone." ) 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 or filename of the downloaded audio file. question: Specific transcription or analysis instruction for the audio. """ try: resolved_path = audio_path if not os.path.isfile(resolved_path): target_name = os.path.basename(audio_path) for root, _, files in os.walk("."): if target_name in files: resolved_path = os.path.join(root, target_name) break if not os.path.isfile(resolved_path): return f"Audio file not found: '{audio_path}'" ext = os.path.splitext(resolved_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(resolved_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(resolved_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 f"[Whisper Transcript]: {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(resolved_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": 512}, }, }, 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 = [] # 1. Gemini Flash jako główny model (najlepsza stabilność z CodeAgent) 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) # 2. Groq jako szybki fallback if self.provider_keys.get("groq"): 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]) # 3. OpenRouter darmowe modele dopiero po Gemini i Groq 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("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"): preferred_nim = [ "nvidia_nim/nvidia/nemotron-3-ultra-550b-a55b", "nvidia_nim/nvidia/llama-3.3-nemotron-super-49b-v1", "nvidia_nim/nvidia/llama-3.1-nemotron-70b-instruct", "nvidia_nim/qwen/qwen2.5-72b-instruct", "nvidia_nim/meta/llama-3.1-70b-instruct", "nvidia_nim/mistralai/mistral-large-2-instruct", ] live_nim = [] try: nim_resp = requests.get( "https://integrate.api.nvidia.com/v1/models", headers={"Authorization": f"Bearer {self.provider_keys['nvidia_nim']}"}, timeout=10, ) if nim_resp.status_code == 200: for item in nim_resp.json().get("data", []): n_id = str(item.get("id", "")).strip() if n_id and not any( bad in n_id.lower() for bad in ("embed", "rerank", "guard", "parse", "ocr", "tts", "asr", "riva", "kosmos", "deplot", "paligemma") ): live_nim.append(f"nvidia_nim/{n_id}") except Exception as nim_exc: print(f"Warning: could not list NVIDIA NIM models: {nim_exc}") if live_nim: live_nim_set = set(live_nim) curated_nim = [m for m in preferred_nim if m in live_nim_set] extra_nim = [ m for m in live_nim if m not in curated_nim and any(k in m.lower() for k in ("nemotron", "70b", "72b", "large", "qwen", "llama-3.3", "llama-3.1")) ] candidate_models.extend((curated_nim + extra_nim)[:5]) else: candidate_models.extend(preferred_nim[:4]) priority_rank = {name: idx for idx, name in enumerate(candidate_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 "ultra" in low or "550b" in low: sub_rank = 0 elif "mistral-large" in low: sub_rank = 1 elif "nemotron" in low and "nano" not in low and "bolt" not in low and "reasoning" not in low: sub_rank = 2 else: sub_rank = 3 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 = ("<code>", "</code>") 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_text_val(val: str, max_len: int) -> str: if len(val) <= max_len: return val half_len = max_len // 2 return val[:half_len] + "\n...[trimmed]...\n" + val[-half_len:] def _trim_messages(raw_msgs): if not isinstance(raw_msgs, list): return raw_msgs if len(raw_msgs) > 8: selected = raw_msgs[:2] + raw_msgs[-6:] else: selected = raw_msgs out = [] for idx, m in enumerate(selected): max_len = 14000 if idx < 2 else 8500 m_copy = copy.copy(m) if isinstance(m_copy, dict): content = m_copy.get("content") if isinstance(content, str) and len(content) > max_len: m_copy["content"] = _trim_text_val(content, max_len) elif isinstance(content, list): new_parts = [] for part in content: if ( isinstance(part, dict) and isinstance(part.get("text"), str) and len(part["text"]) > max_len ): part_copy = dict(part) part_copy["text"] = _trim_text_val(part["text"], max_len) new_parts.append(part_copy) else: new_parts.append(part) m_copy["content"] = new_parts else: content = getattr(m_copy, "content", None) if isinstance(content, str) and len(content) > max_len: try: setattr(m_copy, "content", _trim_text_val(content, max_len)) except Exception: pass out.append(m_copy) return out raw_messages = kwargs.pop("messages", None) if raw_messages is None and len(args) >= 1: raw_messages = args[0] trimmed_messages = _trim_messages(raw_messages) stop_sequences = kwargs.pop("stop_sequences", None) if stop_sequences is None and len(args) >= 2: stop_sequences = args[1] kwargs.pop("response_format", None) kwargs.pop("tools_to_call_from", None) 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 22.0), 22.0, ) call_kwargs["timeout"] = req_timeout litellm.request_timeout = req_timeout hard_timeout = req_timeout + 3.0 role_map = { "tool-call": "assistant", "tool-response": "user", "tool": "user", } formatted_messages = [] for m in trimmed_messages or []: if isinstance(m, dict): raw_role = m.get("role", "user") content_val = m.get("content", "") else: raw_role = getattr(m, "role", "user") content_val = getattr(m, "content", "") role_str = str(getattr(raw_role, "value", raw_role) or "user").lower() role_str = role_map.get(role_str, role_str) if role_str not in {"system", "user", "assistant"}: role_str = "user" if content_val is None: content_val = "" formatted_messages.append({"role": role_str, "content": content_val}) if stop_sequences: call_kwargs["stop"] = list(stop_sequences) def _invoke_completion(): try: from smolagents.models import ChatMessage except ImportError: from smolagents import ChatMessage response = litellm.completion( model=self.model_id, messages=formatted_messages, **call_kwargs, ) choices = ( response.get("choices") if isinstance(response, dict) else getattr(response, "choices", None) ) or [] first_choice = choices[0] if choices else {} raw_msg = ( first_choice.get("message") if isinstance(first_choice, dict) else getattr(first_choice, "message", None) ) raw_content = ( raw_msg.get("content") if isinstance(raw_msg, dict) else getattr(raw_msg, "content", None) ) if isinstance(raw_content, list): content_txt = "\n".join( str(p.get("text", "")) for p in raw_content if isinstance(p, dict) and p.get("text") ) else: content_txt = "" if raw_content is None else str(raw_content) if content_txt and stop_sequences: for seq in stop_sequences: if seq and content_txt.endswith(seq): content_txt = content_txt[: -len(seq)] usage = ( response.get("usage") if isinstance(response, dict) else getattr(response, "usage", None) ) in_tok = ( usage.get("prompt_tokens", 0) if isinstance(usage, dict) else getattr(usage, "prompt_tokens", 0) ) or 0 out_tok = ( usage.get("completion_tokens", 0) if isinstance(usage, dict) else getattr(usage, "completion_tokens", 0) ) or 0 self.last_input_token_count = in_tok self.last_output_token_count = out_tok token_usage_obj = None try: from smolagents.monitoring import TokenUsage token_usage_obj = TokenUsage(input_tokens=in_tok, output_tokens=out_tok) except Exception: pass cm_kwargs = { "role": "assistant", "content": content_txt, "tool_calls": None, "raw": response, "token_usage": token_usage_obj, } cm_sig = inspect.signature(ChatMessage.__init__) return ChatMessage( **{k: v for k, v in cm_kwargs.items() if k != "self" and k in cm_sig.parameters} ) executor = ThreadPoolExecutor(max_workers=1) future = executor.submit(_invoke_completion) 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 text = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL | re.IGNORECASE).strip() text = re.sub( r"(?im)^\s*(?:from\s+(?:tools|download_task_file|read_local_file|web_search|search_wikipedia|fetch_url_text|inspect_image|analyze_chessboard|inspect_youtube|transcribe_audio|ask_web)\s+import\s+.*|import\s+(?:tools|download_task_file|read_local_file|web_search|search_wikipedia|fetch_url_text|inspect_image|analyze_chessboard|inspect_youtube|transcribe_audio|ask_web)\b.*)$", "", text, ).strip() def _convert_xml_tool_calls(raw: str) -> str | None: qwen_calls = re.findall( r"<tool_call>\s*<function=([A-Za-z_][A-Za-z0-9_]*)>(.*?)</function>\s*</tool_call>", raw, flags=re.DOTALL | re.IGNORECASE, ) if qwen_calls: py_lines = [] for idx, (fn_name, params_blob) in enumerate(qwen_calls): params = re.findall( r"<parameter=([A-Za-z_][A-Za-z0-9_]*)>(.*?)</parameter>", 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: var_name = f"tool_res_{idx}" py_lines.append(f"{var_name} = {fn_name}({', '.join(kwargs_parts)})") py_lines.append(f"print({var_name})") if py_lines: return "\n".join(py_lines) dsml_blocks = re.findall( r"<[||]DSML[||]\s*invoke\s+name=['\"]([^'\"]+)['\"]\s*>(.*?)</[||]DSML[||]\s*invoke>", 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=['\"]([^'\"]+)['\"][^>]*>(.*?)</[||]DSML[||]\s*parameter>", 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 _guard_unbound_lines(code_str: str) -> str: if not code_str or "lines" not in code_str: return code_str try: tree = ast.parse(code_str) except SyntaxError: return code_str assigned_before_use = False for node in ast.walk(tree): if isinstance(node, (ast.Assign, ast.AugAssign, ast.AnnAssign)): targets = [] if isinstance(node, ast.Assign): targets = node.targets elif isinstance(node, ast.AugAssign): targets = [node.target] elif isinstance(node, ast.AnnAssign) and node.value is not None: targets = [node.target] if any(isinstance(t, ast.Name) and t.id == "lines" for t in targets): assigned_before_use = True break if assigned_before_use: return code_str return "lines = []\n" + code_str def _ensure_observable_output(code_str: str) -> str: clean_code = (code_str or "").strip() if not clean_code or "final_answer(" in clean_code: return clean_code try: tree = ast.parse(clean_code) except SyntaxError: return clean_code if not tree.body: return clean_code last_node = tree.body[-1] if ( isinstance(last_node, ast.Assign) and len(last_node.targets) == 1 and isinstance(last_node.targets[0], ast.Name) ): var_name = last_node.targets[0].id return f"{clean_code}\nprint({var_name})" return clean_code def _convert_json_tool_calls(raw: str) -> str | None: stripped = raw.strip() if not (stripped.startswith("{") or stripped.startswith("[")): return None try: payload = json.loads(stripped) except Exception: return None calls = [] if isinstance(payload, dict) and isinstance(payload.get("tool_calls"), list): calls = payload["tool_calls"] elif isinstance(payload, dict) and ("name" in payload or "function" in payload): calls = [payload] elif isinstance(payload, list): calls = payload py_lines = [] for idx, item in enumerate(calls): if not isinstance(item, dict): continue fn_obj = item.get("function") if isinstance(item.get("function"), dict) else item fn_name = fn_obj.get("name") fn_args = fn_obj.get("arguments", {}) if not fn_name or not isinstance(fn_name, str): continue if isinstance(fn_args, str): try: fn_args = json.loads(fn_args) if fn_args.strip() else {} except Exception: fn_args = {"query": fn_args} if not isinstance(fn_args, dict): continue var_name = f"tool_res_{idx}" py_lines.append(f"{var_name} = {fn_name}(**{json.dumps(fn_args, ensure_ascii=False)})") py_lines.append(f"print({var_name})") return "\n".join(py_lines) if py_lines else None def _extract_valid_python(raw: str) -> str: json_converted = _convert_json_tool_calls(raw) if json_converted is not None: return _ensure_observable_output(_guard_unbound_lines(json_converted)) converted = _convert_xml_tool_calls(raw) if converted is not None: raw = converted src_lines = [] for line in raw.splitlines(): stripped = line.lstrip() if re.match(r"^(?:thoughts?|thinking)\s*:", stripped, flags=re.IGNORECASE): src_lines.append("# " + stripped) else: src_lines.append(line) n = len(src_lines) for start in range(n): if not src_lines[start].strip(): continue for end in range(n, start, -1): candidate = "\n".join(src_lines[start:end]).strip() if not candidate: continue try: tree = ast.parse(candidate) if not tree.body: continue if ( len(tree.body) == 1 and isinstance(tree.body[0], ast.Expr) and isinstance(tree.body[0].value, (ast.Name, ast.Constant, ast.List, ast.Tuple)) ): continue return _ensure_observable_output(_guard_unbound_lines(candidate)) except SyntaxError: continue plain = "\n".join(src_lines).strip() if ( plain and "\n" not in plain and len(plain) <= 80 and plain.lower() not in {"[code]", "code", "python", "py"} and not plain.endswith((".", "?", ":")) and not re.match(r"^(?:thoughts?|thinking|invalid|error)\b", plain, re.IGNORECASE) ): safe_direct = json.dumps(plain.strip("\"'` "), ensure_ascii=False) return f"final_answer({safe_direct})" fa_match = re.findall( r"(?im)^\s*(?:final\s*answer|answer)\s*:\s*(.+)$", plain, ) if fa_match and fa_match[-1].strip(): safe_ans = ( json.dumps(fa_match[-1].strip(), ensure_ascii=False) .replace("<", "\\u003c") .replace(">", "\\u003e") .replace("```", "\\x60\\x60\\x60") ) return f"final_answer({safe_ans})" return ( 'print("Invalid non-code output. Write valid Python code inside ' 'the code block calling a tool or final_answer(...).")' ) tag_matches = re.findall( rf"{re.escape(open_t)}(.*?){re.escape(close_t)}", text, flags=re.DOTALL, ) if not tag_matches and open_t != "```py": tag_matches = re.findall( r"```(?:py|python)?\s*\n(.*?)```", text, flags=re.DOTALL | re.IGNORECASE, ) if tag_matches: raw_block = tag_matches[-1].strip() converted = _convert_json_tool_calls(raw_block) or _convert_xml_tool_calls(raw_block) inner = converted if converted is not None else raw_block inner = _guard_unbound_lines(inner) inner = _ensure_observable_output(inner) try: tree = ast.parse(inner) if not tree.body: inner = _extract_valid_python(raw_block) except SyntaxError: inner = _extract_valid_python(raw_block) return f"{open_t}\n{inner}\n{close_t}" extracted = _extract_valid_python(text) return f"{open_t}\n{extracted}\n{close_t}" @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"(<code>.*?</code>|```(?: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 = ( json.dumps(fa_matches[-1].strip(), ensure_ascii=False) .replace("<", "\\u003c") .replace(">", "\\u003e") .replace("```", "\\x60\\x60\\x60") ) content_str = ( f"{cls.open_tag}\n" f"final_answer({ans_val})\n" f"{cls.close_tag}" ) else: content_str = ( f"{cls.open_tag}\n" 'print("No Python code block produced. Write valid Python code inside ' 'the code block to call a tool or final_answer(...).")\n' f"{cls.close_tag}" ) 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 = ( json.dumps(fa_direct[-1].strip(), ensure_ascii=False) .replace("<", "\\u003c") .replace(">", "\\u003e") .replace("```", "\\x60\\x60\\x60") ) cleaned = ( f"{cls.open_tag}\n" f"final_answer({ans_val})\n" f"{cls.close_tag}" ) else: cleaned = ( f"{cls.open_tag}\n" 'print("Invalid non-code output. Write valid Python code inside ' 'the code block to call a tool or final_answer(...).")\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 kwargs["api_base"] = api_base if isinstance(getattr(self, "kwargs", None), dict): self.kwargs["api_base"] = api_base if key: self.api_key = key kwargs["api_key"] = key if isinstance(getattr(self, "kwargs", None), dict): self.kwargs["api_key"] = key default_cap = 28.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", "low") 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"] = 4096 if isinstance(getattr(self, "kwargs", None), dict): self.kwargs["max_tokens"] = 4096 if model_name.startswith("openrouter/"): kwargs["max_tokens"] = 4096 if isinstance(getattr(self, "kwargs", None), dict): self.kwargs["max_tokens"] = 4096 kwargs.pop("reasoning_effort", None) if isinstance(getattr(self, "kwargs", None), dict): self.kwargs.pop("reasoning_effort", None) if model_name.startswith("groq/"): is_qwen3 = "qwen3" in model_name.lower() groq_tokens = 4096 if is_qwen3 else 2048 kwargs["max_tokens"] = groq_tokens if isinstance(getattr(self, "kwargs", None), dict): self.kwargs["max_tokens"] = groq_tokens if is_qwen3: kwargs["reasoning_effort"] = "none" kwargs["reasoning_format"] = "hidden" if model_name.startswith("nvidia_nim/"): kwargs["max_tokens"] = 4096 if isinstance(getattr(self, "kwargs", None), dict): self.kwargs["max_tokens"] = 4096 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": 2048, "reasoning_effort": "none", "reasoning_format": "hidden", **common, } elif model_name.startswith("nvidia_nim/"): kwargs = { "model_id": model_name, "api_key": api_key, "max_tokens": 3072, **common, } else: kwargs = { "model_id": model_name, "api_key": api_key, "max_tokens": 2048, **common, } return self._model_cls(**kwargs) DEAD_MODEL_PATTERNS = ( "model_not_found", "does not exist", "decommissioned", "no longer supported", "is not found for api version", "unknown model", ) def _classify_preflight_error(err: Exception) -> str: msg = str(err).lower() status = getattr(err, "status_code", None) if status is None: resp = getattr(err, "response", None) status = getattr(resp, "status_code", None) if status == 404 or any(p in msg for p in DEAD_MODEL_PATTERNS): return "DEAD_MODEL" if status in (401, 403) or "invalid_api_key" in msg or "permission_denied" in msg: return "DEAD_KEY" if status == 400 or "unsupported" in msg or "invalid_request_error" in msg: return "BAD_REQUEST_PARAM" return "TRANSIENT_BUSY" def _remove_specific_key(provider: str, bad_key: str) -> None: with self._state_lock: pool = self.provider_key_pools.get(provider) or [] if bad_key and bad_key in pool: pool = [k for k in pool if k != bad_key] self.provider_key_pools[provider] = pool self._provider_key_idx[provider] = 0 _sync_provider_env(provider, pool[0] if pool else "") def _probe_candidate(model_name: str) -> tuple[str, str, str]: import time provider = model_name.split("/", 1)[0].lower() if "/" in model_name else "gemini" api_key = self._get_api_key(model_name) if not api_key: return (model_name, "DEAD_KEY", "no api key") t0 = time.monotonic() try: kw = {"model": model_name, "api_key": api_key} if 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=16, timeout=8, num_retries=0, max_retries=0, ) return (model_name, "OK", f"{time.monotonic() - t0:.1f}s") except Exception as exc: status_kind = _classify_preflight_error(exc) if status_kind == "DEAD_KEY": _remove_specific_key(provider, api_key) short = " ".join(f"{type(exc).__name__}: {exc}".split())[:220] return (model_name, status_kind, 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:18} {p_name} :: {p_info}", flush=True) except Exception: pass finally: probe_pool.shutdown(wait=False, cancel_futures=True) if not hasattr(self, "_dead_models"): self._dead_models = set() for m_name, st in probe_status.items(): if st == "DEAD_MODEL": self._dead_models.add(m_name) # Usuwamy tylko trwałe DEAD_MODEL; reszta (OK, BAD_REQUEST_PARAM, TRANSIENT_BUSY, DEAD_KEY jeśli zostały inne klucze) zostaje surviving_models = [] for m_name in self.working_models: if m_name in self._dead_models or probe_status.get(m_name) == "DEAD_MODEL": continue prov = m_name.split("/", 1)[0].lower() if "/" in m_name else "gemini" if not (self.provider_key_pools.get(prov) or []): continue surviving_models.append(m_name) ok_models = [m for m in surviving_models if probe_status.get(m) == "OK"] untested_non_or = [ m for m in surviving_models if m not in probe_status and not m.startswith("openrouter/") ] openrouter_models = [ m for m in surviving_models if m.startswith("openrouter/") ] degraded_models = [ m for m in surviving_models if probe_status.get(m) in ("BAD_REQUEST_PARAM", "TRANSIENT_BUSY", "DEAD_KEY") and m not in ok_models and m not in untested_non_or and m not in openrouter_models ] reordered = ok_models + untested_non_or + openrouter_models + degraded_models if reordered: self.working_models = reordered if not self.working_models: raise RuntimeError("No models available after preflight.") 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 ONLY valid, executable Python code inside {code_open_tag}...{code_close_tag} at every step. " "In intermediate steps, always call print(...) on tool outputs (e.g., `res = search_wikipedia(...); print(res)`) " "so you can read the result in the next step—never end a step with a bare assignment without print(...). " "NEVER pass raw webpage text, paragraphs, or full tool outputs into `final_answer(...)`. " "Always parse/extract the specific answer in Python (using regex, string search, or reasoning in the next step) " "before calling `final_answer(exact_value)`. " "When you have the final result, call `final_answer(exact_value)` inside the code block, where `exact_value` is ONLY " "the exact requested value (a single number, single name/surname, short phrase, or comma-separated list, strictly under 100 characters) " "with NO explanations, NO units, NO sentences, and NO 'final answer' prefix. " "Match the exact requested granularity: if the question asks for a single item, person, first name, or surname, " "pass ONLY that single word/field (e.g., only the surname if asked for 'surname', never a paragraph or full name). " "Output a comma-separated list ONLY when multiple items are requested, evaluating every item in the provided list in the requested order. " "For chess moves, pass ONLY Standard Algebraic Notation (SAN, e.g., 'Rd5', 'Nf6+', 'O-O') without move numbers or commentary. " "For numbers, omit commas ('1500' not '1,500'). " "Always define every variable before using it (never reference undefined variables like `lines`), " "NEVER import tools (do NOT write `from download_task_file import ...` or `import tools`—all tools are already built-in global functions), " "do not import `requests` or `posixpath`, and use `read_local_file(file_path=...)` instead of `open(...)` for local files." ) allowed_funcs = { "open": open, "os": os, "posixpath": posixpath, "repr": repr, } 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, analyze_chessboard, inspect_youtube, transcribe_audio, ], "additional_authorized_imports": [ "os", "posixpath", "pathlib", "glob", "json", "csv", "pandas", "numpy", "urllib.request", "urllib.parse", "urllib.error", "html", "decimal", "fractions", "string", "re", "time", "math", "cmath", "statistics", "datetime", "collections", "itertools", "operator", "openpyxl", ], "additional_functions": allowed_funcs, "instructions": exact_match_rule, "code_block_tags": (code_open_tag, code_close_tag), "executor_kwargs": {"additional_functions": allowed_funcs}, "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) > 9000: step_log.observations = obs[:4400] + "\n...[trimmed]...\n" + obs[-4400:] 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 ast import re if text is None: return "" cleaned = str(text).strip() if not cleaned or cleaned.startswith("AGENT ERROR:"): return cleaned code_match = re.search(r"<code[^>]*>(.*?)</code>", cleaned, flags=re.DOTALL | re.IGNORECASE) if code_match: cleaned = code_match.group(1).strip() else: cleaned = re.sub(r"</?code[^>]*>", "", cleaned, flags=re.IGNORECASE).strip() cleaned = re.sub(r"^final_answer\s*:\s*", "", cleaned, flags=re.IGNORECASE).strip() cleaned = re.sub( r'\{\s*["\']tool["\']\s*:\s*["\'][^"\']+["\']\s*,\s*["\']arguments["\']\s*:\s*\{.*?\}\s*\}', "", cleaned, flags=re.DOTALL, ).strip() cleaned = re.sub(r"(?im)^\s*(?:#\s*)?(?:thought|reasoning|plan)\s*:.*$", "", cleaned).strip() tech_error_pattern = re.compile( r"(?:invalid non-code output|no python code block produced|" r"reached max steps|max steps reached|error in generating|error in execution|" r"task time budget exhausted|traceback \(most recent call last\)|" r"transcript/video analysis status:\s*unavailable)", re.IGNORECASE, ) if '"tool_calls"' in cleaned or re.search(r'^\s*\{\s*["\'](?:id|type|function|name)["\']\s*:', cleaned): return "" if tech_error_pattern.search(cleaned): return "" fa_matches = re.findall( r"final_answer\s*\(\s*(?:answer\s*=\s*)?([^()]+?)\s*\)", cleaned, flags=re.DOTALL, ) if fa_matches: inner_fa = fa_matches[-1].strip() try: lit_val = ast.literal_eval(inner_fa) if isinstance(lit_val, (list, tuple)): cleaned = ", ".join(str(item).strip() for item in lit_val if str(item).strip()) elif isinstance(lit_val, (str, int, float, bool)): cleaned = str(lit_val).strip() else: return "" except Exception: return "" raw_tool_call_pattern = re.compile( r"(?:^|\b)(?:web_search|search_wikipedia|fetch_url_text|" r"download_task_file|read_local_file|inspect_image|analyze_chessboard|inspect_youtube|" r"transcribe_audio|ask_web|final_answer)\s*\(|" r"^\s*print\s*\(|" r"^\s*[A-Za-z_][A-Za-z0-9_]*\s*=\s*[A-Za-z_][A-Za-z0-9_.]*\s*\(", re.IGNORECASE | re.MULTILINE, ) raw_py_stmt_pattern = re.compile( r"^\s*(?:import\s+[A-Za-z_][A-Za-z0-9_.]*|" r"from\s+[A-Za-z_][A-Za-z0-9_.]*\s+import\b|" r"def\s+[A-Za-z_][A-Za-z0-9_]*\s*\(|" r"class\s+[A-Za-z_][A-Za-z0-9_]*\s*[:(]|" r"(?:for|while|if|elif|else|try|with)\b.*:\s*$|" r"return\b|raise\b)", re.MULTILINE, ) if raw_tool_call_pattern.search(cleaned) or raw_py_stmt_pattern.search(cleaned): return "" arrow_match = re.search( r"\b(?:answer|result|output|final\s+answer)\s*->\s*(.+)$", cleaned, flags=re.IGNORECASE | re.DOTALL, ) if arrow_match: tail_part = arrow_match.group(1).strip() quoted_match = re.findall(r'"([^"]+)"|\'([^\']+)\'', tail_part) if quoted_match: last_q = quoted_match[-1] cleaned = (last_q[0] or last_q[1]).strip() else: cleaned = tail_part.strip(" .\"'") cleaned = re.sub( r"^(?:so\s+the\s+answer\s+is|the\s+answer\s+is|therefore|thus|hence|in\s+conclusion|" r"based\s+on\s+the\s+(?:text|article|table|video|search\s+results)|according\s+to\s+the\s+(?:text|article|table|video))\s*[,:\-–—]?\s*", "", cleaned, flags=re.IGNORECASE, ).strip() junk_pattern = re.compile( r"^(?:the wikipedia article|the youtube video|the search results show|this scene is from|" r"the page is quite long|the task doesn't have|the download failed|let me try|let me search|" r"let me check|now i need to find|i found the|the operation is not commutative|" r"the scene occurs|i need to|i should|i will|i can|" r"no attachment|no web results|no wikipedia|file not found|image file not found|" r"audio file not found|error fetching|error downloading|error reading|" r"error inspecting|error transcribing)\b", re.IGNORECASE, ) lines = [ln.strip() for ln in cleaned.splitlines() if ln.strip()] answer_line = next( ( ln for ln in reversed(lines) if not junk_pattern.match(ln) and not raw_tool_call_pattern.search(ln) and not raw_py_stmt_pattern.search(ln) ), "", ) if not answer_line: return "" cleaned = answer_line.strip("`").strip() if ( junk_pattern.match(cleaned) or raw_tool_call_pattern.search(cleaned) or raw_py_stmt_pattern.search(cleaned) or tech_error_pattern.search(cleaned) ): return "" if ( (cleaned.startswith("[") and cleaned.endswith("]")) or (cleaned.startswith("(") and cleaned.endswith(")")) ): try: parsed_seq = ast.literal_eval(cleaned) if isinstance(parsed_seq, (list, tuple)): cleaned = ", ".join( str(item).strip() for item in parsed_seq if str(item).strip() ) except Exception: pass if len(cleaned) >= 2 and cleaned[0] == cleaned[-1] and cleaned[0] in ('"', "'"): cleaned = cleaned[1:-1].strip() if ( cleaned.endswith(".") and not cleaned.endswith("...") and not re.search(r"(?:^|\b[A-Za-z]\.)[A-Za-z]\.$", cleaned) and not re.search(r"\b(?:Mr|Mrs|Ms|Dr|Prof|Sr|Jr|St|Inc|Ltd|Co|vs|etc|e\.g|i\.e)\.$", cleaned) ): cleaned = cleaned[:-1].strip() 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(3): 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 and _attempt >= 1: 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 transcription:\n" f"{tr_preview.strip()[:5000]}" ) prompt += ( "\n\nIMPORTANT for audio tasks: Base your answer ONLY on the transcription above. " "If it is empty or missing, call transcribe_audio again. " "Never guess names, numbers, or dates—quote them directly from the transcript." ) 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." ) prompt += ( "\n\nIMPORTANT for image tasks: Extract ALL visible numbers, labels, and text first. " "For tables/charts, read row/column headers and data cells before answering. " "For chess positions, verify board orientation (a1-h8 coordinates, White vs Black at bottom), " "list exact piece squares and side to move, and answer ONLY with the move in Standard Algebraic Notation (SAN). " "Do not describe the image generally—answer the specific question asked." ) else: tool_hint = f"Call read_local_file(file_path='{prefetched_path}') immediately." if ext in {".xlsx", ".xlsm", ".xls", ".csv"}: prompt += ( f"\n\nTask ID: {task_id}. The tabular attachment is saved at '{prefetched_path}'. " f"Use pandas (`pd.read_excel('{prefetched_path}', sheet_name=None)` or `pd.read_csv('{prefetched_path}')`) " "to inspect exact sheet names, columns, and compute exact totals/filters." ) 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")) ): clean_preview = file_preview.strip() if len(clean_preview) > 6000: clean_preview = ( clean_preview[:3000] + "\n...[truncated]...\n" + clean_preview[-3000:] ) prompt += ( f"\n\nTask ID: {task_id}. Attachment '{prefetched_path}' content:\n" f"{clean_preview}" ) 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"\nThe file is ALREADY downloaded locally at '{prefetched_path}'. " "Do NOT call download_task_file again. Write Python code directly to compute the answer and call final_answer(...)." ) else: prompt += f"\n\nTask ID: {task_id}" if clean_file_name: prompt += f" (expected attachment filename: '{clean_file_name}')" prompt += ( ". NEVER list or inspect the current working directory ('.' or repo files like app.py/README.md). " "If this task refers to an attached file, spreadsheet, image, audio, or document, " f"call download_task_file(task_id='{task_id}', preferred_filename='{clean_file_name}') first." ) prompt_lower = prompt.lower() if "chess" in prompt_lower or "algebraic notation" in prompt_lower: side_hint = "white" if "white's turn" in prompt_lower or "white to move" in prompt_lower else "black" img_hint = f"'{prefetched_path}'" if "prefetched_path" in locals() and prefetched_path else "the downloaded image path" prompt += ( "\n\nIMPORTANT for chess tasks:\n" f"1. Call analyze_chessboard(image_path={img_hint}, side_to_move='{side_hint}') first " "(and if needed, inspect_image with the exact piece list per square from rank 8 to rank 1, file a to h).\n" f"2. In Python, verify the board state and candidate moves for {side_hint.upper()} " "(checks, captures, forks, pins, discovered attacks, and forced mate lines), and pick the winning move.\n" "3. Output ONLY the single move in Standard Algebraic Notation (SAN, e.g. Rd5, Nf6+, Qxd4) " "with NO move numbers ('1...' or '1.') and NO commentary." ) if ( "|*|" in prompt or "commutative" in prompt_lower or "commutativity" in prompt_lower or "cayley table" in prompt_lower or "binary operation" in prompt_lower or ("operation" in prompt_lower and "table" in prompt_lower) ): prompt += ( "\n\nIMPORTANT: For binary operation / Cayley table tasks, write Python that builds a dict of dicts, " "then loops over all pairs (x,y) and checks table[x][y] != table[y][x]. " "Collect all elements from pairs where this is true into a set, sort alphabetically, " "and output as comma-separated string. Do NOT use undefined variables." ) if "youtube.com" in prompt or "youtu.be" in prompt or " video" in prompt_lower: prompt += ( "\n\nIMPORTANT for video tasks: Call inspect_youtube first. " "If it returns 'Transcript/Video Analysis Status: unavailable', do NOT guess. " "Immediately use web_search with the video title/channel or search_wikipedia for the quoted dialogue. " "Answer only from retrieved text, never invent." ) if "between" in prompt_lower and ("album" in prompt_lower or "published" in prompt_lower): prompt += ( "\n\nIMPORTANT: Extract the Discography/Studio albums table from the Wikipedia text. " "Count entries where the year is >= start_year and <= end_year. " "If the table is not visible in the provided text, call search_wikipedia again with " "the exact article title + ' discography' to get the full section." ) if any( k in prompt_lower for k in ("first name", "last name", "surname", "ioc", "country code", "recipient") ): prompt += ( "\n\nIMPORTANT for multi-condition & single-field questions: " "Do NOT return a list of candidates before verifying all constraints. " "Check each candidate's attributes via search_wikipedia/web_search, filter down to the single matching entity, " "and extract ONLY the exact requested sub-field (e.g., if 'first name' is asked, output only the given/first name, " "never the full name or a list of names; if 'IOC country code' is asked, verify the exact table numbers first and output only the 3-letter code)." ) 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(8.0, min(28.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 = 7 if rem_now > 60.0 else (5 if rem_now > 25.0 else 4) result = run_agent.run(prompt) 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 len(cleaned) <= 2000 and not cleaned.startswith("AGENT ERROR:"): return cleaned collected_obs = [] mem_steps = getattr(getattr(run_agent, "memory", None), "steps", None) or [] for st in mem_steps: for attr_name in ("observations", "action_output", "model_output"): val = getattr(st, attr_name, None) if val is None: continue txt = "\n".join(str(x) for x in val) if isinstance(val, list) else str(val) txt = txt.strip() if txt and "Invalid non-code output" not in txt and len(txt) > 10: collected_obs.append(txt[:4500]) if collected_obs or raw_result: context_blob = "\n---\n".join(collected_obs[-4:]) if raw_result and "max steps" not in raw_result.lower(): context_blob += f"\n---\nAgent draft: {raw_result[:1500]}" if context_blob.strip(): extract_model = next( ( m for m in [model_name] + models_to_try if m not in blocked_models and m not in rate_limited_models and (m.split("/", 1)[0].lower() if "/" in m else "gemini") not in blocked_providers ), model_name, ) direct_ans = self._direct_extract_answer( model_name=extract_model, question=question.strip(), evidence=context_blob[:12000], deadline=deadline, ) if direct_ans: print(f"[DIRECT EXTRACT OK] task_id={task_id} ans={direct_ans!r}", flush=True) return direct_ans 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, 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 http_status == 402 or "payment required" in err_lower or "insufficient_quota" in err_lower: if hasattr(self, "_rotate_api_key") and self._rotate_api_key( provider, permanent=True ): continue blocked_models.add(model_name) self._dead_models.add(model_name) break is_daily_exhausted = any( marker in err_lower for marker in ( "free-models-per-day", "perday", "per_day", "tokens per day", "tpd", "daily limit", ) ) is_provider_quota = is_daily_exhausted or any( marker in err_lower for marker in ( "quota", "resource_exhausted", ) ) is_model_rate_limit = http_status == 429 or any( marker in err_lower for marker in ( "429", "rate limit exceeded", "too many requests", ) ) if is_model_rate_limit and not is_provider_quota and provider == "nvidia_nim": if transient_retries < 2 and (deadline - time.monotonic()) > 15.0: transient_retries += 1 time.sleep(5.0) continue if is_provider_quota or is_model_rate_limit: if hasattr(self, "_rotate_api_key") and self._rotate_api_key( provider, permanent=is_daily_exhausted ): continue if is_daily_exhausted: for m in models_to_try: if m.startswith(f"{provider}/"): blocked_models.add(m) self._dead_models.add(m) blocked_providers.add(provider) break cooldown_until = time.monotonic() + 20.0 rate_limited_models.add(model_name) self._model_cooldowns[model_name] = cooldown_until if is_provider_quota: rate_limited_providers.add(provider) for m in models_to_try: if m.startswith(f"{provider}/"): rate_limited_models.add(m) self._model_cooldowns[m] = cooldown_until 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", ) ) is_hard_dead_model = http_status == 404 or any( marker in err_lower for marker in ( "model_not_found", "does not exist", "decommissioned", "no longer supported", "is not found for api version", "unknown model", ) ) is_bad_request = http_status == 400 or any( marker in err_lower for marker in ( "badrequesterror", "bad request", "invalid_request_error", "reasoning is mandatory", "cannot be disabled", "does not support", "unsupported", ) ) if is_hard_dead_model or is_bad_request or is_context_overflow: blocked_models.add(model_name) if is_hard_dead_model and not is_context_overflow: self._dead_models.add(model_name) break if http_status == 503 or 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: local_state = getattr(self, "_local_state", None) if local_state is not None: try: local_state.deadline = None except Exception: pass self._task_deadline = None return "" def _direct_extract_answer(self, model_name: str, question: str, evidence: str, deadline: float) -> str: import time import litellm rem = deadline - time.monotonic() if rem <= 5.0: return "" api_key = self._get_api_key(model_name) if not api_key: return "" kw = {"model": model_name, "api_key": api_key} if model_name.startswith("huggingface/"): kw = { "model": "openai/" + model_name[len("huggingface/"):], "api_base": "https://router.huggingface.co/v1", "api_key": api_key, } try: resp = litellm.completion( **kw, messages=[ { "role": "system", "content": ( "Extract ONLY the exact final answer to the user's question from the provided evidence. " "Output ONLY the exact requested value (number, single word/name, SAN chess move, or comma-separated list). " "NO sentences, NO explanations, NO markdown, NO units unless requested." ), }, { "role": "user", "content": f"Question:\n{question}\n\nEvidence:\n{evidence}", }, ], max_tokens=256, timeout=max(6.0, min(15.0, rem - 2.0)), num_retries=0, max_retries=0, ) txt = (resp.choices[0].message.content or "").strip() cleaned = self._clean_exact_match_answer(txt) if cleaned and len(cleaned) <= 300 and not cleaned.startswith("AGENT ERROR:"): return cleaned except Exception as exc: print(f"[DIRECT EXTRACT ERR] model={model_name}: {exc}", flush=True) return "" 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 not isinstance(c_ans, str): continue raw_cached = c_ans.strip() if ( not raw_cached or len(raw_cached) > 120 or raw_cached.startswith("AGENT ERROR:") or "</code>" in raw_cached.lower() or "without access to" in raw_cached.lower() or "gaia_questions.json" in raw_cached.lower() ): continue clean_cached = agent._clean_exact_match_answer(raw_cached) if not clean_cached or clean_cached.startswith("AGENT ERROR:"): continue 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) if not isinstance(submitted_answer, str) or not submitted_answer.strip(): submitted_answer = "AGENT ERROR: Empty answer" 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}) valid_to_cache = [ row for row in results_log if isinstance(row.get("Submitted Answer"), str) and row["Submitted Answer"].strip() and not row["Submitted Answer"].strip().startswith("AGENT ERROR:") ] try: with open(partial_path, "w", encoding="utf-8") as f_part: json.dump(valid_to_cache, 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)
import os
import gradio as gr
import requests
import inspect
import pandas as pd
import posixpath
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.suppress_debug_info = 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."
)