Spaces:
Runtime error
Runtime error
Update app.py
Browse files243 unmodified lines244245246247247248249250251119 unmodified lines3713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334347 unmodified lines44244344438638738838939039139239339439539639739839940044544644744844976 unmodified lines526527528483484485486487488489490529530531532404 unmodified lines937938939940941942943217 unmodified lines1161116211631124116411651126116611671168369 unmodified lines15381539154015021503150415051506150715081541154215431544474 unmodified lines20192020202119891990202220232024116 unmodified lines2141214221432113214421452146777 unmodified lines292429252926292729282929293029312932239 unmodified lines317231733174317531763177317874 unmodified lines325332543255322332243256325732583259326032613262326332643265107 unmodified lines337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734 unmodified lines34623463346434653466337834673468346934703471347234733474347534763477226 unmodified lines37043705370637073708370937103711371237133714371537163717371837193720188 unmodified lines3909391039113811391239133914391539163917391839193920243 unmodified lines 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" base_dir = (output_dir or "").strip() or "/tmp/gaia_files" safe_out_dir = os.path.join(base_dir, clean_id) if clean_id else base_dir os.makedirs(safe_out_dir, exist_ok=True) safe_pref_name = os.path.basename((preferred_filename or "").strip())
119 unmodified lines
self._download_task_file = download_task_file
def _resolve_attachment_path(raw_path: str) -> str: if not raw_path: return raw_path cleaned = str(raw_path).strip().strip("'\"") if os.path.isfile(cleaned): return cleaned base_name = os.path.basename(cleaned) if not base_name: return cleaned
local_state = getattr(self, "_local_state", None) cur_tid = getattr(local_state, "task_id", "") if local_state is not None else "" if cur_tid: task_dir = os.path.join("/tmp/gaia_files", cur_tid) if os.path.isdir(task_dir): direct_tid = os.path.join(task_dir, base_name) if os.path.isfile(direct_tid): return direct_tid for root, _, files in os.walk(task_dir): if base_name in files: cand = os.path.join(root, base_name) if os.path.isfile(cand): return cand
for search_root in ("/tmp/gaia_files", "."): if not os.path.isdir(search_root): continue direct = os.path.join(search_root, base_name) if os.path.isfile(direct): return direct for root, dirs, files in os.walk(search_root): dirs[:] = [d for d in dirs if d not in {".git", "__pycache__", "venv", ".venv", "node_modules"}] if base_name in files: cand = os.path.join(root, base_name) if os.path.isfile(cand): return cand return cleaned
def inspect_spreadsheet(file_path: str) -> str: """Dumps all sheets of an Excel/CSV file with row indices and raw cell values.""" ext = os.path.splitext(file_path)[1].lower() if ext == ".csv": sheets = {"CSV": pd.read_csv(file_path, header=None)} else: sheets = pd.read_excel(file_path, sheet_name=None, header=None) out_lines = [] for s_name, raw_df in sheets.items(): out_lines.append(f"=== Sheet: {s_name} (shape={raw_df.shape}) ===") for r_idx, row in raw_df.iterrows(): vals = [ f"[{c_idx}]={repr(v)}" for c_idx, v in enumerate(row.tolist()) if pd.notna(v) and str(v).strip() != "" ] if vals: out_lines.append(f"Row {r_idx}: " + " | ".join(vals)) return "\n".join(out_lines) @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.7 unmodified lines
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)}" if f_ext in {".xlsx", ".xlsm", ".xls", ".csv"}: text = inspect_spreadsheet(path) or "Empty spreadsheet." elif f_ext == ".json": with open(path, "r", encoding="utf-8", errors="replace") as f: raw_j = f.read()76 unmodified lines 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 resolved = _resolve_attachment_path(file_path) if not os.path.isfile(resolved): return f"File not found: '{file_path}'"
404 unmodified lines import io
try: image_path = _resolve_attachment_path(image_path) if not os.path.isfile(image_path): return f"Image file not found: '{image_path}'"
217 unmodified lines import chess
fen_match = re.search( r"\b([rnbqkprnbqkprnbqkprnbqkprnbqkprnbqkprnbqkp1-8]{1,8}(?:/[rnbqkprnbqkprnbqkprnbqkprnbqkprnbqkprnbqkp1-8]{1,8}){7})\b", r"\b([rnbqkpRNBQKP1-8]{1,8}(?:/[rnbqkpRNBQKP1-8]{1,8}){7})\b", vision_summary, flags=re.IGNORECASE, ) if fen_match: raw_placement = fen_match.group(1)369 unmodified lines question: Specific transcription or analysis instruction for the audio. """ try: resolved_path = audio_path if not os.path.isfile(resolved_path): target_name = os.path.basename(audio_path) for root, _, files in os.walk("."): if target_name in files: resolved_path = os.path.join(root, target_name) break resolved_path = _resolve_attachment_path(audio_path) if not os.path.isfile(resolved_path): return f"Audio file not found: '{audio_path}'"
474 unmodified lines 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",116 unmodified lines raise finally: executor.shutdown(wait=False, cancel_futures=True) print(f"[LLM] {self.model_id}: {time.monotonic() - t0:.1f}s", flush=True)
@classmethod777 unmodified lines "os": os, "posixpath": posixpath, "repr": repr, "inspect_spreadsheet": inspect_spreadsheet, } accepted_params = set(sig.parameters) | set(inspect.signature(MultiStepAgent.__init__).parameters) agent_kwargs = { "tools": [239 unmodified lines
deadline = time.monotonic() + 185.0 self._local_state.deadline = deadline self._local_state.task_id = (task_id or "").strip() self._task_deadline = deadline
try:74 unmodified lines 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." "CRITICAL RULES FOR EXCEL/CSV:\n" "1. First inspect raw rows with `inspect_spreadsheet(file_path)` or `pd.read_excel(..., sheet_name=None, header=None)` " "so you see exact header rows, footers/Total rows, and categories.\n" "2. Do NOT sum a 'Total' summary row together with line items.\n" "3. Before summing numeric/currency columns, ALWAYS clean strings with: " "`pd.to_numeric(col.astype(str).str.replace(r'[^0-9.-]', '', regex=True), errors='coerce').fillna(0)`.\n" "4. Apply any category exclusions carefully and format decimals exactly as requested (e.g., `f'{total:.2f}'`)." ) read_fn = getattr(self, "_read_local_file", None) or tools_map.get("read_local_file") if read_fn is not None:107 unmodified lines
backoff_rounds = 0
global_collected_obs = [] last_draft_result = ""
def _harvest_agent_memory(agent_obj) -> None: if agent_obj is None: return mem_steps = getattr(getattr(agent_obj, "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 "No Python code block produced" not in txt and len(txt) > 10 ): snippet = txt[:4500] if snippet not in global_collected_obs: global_collected_obs.append(snippet)
def _run_emergency_fallback() -> str: evidence_parts = list(global_collected_obs[-5:]) if last_draft_result and "max steps" not in last_draft_result.lower(): evidence_parts.append(f"Agent partial draft: {last_draft_result[:1500]}") evidence_blob = "\n---\n".join(evidence_parts).strip()
fallback_candidates = [ m for m in all_candidates if m not in self._dead_models and (m.split("/", 1)[0].lower() if "/" in m else "gemini") not in blocked_providers and self._get_api_key(m) ] for fb_model in fallback_candidates[:3]: hard_fb_deadline = max(deadline + 12.0, time.monotonic() + 10.0) ans = self._direct_extract_answer( model_name=fb_model, question=question.strip(), evidence=evidence_blob[:12000] if evidence_blob else "(No tool output collected; answer from general knowledge.)", deadline=hard_fb_deadline, ) if ans: print(f"[EMERGENCY FALLBACK OK] task_id={task_id} model={fb_model} ans={ans!r}", flush=True) return ans return ""
while time.monotonic() < deadline: rate_limited_models = set() rate_limited_providers = set()34 unmodified lines 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 = None try: result = run_agent.run(prompt) result = run_agent.run(prompt) finally: # Zbieramy obserwacje z kroków agenta nawet przy wyjątku _harvest_agent_memory(run_agent)
raw_result = "" if result is None else str(result).strip() if raw_result: last_draft_result = raw_result if raw_result.lower().startswith("error in generating"): raise RuntimeError(raw_result) cleaned = self._clean_exact_match_answer(raw_result)226 unmodified lines time.sleep(min(12.0, max(3.0, rem_after_pass - 15.0))) continue break
emergency_ans = _run_emergency_fallback() if emergency_ans: return emergency_ans finally: local_state = getattr(self, "_local_state", None) if local_state is not None: try: local_state.deadline = None local_state.task_id = "" except Exception: pass self._task_deadline = None188 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() file_name = str( item.get("file_name") or item.get("filename") or item.get("file") or "" ).strip() if not task_id or question_text is None: print(f"Skipping item with missing task_id or question: {item}") continueapp.py+146-40