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)]*\bclass=['\"][^'\"]*result__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)]*\bclass=['\"][^'\"]*result-link[^'\"]*['\"][^>]*)>(.*?)", lite_resp.text, ) lite_snippets = re.findall( r"(?is)
", "") 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,
)
task_deadline = getattr(self, "deadline", None)
if task_deadline is not None:
remaining = task_deadline - time.monotonic()
if remaining <= 1.0:
raise RuntimeError("Task time budget exhausted")
req_timeout = max(1.0, min(req_timeout, remaining - 0.5))
hard_timeout = max(1.5, min(req_timeout + 2.0, remaining))
else:
hard_timeout = req_timeout + 3.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".*?|```(?: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 = 22.0
raw_timeout = kwargs.get("timeout") or getattr(self, "timeout", None) or default_cap
timeout = min(float(raw_timeout), default_cap)
task_deadline = getattr(self, "deadline", None)
if task_deadline is not None:
remaining = task_deadline - time.monotonic()
if remaining <= 2.5:
raise RuntimeError("Task time budget exhausted")
timeout = max(1.5, min(timeout, remaining - 1.5))
kwargs["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"
t0 = time.monotonic()
max_key_attempts = max(1, len(self.provider_key_pools.get(provider) or []))
tried_keys = set()
last_short = "no api key"
for _ in range(max_key_attempts):
api_key = self._get_api_key(model_name)
if not api_key or api_key in tried_keys:
return (model_name, "DEAD_KEY", last_short)
tried_keys.add(api_key)
try:
kw = {
"model": model_name,
"api_key": api_key,
"max_tokens": 128,
"timeout": 8,
"num_retries": 0,
"max_retries": 0,
}
if model_name.startswith("huggingface/"):
kw["model"] = "openai/" + model_name[len("huggingface/"):]
kw["api_base"] = "https://router.huggingface.co/v1"
elif model_name.startswith("gemini/") and "gemma" not in model_name.lower():
kw["reasoning_effort"] = "low"
elif model_name.startswith("groq/") and "qwen3" in model_name.lower():
kw["reasoning_effort"] = "none"
kw["reasoning_format"] = "hidden"
litellm.completion(
**kw,
messages=[{"role": "user", "content": "Reply with the single word OK."}],
)
return (model_name, "OK", f"{time.monotonic() - t0:.1f}s")
except Exception as exc:
status_kind = _classify_preflight_error(exc)
last_short = " ".join(f"{type(exc).__name__}: {exc}".split())[:220]
if status_kind == "DEAD_KEY":
_remove_specific_key(provider, api_key)
continue
return (model_name, status_kind, last_short)
return (model_name, "DEAD_KEY", last_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"]*>(.*?)", 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 "" 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)