import os import gradio as gr import requests import inspect import pandas as pd try: import spaces @spaces.GPU def _register_zerogpu(): return None except ImportError: pass # (Keep Constants as is) # --- Constants --- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space" # --- Basic Agent Definition --- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------ class BasicAgent: def __init__(self): import re import base64 import mimetypes import litellm from smolagents import CodeAgent, LiteLLMModel, tool litellm.drop_params = True litellm.request_timeout = 120 provider_env_prefixes = { "openrouter": ("OPENROUTER_API_KEY", "OPENROUTER_TOKEN", "OPENROUTER_KEY"), "gemini": ("GEMINI_API_KEY", "GOOGLE_API_KEY", "GEMINI_TOKEN", "GOOGLE_GEMINI_API_KEY"), "groq": ("GROQ_API_KEY", "GROQ_TOKEN"), "huggingface": ("HF_TOKEN", "HUGGINGFACE_API_KEY", "HUGGINGFACEHUB_API_TOKEN", "HUGGINGFACE_TOKEN"), } raw_pools = {p: [] for p in provider_env_prefixes} def _classify_token(token: str, default_provider: str) -> str: if token.startswith("sk-or-"): return "openrouter" if token.startswith("AIza"): return "gemini" if token.startswith("gsk_"): return "groq" if token.startswith("hf_"): return "huggingface" return default_provider for raw_name, raw_val in os.environ.items(): if not raw_val: continue env_name = raw_name.upper().strip() matched_provider = next( ( prov for prov, prefixes in provider_env_prefixes.items() if any(env_name == pref or env_name.startswith(pref + "_") for pref in prefixes) ), None, ) if not matched_provider: continue for part in re.split(r"[\s,;]+", raw_val): tok = part.strip(" '\"\n\r\t[]") if tok: target_prov = _classify_token(tok, matched_provider) raw_pools[target_prov].append(tok) self.provider_key_pools = { prov: list(dict.fromkeys(tokens)) for prov, tokens in raw_pools.items() } self._provider_key_idx = {prov: 0 for prov in self.provider_key_pools} openrouter_key = self.provider_key_pools["openrouter"][0] if self.provider_key_pools["openrouter"] else "" groq_key = self.provider_key_pools["groq"][0] if self.provider_key_pools["groq"] else "" hf_key = self.provider_key_pools["huggingface"][0] if self.provider_key_pools["huggingface"] else "" gemini_key = self.provider_key_pools["gemini"][0] if self.provider_key_pools["gemini"] else "" self.provider_keys = { "openrouter": openrouter_key, "groq": groq_key, "huggingface": hf_key, "gemini": gemini_key, } if not any(self.provider_keys.values()): raise ValueError( "Missing API key in Space secrets. Add at least one of: " "OPENROUTER_API_KEY, GROQ_API_KEY, HF_TOKEN, or GEMINI_API_KEY." ) self.gemini_key = gemini_key if gemini_key: os.environ["GEMINI_API_KEY"] = gemini_key os.environ["GOOGLE_API_KEY"] = gemini_key if openrouter_key: os.environ["OPENROUTER_API_KEY"] = openrouter_key if groq_key: os.environ["GROQ_API_KEY"] = groq_key if hf_key: os.environ["HF_TOKEN"] = hf_key os.environ["HUGGINGFACE_API_KEY"] = hf_key import threading 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 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(20.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) <= 24000: return cleaned return cleaned[:12000] + "\n...\n" + cleaned[-12000:] except Exception as e: return f"Error fetching URL '{url}': {str(e)}" @tool def download_task_file( task_id: str, output_dir: str = "/tmp/gaia_files", preferred_filename: str = "", ) -> str: """Downloads a task attachment from the course API by task_id and returns the local file path. Args: task_id: Task identifier from the evaluation dataset. output_dir: Local directory where the file should be saved. preferred_filename: Optional original attachment filename from the task metadata. """ import re import time from urllib.parse import unquote clean_id = (task_id or "").strip() if not clean_id: return "Error downloading file: missing task_id." os.makedirs(output_dir, exist_ok=True) safe_pref_name = os.path.basename((preferred_filename or "").strip()) if safe_pref_name: cached_pref_path = os.path.join(output_dir, safe_pref_name) if os.path.isfile(cached_pref_path) and os.path.getsize(cached_pref_path) > 0: return cached_pref_path base_url = DEFAULT_API_URL.rstrip("/") candidate_urls = [ f"{base_url}/files/{clean_id}", f"{base_url}/attachments/{clean_id}", ] last_err = None for url in candidate_urls: resp = None for attempt in range(3): try: resp = requests.get( url, timeout=(10.0, _tool_timeout(30.0, min_timeout=5.0)), headers={"User-Agent": "Mozilla/5.0"}, ) if resp.status_code in {429, 502, 503, 504} and attempt < 2: _tool_timeout(4.0, min_timeout=1.0) time.sleep(1.5 * (attempt + 1)) continue break except Exception as exc: last_err = exc if "task time budget exhausted" in str(exc).lower(): return f"Error downloading file for task '{clean_id}': {str(exc)}" if attempt < 2: try: _tool_timeout(4.0, min_timeout=1.0) time.sleep(1.5 * (attempt + 1)) continue except Exception: resp = None break resp = None break if resp is None or resp.status_code == 404: continue try: resp.raise_for_status() except Exception as exc: last_err = exc continue if not resp.content: continue content_disp = resp.headers.get("Content-Disposition", "") filename = safe_pref_name if not filename: star_match = re.search( r"filename\*\s*=\s*(?:[A-Za-z0-9_-]+''|\"[A-Za-z0-9_-]+'')?([^\";]+)", content_disp, flags=re.IGNORECASE, ) if star_match: raw_star = star_match.group(1).strip().strip('"') if "''" in raw_star: raw_star = raw_star.split("''", 1)[1] filename = os.path.basename(unquote(raw_star)) if not filename: std_match = re.search( r'filename\s*=\s*"?([^";]+)"?', content_disp, flags=re.IGNORECASE, ) if std_match: filename = os.path.basename(unquote(std_match.group(1).strip())) if not filename: content_type = resp.headers.get("Content-Type", "").split(";")[0].strip().lower() ext_map = { "text/plain": ".txt", "text/csv": ".csv", "application/json": ".json", "application/pdf": ".pdf", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ".xlsx", "application/vnd.ms-excel": ".xls", "image/png": ".png", "image/jpeg": ".jpg", "audio/mpeg": ".mp3", "audio/wav": ".wav", "text/x-python": ".py", } ext = ext_map.get(content_type) or mimetypes.guess_extension(content_type) or ".bin" filename = f"{clean_id}{ext}" out_path = os.path.join(output_dir, filename) with open(out_path, "wb") as f: f.write(resp.content) return out_path if last_err is not None: return f"Error downloading file for task '{clean_id}': {str(last_err)}" return f"No attachment available for task '{clean_id}' (404 Not Found)." self._download_task_file = download_task_file @tool def read_local_file(file_path: str) -> str: """Reads text, PDF, DOCX, PPTX, ZIP archive, or spreadsheet content from a local file downloaded by download_task_file. Args: file_path: Local path to the downloaded file. """ import re import xml.etree.ElementTree as ET import zipfile def _read_single(path: str, max_chars: int) -> str: f_ext = os.path.splitext(path)[1].lower() if f_ext in {".xlsx", ".xlsm", ".xls"}: sheets = pd.read_excel(path, sheet_name=None) if not sheets: return "Empty Excel workbook." text = "\n\n".join( f"=== Sheet: {s_name} ===\n{df.to_csv(index=False)}" for s_name, df in sheets.items() ) elif f_ext == ".pdf": try: from pypdf import PdfReader reader = PdfReader(path) pages = [ f"=== Page {i + 1} ===\n{(p.extract_text() or '').strip()}" for i, p in enumerate(reader.pages) ] text = "\n\n".join(p for p in pages if p.strip()) or "Empty PDF text." except Exception as pdf_exc: return f"Error reading PDF '{path}': {str(pdf_exc)}" elif f_ext == ".docx": try: with zipfile.ZipFile(path, "r") as zf: if "word/document.xml" not in zf.namelist(): return f"Invalid DOCX archive '{path}': missing word/document.xml." root = ET.fromstring(zf.read("word/document.xml")) paragraphs = [] for p_elem in root.iter(): if p_elem.tag.endswith("}p"): runs = [ t_elem.text for t_elem in p_elem.iter() if t_elem.tag.endswith("}t") and t_elem.text ] line = "".join(runs).strip() if line: paragraphs.append(line) text = "\n".join(paragraphs) or "Empty DOCX document." except Exception as docx_exc: return f"Error reading DOCX '{path}': {str(docx_exc)}" elif f_ext == ".pptx": try: with zipfile.ZipFile(path, "r") as zf: slide_names = [ name for name in zf.namelist() if re.fullmatch(r"ppt/slides/slide\d+\.xml", name) ] slide_names.sort( key=lambda n: int(re.search(r"slide(\d+)\.xml$", n).group(1)) ) slides_out = [] for idx, s_name in enumerate(slide_names, start=1): root = ET.fromstring(zf.read(s_name)) s_lines = [] for p_elem in root.iter(): if p_elem.tag.endswith("}p"): runs = [ t_elem.text for t_elem in p_elem.iter() if t_elem.tag.endswith("}t") and t_elem.text ] line = "".join(runs).strip() if line: s_lines.append(line) slides_out.append(f"=== Slide {idx} ===\n" + ("\n".join(s_lines) or "(empty)")) text = "\n\n".join(slides_out) or "Empty PPTX presentation." except Exception as pptx_exc: return f"Error reading PPTX '{path}': {str(pptx_exc)}" elif f_ext in {".png", ".jpg", ".jpeg", ".webp", ".gif"}: return f"Binary image file '{path}'. Use inspect_image(image_path='{path}', question=...)." elif f_ext in {".mp3", ".wav", ".m4a", ".ogg", ".flac"}: return f"Binary audio file '{path}'. Use transcribe_audio(audio_path='{path}', question=...)." else: with open(path, "r", encoding="utf-8", errors="replace") as f: text = f.read() if len(text) <= max_chars: return text half = max_chars // 2 return text[:half] + "\n...\n" + text[-half:] try: if not os.path.isfile(file_path): return f"File not found: '{file_path}'" ext = os.path.splitext(file_path)[1].lower() office_zip_exts = {".xlsx", ".xlsm", ".xls", ".docx", ".pptx"} if ext == ".zip" or (ext not in office_zip_exts and zipfile.is_zipfile(file_path)): extract_dir = os.path.join( os.path.dirname(file_path), f"extracted_{os.path.basename(file_path)}", ) os.makedirs(extract_dir, exist_ok=True) base_extract = os.path.realpath(extract_dir) sections = [] with zipfile.ZipFile(file_path, "r") as zf: members = [m for m in zf.namelist() if not m.endswith("/")] sections.append( f"=== ZIP Archive ({len(members)} files) ===\nFiles: {', '.join(members)}" ) for member in members: target_path = os.path.realpath(os.path.join(extract_dir, member)) if not (target_path == base_extract or target_path.startswith(base_extract + os.sep)): sections.append(f"=== {member} ===\nSkipped unsafe path.") continue os.makedirs(os.path.dirname(target_path), exist_ok=True) with zf.open(member, "r") as src, open(target_path, "wb") as dst: dst.write(src.read()) try: content_str = _read_single(target_path, max_chars=24000) sections.append(f"=== {member} (extracted to {target_path}) ===\n{content_str}") except Exception as m_exc: sections.append(f"=== {member} (extracted to {target_path}) ===\nRead error: {m_exc}") joined_zip = "\n\n".join(sections) if len(joined_zip) <= 48000: return joined_zip return joined_zip[:24000] + "\n...\n" + joined_zip[-24000:] return _read_single(file_path, max_chars=48000) except Exception as e: return f"Error reading file '{file_path}': {str(e)}" self._read_local_file = read_local_file @tool def web_search(query: str) -> str: """Searches the web for a query and returns top results with titles, URLs, and snippets. Args: query: The search query string. """ from concurrent.futures import ThreadPoolExecutor import re from html import unescape from urllib.parse import parse_qs, unquote, urlparse clean_q = (query or "").strip() if not clean_q: return "Empty search query." def _clean_ddg_href(raw_href: str) -> str: h = unescape((raw_href or "").strip()) if h.startswith("//"): h = "https:" + h if "duckduckgo.com/l/?" in h or h.startswith("/l/?"): parsed = urlparse(h) uddg = parse_qs(parsed.query).get("uddg") if uddg and uddg[0]: return unquote(uddg[0]) return h results_out = [] try: ddgs_timeout = _tool_timeout(8.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(8.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(8.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 time
if getattr(self, "_last_llm_error", None) is not None:
raise self._last_llm_error
litellm.suppress_debug_info = True
t0 = time.monotonic()
call_kwargs = self._prepare_call_kwargs(dict(kwargs))
call_kwargs["num_retries"] = 0
req_timeout = float(call_kwargs.get("timeout") or getattr(self, "timeout", None) or 45.0)
hard_timeout = req_timeout + 8.0
executor = ThreadPoolExecutor(max_workers=1)
future = executor.submit(super().generate, *args, **call_kwargs)
try:
raw_msg = future.result(timeout=hard_timeout)
msg = self._validate_message(raw_msg)
self._last_llm_error = None
return msg
except FutureTimeoutError:
timeout_exc = TimeoutError(
f"LLM call timed out after {hard_timeout:.1f}s for {self.model_id}"
)
self._last_llm_error = timeout_exc
raise timeout_exc
except Exception as exc:
self._last_llm_error = exc
raise
finally:
executor.shutdown(wait=False, cancel_futures=True)
print(f"[LLM] {self.model_id}: {time.monotonic() - t0:.1f}s", flush=True)
@classmethod
def _sanitize_code_tags(cls, text: str) -> str:
import ast
import re
open_t = cls.open_tag
close_t = cls.close_tag
def _extract_valid_python(raw: str) -> str:
lines = []
for line in raw.splitlines():
stripped = line.lstrip()
if re.match(r"^(?:thoughts?|thinking)\s*:", stripped, flags=re.IGNORECASE):
lines.append("# " + stripped)
else:
lines.append(line)
n = len(lines)
for start in range(n):
if not lines[start].strip():
continue
for end in range(n, start, -1):
candidate = "\n".join(lines[start:end]).strip()
if not candidate:
continue
try:
ast.parse(candidate)
return candidate
except SyntaxError:
continue
return "\n".join(lines).strip()
cleaned_text = re.sub(r"<\|[^|]+\|>", "", text)
cleaned_text = re.sub(r"?code[^>]*>\s*```", "\n", cleaned_text, flags=re.IGNORECASE)
cleaned_text = re.sub(r"```\s*?code[^>]*>", "\n", cleaned_text, flags=re.IGNORECASE)
html_match = re.search(r"(.*?)", cleaned_text, flags=re.DOTALL | re.IGNORECASE)
if html_match:
inner = html_match.group(1)
inner = re.sub(r"```(?:py|python)?\s*\n?", "", inner, flags=re.IGNORECASE)
inner = re.sub(r"\n?```", "", inner)
inner = re.sub(r"?code[^>]*>", "", inner, flags=re.IGNORECASE)
return f"{open_t}\n{_extract_valid_python(inner)}\n{close_t}"
md_match = re.search(
r"```(?:py|python)?\s*\n(.*?)```",
cleaned_text,
flags=re.DOTALL | re.IGNORECASE,
)
if md_match:
inner = re.sub(r"?code[^>]*>", "", md_match.group(1), flags=re.IGNORECASE)
return f"{open_t}\n{_extract_valid_python(inner)}\n{close_t}"
stripped_orphan_tags = re.sub(r"?code[^>]*>", "", cleaned_text, flags=re.IGNORECASE).strip()
if stripped_orphan_tags != cleaned_text.strip() and stripped_orphan_tags:
return f"{open_t}\n{_extract_valid_python(stripped_orphan_tags)}\n{close_t}"
if "final_answer(" in cleaned_text:
extracted = _extract_valid_python(cleaned_text)
if "final_answer(" in extracted:
return f"{open_t}\n{extracted}\n{close_t}"
return cleaned_text
@classmethod
def _validate_message(cls, msg):
import json
import re
if msg is None:
raise RuntimeError(
"Error in generating model output: empty model response (content=None)"
)
def _extract_text_from_blocks(val) -> str:
if val is None:
return ""
if isinstance(val, str):
return val.strip()
if isinstance(val, list):
parts = []
for part in val:
if isinstance(part, dict):
txt = part.get("text") or part.get("thinking") or part.get("content")
if txt:
parts.append(str(txt))
else:
txt = (
getattr(part, "text", None)
or getattr(part, "thinking", None)
or getattr(part, "content", None)
)
if txt:
parts.append(str(txt))
return "\n".join(parts).strip()
return str(val).strip()
raw_obj = getattr(msg, "raw", None)
raw_msg = None
finish_reason = ""
if raw_obj is not None:
choices = raw_obj.get("choices") if isinstance(raw_obj, dict) else getattr(raw_obj, "choices", None)
if choices:
first_choice = choices[0]
finish_reason = str(
(
first_choice.get("finish_reason")
if isinstance(first_choice, dict)
else getattr(first_choice, "finish_reason", "")
)
or ""
).lower()
raw_msg = (
first_choice.get("message")
if isinstance(first_choice, dict)
else getattr(first_choice, "message", None)
)
content_str = _extract_text_from_blocks(getattr(msg, "content", None))
reasoning_sources = [
getattr(msg, "reasoning_content", None),
getattr(msg, "reasoning", None),
]
if raw_msg is not None:
if isinstance(raw_msg, dict):
reasoning_sources.extend([
raw_msg.get("reasoning_content"),
raw_msg.get("reasoning"),
raw_msg.get("thinking_blocks"),
])
else:
reasoning_sources.extend([
getattr(raw_msg, "reasoning_content", None),
getattr(raw_msg, "reasoning", None),
getattr(raw_msg, "thinking_blocks", None),
])
reasoning_str = next(
(txt for src in reasoning_sources if (txt := _extract_text_from_blocks(src))),
"",
)
tool_calls = getattr(msg, "tool_calls", None)
if not tool_calls and raw_msg is not None:
tool_calls = (
raw_msg.get("tool_calls")
if isinstance(raw_msg, dict)
else getattr(raw_msg, "tool_calls", None)
)
if not content_str and not tool_calls and not reasoning_str and "malformed_function_call" in finish_reason:
raise RuntimeError(
"Error in generating model output: malformed_function_call with empty content"
)
if not content_str and tool_calls:
rendered_calls = []
for tc in tool_calls:
fn_obj = getattr(tc, "function", None)
if fn_obj is None and isinstance(tc, dict):
fn_obj = tc.get("function")
fn_name = getattr(fn_obj, "name", None) if fn_obj is not None else None
if fn_name is None and isinstance(fn_obj, dict):
fn_name = fn_obj.get("name")
fn_args = getattr(fn_obj, "arguments", None) if fn_obj is not None else None
if fn_args is None and isinstance(fn_obj, dict):
fn_args = fn_obj.get("arguments")
if not fn_name:
continue
if isinstance(fn_args, str):
try:
parsed_args = json.loads(fn_args) if fn_args.strip() else {}
except Exception:
parsed_args = {"query": fn_args}
else:
parsed_args = fn_args or {}
if isinstance(parsed_args, dict):
rendered_calls.append(
f"print({fn_name}(**{json.dumps(parsed_args, ensure_ascii=False)}))"
)
if rendered_calls:
content_str = f"{cls.open_tag}\n" + "\n".join(rendered_calls) + f"\n{cls.close_tag}"
if not content_str and reasoning_str:
code_matches = re.findall(
r"(.*?|```(?:py|python)?\s*\n.*?```)",
reasoning_str,
flags=re.DOTALL | re.IGNORECASE,
)
if code_matches:
content_str = code_matches[-1].strip()
elif re.search(r"\bfinal_answer\s*\(", reasoning_str):
content_str = reasoning_str
else:
fa_matches = re.findall(
r"(?im)^\s*(?:final\s*answer|answer)\s*:\s*(.+)$",
reasoning_str,
)
if fa_matches and fa_matches[-1].strip():
ans_val = fa_matches[-1].strip()
content_str = (
f"{cls.open_tag}\n"
f"final_answer({json.dumps(ans_val, ensure_ascii=False)})\n"
f"{cls.close_tag}"
)
else:
raise RuntimeError(
"Error in generating model output: reasoning-only response without code block or final_answer()"
)
if not content_str:
print(
f"[EMPTY] finish_reason={finish_reason!r} raw={repr(raw_obj)[:800]}",
flush=True,
)
raise RuntimeError(
"Error in generating model output: empty model response (content=None)"
)
cleaned = cls._sanitize_code_tags(content_str)
if cls.open_tag not in cleaned and cls.close_tag not in cleaned:
fa_direct = re.findall(
r"(?im)^\s*(?:final\s*answer|answer)\s*:\s*(.+)$",
cleaned,
)
if fa_direct and fa_direct[-1].strip():
ans_val = fa_direct[-1].strip()
cleaned = (
f"{cls.open_tag}\n"
f"final_answer({json.dumps(ans_val, ensure_ascii=False)})\n"
f"{cls.close_tag}"
)
if not cleaned.strip():
raise RuntimeError(
"Error in generating model output: empty model response after sanitization"
)
try:
msg.content = cleaned
msg.tool_calls = None
except Exception:
pass
if getattr(msg, "content", None) != cleaned or getattr(msg, "tool_calls", None) is not None:
try:
from smolagents.models import ChatMessage
except ImportError:
from smolagents import ChatMessage
cm_kwargs = {
"role": getattr(msg, "role", "assistant"),
"content": cleaned,
"tool_calls": None,
"raw": getattr(msg, "raw", None),
"token_usage": getattr(msg, "token_usage", None),
}
cm_sig = inspect.signature(ChatMessage.__init__)
msg = ChatMessage(
**{k: v for k, v in cm_kwargs.items() if k != "self" and k in cm_sig.parameters}
)
return msg
def _prepare_call_kwargs(self, kwargs: dict) -> dict:
import time
key = kwargs.pop("api_key", None) or getattr(self, "_explicit_api_key", None)
api_base = kwargs.pop("api_base", None) or getattr(self, "_explicit_api_base", None)
model_name = str(getattr(self, "model_id", "") or "")
if api_base:
self.api_base = api_base
if isinstance(getattr(self, "kwargs", None), dict):
self.kwargs["api_base"] = api_base
if key:
self.api_key = key
if isinstance(getattr(self, "kwargs", None), dict):
self.kwargs["api_key"] = key
if model_name.startswith("groq/"):
default_cap = 45.0
elif model_name.startswith("openrouter/"):
default_cap = 55.0
else:
default_cap = 55.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(8.0, min(timeout, remaining - 2.0))
self.timeout = timeout
if isinstance(getattr(self, "kwargs", None), dict):
self.kwargs["timeout"] = timeout
kwargs["timeout"] = timeout
litellm.request_timeout = timeout
if model_name.startswith("groq/"):
kwargs["max_tokens"] = 1536
if isinstance(getattr(self, "kwargs", None), dict):
self.kwargs["max_tokens"] = 1536
if "qwen3" in model_name.lower():
kwargs.setdefault("reasoning_effort", "none")
if model_name.startswith("gemini/"):
kwargs.setdefault("reasoning_effort", "low")
if "gemini-3" in model_name.lower():
kwargs.pop("temperature", None)
if isinstance(getattr(self, "kwargs", None), dict):
self.kwargs.pop("temperature", None)
if model_name.startswith("openrouter/"):
kwargs["max_tokens"] = 1536
if isinstance(getattr(self, "kwargs", None), dict):
self.kwargs["max_tokens"] = 1536
kwargs.setdefault("reasoning_effort", "none")
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": 45}
if model_name.startswith("gemini/"):
kwargs = {
"model_id": model_name,
"api_key": api_key,
"max_tokens": 4096,
"reasoning_effort": "low",
**common,
}
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": 4096,
**common,
}
else:
kwargs = {
"model_id": model_name,
"api_key": api_key,
"max_tokens": 4096,
**common,
}
return self._model_cls(**kwargs)
def _probe_candidate(model_name: str) -> tuple[str, str, str]:
import time
api_key = self._get_api_key(model_name)
if not api_key:
return (model_name, "dead", "no api key")
t0 = time.monotonic()
try:
kw = {"model": model_name, "api_key": api_key}
if model_name.startswith("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=64,
timeout=20,
num_retries=0,
)
return (model_name, "ok", f"{time.monotonic() - t0:.1f}s")
except Exception as exc:
text = f"{type(exc).__name__}: {exc}"
low = text.lower()
short = " ".join(text.split())[:220]
busy_markers = (
"429", "rate limit", "quota", "resource_exhausted",
"timeout", "timed out", "connection", "503", "overloaded", "unavailable",
)
if any(m in low for m in busy_markers):
return (model_name, "busy", short)
return (model_name, "dead", short)
from concurrent.futures import ThreadPoolExecutor, wait as futures_wait
# OpenRouter :free ma 50 zapytań/dzień – nie marnujemy ich na test
probe_targets = [m for m in self.working_models if not m.startswith("openrouter/")][:8]
probe_status = {}
probe_pool = ThreadPoolExecutor(max_workers=6)
try:
probe_futures = [probe_pool.submit(_probe_candidate, m) for m in probe_targets]
done, _ = futures_wait(probe_futures, timeout=30)
for fut in done:
try:
p_name, p_state, p_info = fut.result()
probe_status[p_name] = p_state
print(f"[PREFLIGHT] {p_state.upper():4} {p_name} :: {p_info}", flush=True)
except Exception:
pass
finally:
probe_pool.shutdown(wait=False, cancel_futures=True)
tested_providers = {
m.split("/", 1)[0].lower() for m in probe_status if "/" in m
}
for prov in tested_providers:
prov_states = [
st for m, st in probe_status.items() if m.startswith(f"{prov}/")
]
if prov_states and all(st == "dead" for st in prov_states):
self.provider_key_pools[prov] = []
self._sync_provider_env(prov, "")
ok_models = [m for m in self.working_models if probe_status.get(m) == "ok"]
untested = [m for m in self.working_models if m not in probe_status]
busy_models = [m for m in self.working_models if probe_status.get(m) == "busy"]
reordered = ok_models + untested + busy_models
if reordered:
self.working_models = reordered
self.model_id = self.working_models[0]
print(f"Using primary LLM model: {self.model_id} (fallbacks: {self.working_models[1:]})")
self._build_model = _build_model
model = self._build_model(self.model_id)
exact_match_rule = (
"CRITICAL OUTPUT RULES FOR EXACT MATCH EVALUATION:\n"
f"- Always write valid Python code inside {code_open_tag} and {code_close_tag} tags. "
"NEVER put 'Thought:' or extra markdown fences inside the code block.\n"
"- NEVER import or call 'subprocess', 'os.system', 'os.popen', or shell commands. "
"Use the provided tools and allowed Python modules only.\n"
"- Always call provided tools directly as Python functions inside the code block "
"(e.g. web_search(query=...), search_wikipedia(query=...), fetch_url_text(url=...), "
"read_local_file(file_path=...), inspect_image(image_path=..., question=...), "
"inspect_youtube(url=..., question=...), transcribe_audio(audio_path=..., question=...)).\n"
"- If the prompt includes a Task ID and mentions an image, board, diagram, or attached file, FIRST call path = download_task_file(task_id=...) and inspect it.\n"
"- Never call built-in open(); use read_local_file(file_path) for text/PDF/ZIP/spreadsheet files, "
"inspect_image(image_path, question) for images, and transcribe_audio(audio_path, question) for audio files (.mp3, .wav).\n"
"- If web_search returns no results, use search_wikipedia(query) or fetch_url_text(url).\n"
"- Return ONLY the concise exact answer value itself "
"(e.g. a number, date, name, or short phrase) via final_answer().\n"
"- NEVER include introductory text, explanations, markdown formatting, or the phrase 'FINAL ANSWER'.\n"
"- Do not wrap the answer in a dictionary like {'answer': ...}; pass the plain answer string directly."
)
from smolagents import MultiStepAgent
accepted_params = set(sig.parameters) | set(inspect.signature(MultiStepAgent.__init__).parameters)
agent_kwargs = {
"tools": [
web_search,
search_wikipedia,
ask_web,
fetch_url_text,
download_task_file,
read_local_file,
inspect_image,
inspect_youtube,
transcribe_audio,
],
"additional_authorized_imports": [
"json",
"csv",
"pandas",
"numpy",
"urllib.request",
"urllib.parse",
"urllib.error",
"html",
"decimal",
"fractions",
"string",
"re",
"time",
"math",
"cmath",
"statistics",
"datetime",
"collections",
"itertools",
"operator",
"openpyxl",
],
"instructions": exact_match_rule,
"code_block_tags": (code_open_tag, code_close_tag),
"max_steps": 6,
"verbosity_level": 0,
}
def _create_code_agent(model_instance):
def _abort_on_fatal_llm_error(step_log, *args, **kwargs):
llm_err = getattr(model_instance, "_last_llm_error", None)
if llm_err is not None:
raise llm_err
local_kwargs = dict(agent_kwargs)
local_kwargs["model"] = model_instance
local_kwargs["step_callbacks"] = [_abort_on_fatal_llm_error]
filtered_local = {k: v for k, v in local_kwargs.items() if k in accepted_params}
return CodeAgent(**filtered_local)
self._create_code_agent = _create_code_agent
self.agent = _create_code_agent(model)
if not hasattr(self, "_build_model") or not hasattr(self, "agent"):
raise RuntimeError("BasicAgent.__init__ failed to bind _build_model or self.agent.")
print("CodeAgent initialized with LiteLLMModel.")
def _clean_exact_match_answer(self, text: str) -> str:
import re
if text is None:
return ""
cleaned = str(text).strip()
if not cleaned or cleaned.startswith("AGENT ERROR:"):
return cleaned
cleaned = re.sub(r"?code[^>]*>", "", cleaned, flags=re.IGNORECASE).strip()
fa_call = re.fullmatch(
r"final_answer\(\s*(?:answer\s*=\s*)?(.*?)\s*\)",
cleaned,
flags=re.DOTALL,
)
if fa_call:
cleaned = fa_call.group(1).strip()
if cleaned.startswith("```") and cleaned.endswith("```"):
lines = cleaned.splitlines()
if len(lines) >= 3:
cleaned = "\n".join(lines[1:-1]).strip()
else:
cleaned = cleaned.strip("`").strip()
lines = [ln.strip() for ln in cleaned.splitlines() if ln.strip()]
if len(lines) > 1:
for ln in reversed(lines):
m_final = re.match(
r"^(?:\*\*)?(?:final\s+answer|answer|result|output)(?:\*\*)?\s*:\s*(.+)$",
ln,
flags=re.IGNORECASE,
)
if m_final:
cleaned = m_final.group(1).strip()
break
else:
cleaned = lines[-1]
prefix_match = re.match(
r"^(?:\*\*)?(?:final\s+answer|the\s+final\s+answer\s+is|the\s+answer\s+is|answer|result|output)(?:\*\*)?\s*:?\s+(.+)$",
cleaned,
flags=re.IGNORECASE,
)
had_prefix = False
if prefix_match:
cleaned = prefix_match.group(1).strip()
had_prefix = True
trailing_bold = re.search(r"\*\*([^*]+?)\*\*[.!?]?\s*$", cleaned)
if trailing_bold:
candidate = trailing_bold.group(1).strip()
prefix_part = cleaned[: trailing_bold.start()].strip().lower()
if (
candidate
and len(candidate) <= 120
and (
not prefix_part
or prefix_part.startswith(
("according to", "based on", "under ", "in ", "from ", "the ", "this ", "it is", "it was")
)
)
):
cleaned = candidate
had_prefix = True
if len(cleaned) >= 2 and (
(cleaned.startswith("**") and cleaned.endswith("**"))
or (cleaned.startswith("__") and cleaned.endswith("__"))
or (cleaned.startswith("`") and cleaned.endswith("`"))
or (cleaned.startswith('"') and cleaned.endswith('"'))
or (cleaned.startswith("'") and cleaned.endswith("'"))
):
cleaned = cleaned[2:-2].strip() if cleaned.startswith(("**", "__")) else cleaned[1:-1].strip()
if had_prefix and cleaned.endswith(".") and not re.search(r"\b(?:Mr|Mrs|Ms|Dr|St|Jr|Sr|Inc|Ltd|vs|etc)\.$", cleaned):
cleaned = cleaned[:-1].strip()
if re.match(
r"^(?:title|channel|transcript|description|duration|views|url|source|file\s*path|status|error|no\s+transcript)\s*:",
cleaned,
flags=re.IGNORECASE,
):
return ""
return cleaned
def __call__(self, question: str, task_id: str = "", file_name: str = "") -> str:
import time
import threading
if not hasattr(self, "_local_state"):
self._local_state = threading.local()
if not hasattr(self, "_dead_models"):
self._dead_models = set()
if not hasattr(self, "_model_cooldowns"):
self._model_cooldowns = {}
if hasattr(self, "_reset_key_indices"):
self._reset_key_indices()
deadline = time.monotonic() + 185.0
self._local_state.deadline = deadline
self._task_deadline = deadline
try:
prompt = question.strip()
self._prefer_2022_wiki = "2022" in prompt.lower()
clean_file_name = (file_name or "").strip()
tools_map = getattr(getattr(self, "agent", None), "tools", {}) or {}
if task_id:
prefetched_path = ""
if hasattr(self, "_download_task_file"):
for _attempt in range(2):
try:
res_path = self._download_task_file(
task_id=task_id,
preferred_filename=clean_file_name,
)
if (
isinstance(res_path, str)
and not res_path.startswith(("Error ", "No attachment"))
and os.path.isfile(res_path)
):
prefetched_path = res_path
break
except Exception as dl_exc:
print(f"[DOWNLOAD WARN] task_id={task_id} attempt={_attempt + 1}: {dl_exc}", flush=True)
if not clean_file_name:
break
time.sleep(1.0)
if prefetched_path:
ext = os.path.splitext(prefetched_path)[1].lower()
if ext in {".mp3", ".wav", ".m4a", ".ogg", ".flac"}:
tool_hint = f"Call transcribe_audio(audio_path='{prefetched_path}', question=...) if more detail is needed."
transcribe_fn = getattr(self, "_transcribe_audio", None) or tools_map.get("transcribe_audio")
if transcribe_fn is not None:
try:
tr_preview = transcribe_fn(
audio_path=prefetched_path,
question=question.strip(),
)
if (
isinstance(tr_preview, str)
and tr_preview.strip()
and not tr_preview.startswith(("Error ", "Audio file not found"))
):
prompt += (
f"\n\nTask ID: {task_id}. Audio file '{prefetched_path}' transcription:\n"
f"{tr_preview.strip()[:8000]}"
)
tool_hint = ""
except Exception as tr_exc:
print(f"[PRE-TRANSCRIBE WARN] task_id={task_id}: {tr_exc}", flush=True)
if tool_hint:
prompt += (
f"\n\nTask ID: {task_id}. The task attachment is downloaded at '{prefetched_path}'. "
f"{tool_hint}"
)
elif ext in {".png", ".jpg", ".jpeg", ".webp", ".gif"}:
prompt += (
f"\n\nTask ID: {task_id}. The task attachment is downloaded at '{prefetched_path}'. "
f"Call inspect_image(image_path='{prefetched_path}', question=...) immediately."
)
else:
tool_hint = f"Call read_local_file(file_path='{prefetched_path}') immediately."
read_fn = getattr(self, "_read_local_file", None) or tools_map.get("read_local_file")
if read_fn is not None:
try:
file_preview = read_fn(file_path=prefetched_path)
if (
isinstance(file_preview, str)
and file_preview.strip()
and not file_preview.startswith(("Error ", "File not found"))
):
prompt += (
f"\n\nTask ID: {task_id}. Attachment '{prefetched_path}' content:\n"
f"{file_preview.strip()[:12000]}"
)
tool_hint = ""
except Exception as rd_exc:
print(f"[PRE-READ WARN] task_id={task_id}: {rd_exc}", flush=True)
if tool_hint:
prompt += (
f"\n\nTask ID: {task_id}. The task attachment is downloaded at '{prefetched_path}'. "
f"{tool_hint}"
)
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(15.0, min(55.0, rem_now - 3.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 > 30.0 else 4
result = run_agent.run(prompt)
print(
f"[TRACE] task_id={task_id} model={model_name} "
f"elapsed={time.monotonic() - step_t0:.1f}s returned={type(result).__name__}",
flush=True,
)
raw_result = "" if result is None else str(result).strip()
if raw_result.lower().startswith("error in generating"):
raise RuntimeError(raw_result)
cleaned = self._clean_exact_match_answer(raw_result)
if cleaned and not cleaned.startswith("AGENT ERROR:"):
return cleaned
blocked_models.add(model_name)
break
except Exception as exc:
llm_err = getattr(built_model, "_last_llm_error", None)
if llm_err is not None and llm_err is not exc:
exc = llm_err
err_text = str(exc)
err_lower = err_text.lower()
print(f"[AGENT ERROR] task_id={task_id} model={model_name}: {err_text}", flush=True)
if "task time budget exhausted" in err_lower:
break
http_status = getattr(exc, "status_code", None)
if http_status in (401, 402, 403) or any(
marker in err_lower
for marker in (
"authentication",
"invalid api key",
"api key not valid",
"permission_denied",
"insufficient permissions",
)
):
if hasattr(self, "_rotate_api_key") and self._rotate_api_key(
provider, permanent=True
):
continue
for m in models_to_try:
if m.startswith(f"{provider}/"):
blocked_models.add(m)
blocked_providers.add(provider)
break
if any(
marker in err_lower
for marker in (
"free-models-per-day",
"quota",
"resource_exhausted",
"429",
"rate limit exceeded",
)
):
if hasattr(self, "_rotate_api_key") and self._rotate_api_key(provider):
continue
cooldown_until = time.monotonic() + 20.0
rate_limited_models.add(model_name)
self._model_cooldowns[model_name] = cooldown_until
rate_limited_providers.add(provider)
break
if any(
marker in err_lower
for marker in (
"timeout",
"timed out",
)
):
blocked_models.add(model_name)
self._model_cooldowns[model_name] = time.monotonic() + 180.0
break
if any(
marker in err_lower
for marker in (
"404",
"not found",
"model_not_found",
"decommissioned",
"unsupported",
)
):
blocked_models.add(model_name)
self._dead_models.add(model_name)
break
if any(
marker in err_lower
for marker in (
"503",
"service unavailable",
"high demand",
"overloaded",
)
):
blocked_models.add(model_name)
self._model_cooldowns[model_name] = time.monotonic() + 180.0
break
if "connection error" in err_lower:
if transient_retries < 1 and (deadline - time.monotonic()) > 10.0:
transient_retries += 1
time.sleep(0.5)
continue
blocked_models.add(model_name)
self._model_cooldowns[model_name] = time.monotonic() + 60.0
break
blocked_models.add(model_name)
break
if time.monotonic() >= deadline:
break
rotated_any = False
if hasattr(self, "_rotate_api_key"):
for prov in rate_limited_providers:
if prov not in blocked_providers:
pool = self.provider_key_pools.get(prov) or []
if self._provider_key_idx.get(prov, 0) + 1 < len(pool):
if self._rotate_api_key(prov):
rotated_any = True
if not rotated_any:
rem_after_pass = deadline - time.monotonic()
if rate_limited_models and backoff_rounds < 2 and rem_after_pass > 18.0:
backoff_rounds += 1
for prov in rate_limited_providers:
if prov not in blocked_providers:
pool = self.provider_key_pools.get(prov) or []
self._provider_key_idx[prov] = 0
if hasattr(self, "_sync_provider_env"):
self._sync_provider_env(prov, pool[0] if pool else "")
time.sleep(min(12.0, max(3.0, rem_after_pass - 15.0)))
continue
break
finally:
self._local_state.deadline = None
self._task_deadline = None
return "AGENT ERROR: All candidate models failed."
def _trim_tool_output(text: str, max_chars: int = 4000) -> str:
if not isinstance(text, str):
return str(text)
cleaned = "\n".join(line.strip() for line in text.splitlines() if line.strip())
if len(cleaned) <= max_chars:
return cleaned
return cleaned[:max_chars] + "\n...[truncated]..."
def run_and_submit_all(profile: gr.OAuthProfile | None):
"""
Fetches all questions, runs the BasicAgent on them, submits all answers,
and displays the results.
"""
# --- Determine HF Space Runtime URL and Repo URL ---
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
if profile:
username = f"{profile.username}"
print(f"User logged in: {username}")
else:
print("User not logged in.")
return "Please Login to Hugging Face with the button.", None
api_url = DEFAULT_API_URL
questions_url = f"{api_url}/questions"
submit_url = f"{api_url}/submit"
# 1. Instantiate Agent ( modify this part to create your agent)
try:
agent = BasicAgent()
except Exception as e:
print(f"Error instantiating agent: {e}")
return f"Error initializing agent: {e}", None
# In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
agent_code = (
f"https://huggingface.co/spaces/{space_id.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 your Agent
from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeoutError
import json
import time
results_log = []
answers_payload = []
partial_path = "/tmp/gaia_partial_results.json"
cached_by_task_id = {}
cached_by_question = {}
try:
if os.path.isfile(partial_path):
with open(partial_path, "r", encoding="utf-8") as f_cache:
cached_items = json.load(f_cache)
if isinstance(cached_items, list):
for c_item in cached_items:
if not isinstance(c_item, dict):
continue
c_tid = c_item.get("Task ID")
c_q = c_item.get("Question")
c_ans = c_item.get("Submitted Answer")
if (
isinstance(c_ans, str)
and c_ans.strip()
and not c_ans.strip().startswith("AGENT ERROR:")
and "" not in c_ans.lower()
and "without access to" not in c_ans.lower()
):
clean_cached = c_ans.strip()
if isinstance(c_tid, str) and c_tid.strip():
cached_by_task_id[c_tid.strip()] = clean_cached
if isinstance(c_q, str) and c_q.strip():
cached_by_question[c_q.strip()] = clean_cached
except Exception:
cached_by_task_id = {}
cached_by_question = {}
print(f"Running agent on {len(questions_data)} questions...")
ran_fresh_query = False
for idx, item in enumerate(questions_data):
task_id = item.get("task_id")
question_text = item.get("question")
file_name = str(item.get("file_name") or "").strip()
if not task_id or question_text is None:
print(f"Skipping item with missing task_id or question: {item}")
continue
clean_tid = str(task_id).strip()
clean_q = str(question_text).strip()
force_refresh = os.getenv("FORCE_REFRESH_TASKS", "").strip().lower() in {"1", "true", "yes"}
if not force_refresh and clean_tid in cached_by_task_id:
submitted_answer = cached_by_task_id[clean_tid]
elif not force_refresh and clean_q in cached_by_question:
submitted_answer = cached_by_question[clean_q]
else:
if ran_fresh_query:
time.sleep(2)
ran_fresh_query = True
executor = ThreadPoolExecutor(max_workers=1)
future = executor.submit(agent, question_text, task_id=task_id, file_name=file_name)
try:
submitted_answer = future.result(timeout=210)
except FutureTimeoutError:
print(f"Timeout running agent on task {task_id} after 210s.")
submitted_answer = "AGENT ERROR: Task timed out after 210s."
except Exception as e:
print(f"Error running agent on task {task_id}: {e}")
submitted_answer = f"AGENT ERROR: {e}"
finally:
executor.shutdown(wait=False, cancel_futures=True)
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
try:
with open(partial_path, "w", encoding="utf-8") as f_part:
json.dump(results_log, f_part, ensure_ascii=False, indent=2)
except Exception:
pass
# 4. Prepare Submission
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
print(status_update)
# 5. Submit
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
results_df = pd.DataFrame(results_log)
try:
response = None
for attempt in range(3):
try:
response = requests.post(submit_url, json=submission_data, timeout=(15, 90))
if response.status_code in {429, 502, 503, 504} and attempt < 2:
time.sleep(3 * (attempt + 1))
continue
response.raise_for_status()
break
except (requests.exceptions.Timeout, requests.exceptions.ConnectionError):
if attempt < 2:
time.sleep(3 * (attempt + 1))
continue
raise
result_data = response.json()
final_status = (
f"Submission Successful!\n"
f"User: {result_data.get('username')}\n"
f"Overall Score: {result_data.get('score', 'N/A')}% "
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
f"Message: {result_data.get('message', 'No message received.')}"
)
print("Submission successful.")
return final_status, results_df
except requests.exceptions.HTTPError as e:
error_detail = f"Server responded with status {e.response.status_code}."
try:
error_json = e.response.json()
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
except requests.exceptions.JSONDecodeError:
error_detail += f" Response: {e.response.text[:500]}"
status_message = f"Submission Failed: {error_detail}"
print(status_message)
return status_message, results_df
except requests.exceptions.Timeout:
status_message = "Submission Failed: The request timed out."
print(status_message)
return status_message, results_df
except requests.exceptions.RequestException as e:
status_message = f"Submission Failed: Network error - {e}"
print(status_message)
return status_message, results_df
except Exception as e:
status_message = f"An unexpected error occurred during submission: {e}"
print(status_message)
return status_message, results_df
# --- Build Gradio Interface using Blocks ---
with gr.Blocks() as demo:
gr.Markdown("# Basic Agent Evaluation Runner")
gr.Markdown(
"""
**Instructions:**
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
---
**Disclaimers:**
Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
"""
)
gr.LoginButton()
run_button = gr.Button("Run Evaluation & Submit All Answers")
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
# Removed max_rows=10 from DataFrame constructor
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
run_button.click(
fn=run_and_submit_all,
outputs=[status_output, results_table]
)
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)