Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files208 unmodified lines2092102112122132142152162172182193 unmodified lines2232242252262272285 unmodified lines2342352362372382392403 unmodified lines2442452462472482492502512522532542552562572582592602611809 unmodified lines20712072207320742075207620773 unmodified lines2081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211212 unmodified lines212521262127212821292130213112 unmodified lines21442145214621472148214921502151215221532154215521562157215865 unmodified lines22242225222622272228222922302231223222332234223522362237223815 unmodified lines22542255225622572258225922601 unmodified line2262226322642265226622672268108 unmodified lines2377237823792380238123827 unmodified lines239023912392239323942395239623972398239924002401240224032404208 unmodified linesreturn f"Error fetching URL '{url}': {str(e)}"@tooldef download_task_file(task_id: str, output_dir: str = "/tmp/gaia_files") -> 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."""import refrom urllib.parse import unquote3 unmodified linesreturn "Error downloading file: missing task_id."os.makedirs(output_dir, exist_ok=True)base_url = DEFAULT_API_URL.rstrip("/")candidate_urls = [f"{base_url}/files/{clean_id}",5 unmodified linestry:resp = requests.get(url,timeout=_tool_timeout(8.0, min_timeout=2.0),headers={"User-Agent": "Mozilla/5.0"},)if resp.status_code == 404:3 unmodified linescontinuecontent_disp = resp.headers.get("Content-Disposition", "")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(1809 unmodified linesreturn textdef __call__(self, question: str, task_id: str = "") -> str:import timeimport threading3 unmodified linesif hasattr(self, "_reset_key_indices"):self._reset_key_indices()deadline = time.monotonic() + 55.0self._local_state.deadline = deadlinetry:prompt = question.strip()self._prefer_2022_wiki = "2022" in prompt.lower()if task_id:prefetched_path = ""if hasattr(self, "_download_task_file"):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_pathexcept Exception:passif prefetched_path: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=...).")else:prompt += f"\n\nTask ID: {task_id}."12 unmodified linesfor model_name in models_to_try:remaining = deadline - time.monotonic()if remaining <= 4.0:breakif not hasattr(self, "_build_model") or not hasattr(self, "_create_code_agent"):return "AGENT ERROR: Agent not initialized."12 unmodified linesbuilt_model = Nonetry:rem_now = deadline - time.monotonic()if rem_now <= 4.0:breakcall_timeout = max(4.0, min(9.0, rem_now - 2.0))self.model_id = model_namebuilt_model = self._build_model(model_name)built_model.timeout = call_timeoutbuilt_model.deadline = deadlinerun_agent = self._create_code_agent(built_model)run_agent.max_steps = 8 if rem_now > 20.0 else 5result = 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:passbreakif "connection error" in err_lower:if transient_retries < 1 and (deadline - time.monotonic()) > 6.0:transient_retries += 1time.sleep(0.5)continue15 unmodified linesrotated_any = Trueif not rotated_any:rem_after_pass = deadline - time.monotonic()if rate_limited_models and backoff_rounds < 2 and rem_after_pass > 12.0:backoff_rounds += 1for prov in rate_limited_providers:if prov not in blocked_providers:1 unmodified lineself._provider_key_idx[prov] = 0if 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)))continuebreakfinally:108 unmodified linesfor idx, item in enumerate(questions_data):task_id = item.get("task_id")question_text = item.get("question")if not task_id or question_text is None:print(f"Skipping item with missing task_id or question: {item}")continue7 unmodified linessubmitted_answer = cached_by_question[clean_q]else:if ran_fresh_query:time.sleep(3)ran_fresh_query = Trueexecutor = ThreadPoolExecutor(max_workers=1)future = executor.submit(agent, question_text, task_id=task_id)try:submitted_answer = future.result(timeout=80)except FutureTimeoutError:print(f"Timeout running agent on task {task_id} after 80s.")submitted_answer = "AGENT ERROR: Task timed out after 80s."except Exception as e:print(f"Error running agent on task {task_id}: {e}")submitted_answer = f"AGENT ERROR: {e}"208 unmodified lines2092102112122132142152162172182192202212222232243 unmodified lines2282292302312322332342352362372382395 unmodified lines2452462472482492502513 unmodified lines2552562572582592602612622632642652662672682692702712722731809 unmodified lines20832084208520862087208820893 unmodified lines2093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214512 unmodified lines215821592160216121622163216412 unmodified lines21772178217921802181218221832184218521862187218821892190219165 unmodified lines22572258225922602261226222632264226515 unmodified lines22812282228322842285228622871 unmodified line2289229022912292229322942295108 unmodified lines24042405240624072408240924107 unmodified lines241824192420242124222423242424252426242724282429243024312432208 unmodified linesreturn f"Error fetching URL '{url}': {str(e)}"@tooldef 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 refrom urllib.parse import unquote3 unmodified linesreturn "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_pathbase_url = DEFAULT_API_URL.rstrip("/")candidate_urls = [f"{base_url}/files/{clean_id}",5 unmodified linestry:resp = requests.get(url,timeout=_tool_timeout(20.0, min_timeout=5.0),headers={"User-Agent": "Mozilla/5.0"},)if resp.status_code == 404:3 unmodified linescontinuecontent_disp = resp.headers.get("Content-Disposition", "")filename = safe_pref_nameif 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(1809 unmodified linesreturn textdef __call__(self, question: str, task_id: str = "", file_name: str = "") -> str:import timeimport threading3 unmodified linesif hasattr(self, "_reset_key_indices"):self._reset_key_indices()deadline = time.monotonic() + 140.0self._local_state.deadline = deadlinetry: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,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_pathbreakexcept Exception as dl_exc:print(f"[DOWNLOAD WARN] task_id={task_id} attempt={_attempt + 1}: {dl_exc}", flush=True)if not clean_file_name:breaktime.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 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 linesfor model_name in models_to_try:remaining = deadline - time.monotonic()if remaining <= 6.0:breakif not hasattr(self, "_build_model") or not hasattr(self, "_create_code_agent"):return "AGENT ERROR: Agent not initialized."12 unmodified linesbuilt_model = Nonetry:rem_now = deadline - time.monotonic()if rem_now <= 6.0:breakcall_timeout = max(12.0, min(35.0, rem_now - 3.0))self.model_id = model_namebuilt_model = self._build_model(model_name)built_model.timeout = call_timeoutbuilt_model.deadline = deadlinerun_agent = self._create_code_agent(built_model)run_agent.max_steps = 8 if rem_now > 35.0 else 5result = 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)breakif "connection error" in err_lower:if transient_retries < 1 and (deadline - time.monotonic()) > 10.0:transient_retries += 1time.sleep(0.5)continue15 unmodified linesrotated_any = Trueif not rotated_any:rem_after_pass = deadline - time.monotonic()if rate_limited_models and backoff_rounds < 2 and rem_after_pass > 15.0:backoff_rounds += 1for prov in rate_limited_providers:if prov not in blocked_providers:1 unmodified lineself._provider_key_idx[prov] = 0if 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 - 10.0)))continuebreakfinally:108 unmodified linesfor 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 linessubmitted_answer = cached_by_question[clean_q]else:if ran_fresh_query:time.sleep(2)ran_fresh_query = Trueexecutor = ThreadPoolExecutor(max_workers=1)future = executor.submit(agent, question_text, task_id=task_id, file_name=file_name)try:submitted_answer = future.result(timeout=150)except FutureTimeoutError: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