Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files208 unmodified lines2092102112122122132142152162172182192202212222232243 unmodified lines2282292302312322332342352362372382395 unmodified lines2452462472372482492502513 unmodified lines2552562572472582592602492502512522532542552562572582612622632642652662672682692702712722731809 unmodified lines208320842085207420862087208820893 unmodified lines2093209420952084209620972098209921002101210221032104210521062107210821092110209320942095209620972098209921002101210221112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421062107210821092135213621372138213921402141214221432144214512 unmodified lines2158215921602128216121622163216412 unmodified lines21772178217921472180218121492182218321842185218621872155218821892190219165 unmodified lines225722582259222722282229223022312232226022612235226222632264226515 unmodified lines228122822283225722842285228622871 unmodified line22892290229122652292229322942295108 unmodified lines24042405240624072408240924107 unmodified lines24182419242023932421242224232396242424252398242624272400240124282429243024312432208 unmodified lines return f"Error fetching URL '{url}': {str(e)}"
@tool def download_task_file(task_id: str, output_dir: str = "/tmp/gaia_files") -> str: 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 from urllib.parse import unquote3 unmodified lines 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}",5 unmodified lines try: resp = requests.get( url, timeout=_tool_timeout(8.0, min_timeout=2.0), timeout=_tool_timeout(20.0, min_timeout=5.0), headers={"User-Agent": "Mozilla/5.0"}, ) if resp.status_code == 404:3 unmodified lines continue
content_disp = resp.headers.get("Content-Disposition", "") filename = "" 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)) 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(1809 unmodified lines
return text
def __call__(self, question: str, task_id: str = "") -> str: def __call__(self, question: str, task_id: str = "", file_name: str = "") -> str: import time import threading
3 unmodified lines if hasattr(self, "_reset_key_indices"): self._reset_key_indices()
deadline = time.monotonic() + 55.0 deadline = time.monotonic() + 140.0 self._local_state.deadline = deadline
try: prompt = question.strip() self._prefer_2022_wiki = "2022" in prompt.lower() clean_file_name = (file_name or "").strip()
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, try: res_path = self._download_task_file(task_id=task_id) if ( isinstance(res_path, str) and not res_path.startswith(("Error ", "No attachment")) and os.path.isfile(res_path) ): prefetched_path = res_path except Exception: pass 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=...) immediately." elif ext in {".png", ".jpg", ".jpeg", ".webp", ".gif"}: tool_hint = f"Call inspect_image(image_path='{prefetched_path}', question=...) immediately." else: tool_hint = f"Call read_local_file(file_path='{prefetched_path}') immediately." prompt += ( f"\n\nTask ID: {task_id}. The task attachment is already downloaded at '{prefetched_path}'. " f"Inspect it directly with read_local_file(file_path='{prefetched_path}'), " f"inspect_image(image_path='{prefetched_path}', question=...), or " f"transcribe_audio(audio_path='{prefetched_path}', question=...)." f"\n\nTask ID: {task_id}. The task attachment is downloaded at '{prefetched_path}'. " f"{tool_hint}" ) elif clean_file_name: prompt += ( f"\n\nTask ID: {task_id}. Expected attachment filename: '{clean_file_name}'. " f"First call download_task_file(task_id='{task_id}', preferred_filename='{clean_file_name}') " f"and inspect the downloaded file." ) else: prompt += f"\n\nTask ID: {task_id}."12 unmodified lines
for model_name in models_to_try: remaining = deadline - time.monotonic() if remaining <= 4.0: if remaining <= 6.0: break if not hasattr(self, "_build_model") or not hasattr(self, "_create_code_agent"): return "AGENT ERROR: Agent not initialized."12 unmodified lines built_model = None try: rem_now = deadline - time.monotonic() if rem_now <= 4.0: if rem_now <= 6.0: break call_timeout = max(4.0, min(9.0, rem_now - 2.0)) call_timeout = max(12.0, min(35.0, rem_now - 3.0)) self.model_id = model_name built_model = self._build_model(model_name) built_model.timeout = call_timeout built_model.deadline = deadline run_agent = self._create_code_agent(built_model) run_agent.max_steps = 8 if rem_now > 20.0 else 5 run_agent.max_steps = 8 if rem_now > 35.0 else 5 result = run_agent.run(prompt) raw_result = "" if result is None else str(result).strip() if raw_result.lower().startswith("error in generating"):65 unmodified lines ) ): blocked_models.add(model_name) if hasattr(self, "working_models"): try: self.working_models.remove(model_name) self.working_models.append(model_name) except ValueError: pass break if "connection error" in err_lower: if transient_retries < 1 and (deadline - time.monotonic()) > 6.0: if transient_retries < 1 and (deadline - time.monotonic()) > 10.0: transient_retries += 1 time.sleep(0.5) continue15 unmodified lines 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 > 12.0: if rate_limited_models and backoff_rounds < 2 and rem_after_pass > 15.0: backoff_rounds += 1 for prov in rate_limited_providers: if prov not in blocked_providers:1 unmodified line 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(3.0 * backoff_rounds, max(0.5, rem_after_pass - 8.0))) time.sleep(min(3.0 * backoff_rounds, max(0.5, rem_after_pass - 10.0))) continue break finally:108 unmodified lines 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}") continue7 unmodified lines submitted_answer = cached_by_question[clean_q] else: if ran_fresh_query: time.sleep(3) time.sleep(2) ran_fresh_query = True executor = ThreadPoolExecutor(max_workers=1) future = executor.submit(agent, question_text, task_id=task_id) future = executor.submit(agent, question_text, task_id=task_id, file_name=file_name) try: submitted_answer = future.result(timeout=80) submitted_answer = future.result(timeout=150) except FutureTimeoutError: print(f"Timeout running agent on task {task_id} after 80s.") submitted_answer = "AGENT ERROR: Task timed out after 80s." print(f"Timeout running agent on task {task_id} after 150s.") submitted_answer = "AGENT ERROR: Task timed out after 150s." except Exception as e: print(f"Error running agent on task {task_id}: {e}") submitted_answer = f"AGENT ERROR: {e}"app.py+75-47