Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files1351 unmodified lines135213531354135513561357505 unmodified lines186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331351 unmodified linesself.agent = CodeAgent(**filtered_agent_kwargs)print("CodeAgent initialized with LiteLLMModel.")@staticmethoddef _clean_exact_match_answer(raw_answer) -> str:import re505 unmodified lines@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: The GAIA task identifier.output_dir: Target directory where the downloaded file is saved."""import refrom urllib.parse import unquoteurl = f"{DEFAULT_API_URL.rstrip('/')}/files/{task_id}"try:os.makedirs(output_dir, exist_ok=True)response = requests.get(url,timeout=30,headers={"User-Agent": "Mozilla/5.0"},)response.raise_for_status()content_disp = response.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(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 = response.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"{task_id}{ext}"file_path = os.path.join(output_dir, filename)with open(file_path, "wb") as f:f.write(response.content)return file_pathexcept Exception as e:return f"Error downloading file for task '{task_id}': {str(e)}"@tooldef read_local_file(file_path: str) -> str:1351 unmodified lines13521353135413551356135713581359136013611362136313641365136613671368136913701371505 unmodified lines187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261351 unmodified linesself.agent = CodeAgent(**filtered_agent_kwargs)print("CodeAgent initialized with LiteLLMModel.")def generate(self, messages, stop_sequences=None, grammar=None, tools_to_call_from=None, **kwargs):call_kwargs = dict(kwargs)call_kwargs.setdefault("timeout", 12)if tools_to_call_from:call_kwargs["tools"] = tools_to_call_fromif stop_sequences:call_kwargs["stop"] = stop_sequencesresponse = super().generate(messages, **call_kwargs)content = getattr(response, "content", None)if content is None or (isinstance(content, str) and not content.strip()):raise RuntimeError("empty model response (content=None)")return response@staticmethoddef _clean_exact_match_answer(raw_answer) -> str:import re505 unmodified lines@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."""clean_id = (task_id or "").strip()if not clean_id:return "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}",f"{base_url}/attachments/{clean_id}",]for url in candidate_urls:try:resp = requests.get(url, timeout=15)if resp.status_code == 404:continueresp.raise_for_status()if not resp.content:continuefilename = f"{clean_id}.bin"content_disp = resp.headers.get("content-disposition", "")if "filename=" in content_disp:raw_name = content_disp.split("filename=", 1)[1].strip().strip('"').strip("'")if raw_name:filename = os.path.basename(raw_name)else:ext = mimetypes.guess_extension(resp.headers.get("content-type", "").split(";")[0].strip())if ext: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_pathexcept Exception as exc:last_err = excreturn f"No attachment available for task '{clean_id}' (404 Not Found)."@tooldef read_local_file(file_path: str) -> str:
app.py+56-63