Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files1775 unmodified lines17761777177817791780178117821783178417851786178717 unmodified lines180518061807180818091810241 unmodified lines2052205320542055205620572058205920602061206212 unmodified lines207520762077207820792080129 unmodified lines221022112212221322142215221622172218221922202221259 unmodified lines2481248224832484248524861775 unmodified lines@classmethoddef _sanitize_code_tags(cls, text: str) -> str:import astimport reopen_t = cls.open_tagclose_t = cls.close_tagdef _extract_valid_python(raw: str) -> str:lines = []for line in raw.splitlines():stripped = line.lstrip()17 unmodified linescontinuereturn "\n".join(lines).strip()cleaned_text = re.sub(r"<\|[^|]+\|>", "", text)cleaned_text = re.sub(r"</?code[^>]*>\s*```", "<code>\n", cleaned_text, flags=re.IGNORECASE)cleaned_text = re.sub(r"```\s*</?code[^>]*>", "\n</code>", cleaned_text, flags=re.IGNORECASE)241 unmodified linesif isinstance(getattr(self, "kwargs", None), dict):self.kwargs["api_key"] = keyif model_name.startswith("groq/"):default_cap = 18.0elif model_name.startswith("openrouter/"):default_cap = 25.0else:default_cap = 30.0timeout = min(float(getattr(self, "timeout", None) or default_cap), default_cap)task_deadline = getattr(self, "deadline", None)if task_deadline is not None:12 unmodified linesself.kwargs["max_tokens"] = 1536if "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():129 unmodified lines"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"259 unmodified linesf"\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()1775 unmodified lines17761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185017 unmodified lines1868186918701871187218731874187518761877241 unmodified lines2119212021212122212321242125212621272128212912 unmodified lines2142214321442145214621472148129 unmodified lines227822792280228122822283228422852286228722882289229022912292259 unmodified lines255225532554255525562557255825592560256125622563256425651775 unmodified lines@classmethoddef _sanitize_code_tags(cls, text: str) -> str:import astimport jsonimport reopen_t = cls.open_tagclose_t = cls.close_tagdef _convert_xml_tool_calls(raw: str) -> str | None:qwen_calls = re.findall(r"<tool_call>\s*<function=([A-Za-z_][A-Za-z0-9_]*)>(.*?)</function>\s*</tool_call>",raw,flags=re.DOTALL | re.IGNORECASE,)if qwen_calls:py_lines = []for fn_name, params_blob in qwen_calls:params = re.findall(r"<parameter=([A-Za-z_][A-Za-z0-9_]*)>(.*?)</parameter>",params_blob,flags=re.DOTALL | re.IGNORECASE,)kwargs_parts = []for p_name, p_val in params:val_clean = p_val.strip()try:parsed_val = json.loads(val_clean)kwargs_parts.append(f"{p_name}={repr(parsed_val)}")except Exception:kwargs_parts.append(f"{p_name}={json.dumps(val_clean, ensure_ascii=False)}")if fn_name in ("python_interpreter", "python", "code"):code_arg = next((v.strip() for k, v in params if k in ("code", "arguments", "script")), "")if code_arg:py_lines.append(code_arg)else:py_lines.append(f"print({fn_name}({', '.join(kwargs_parts)}))")if py_lines:return "\n".join(py_lines)dsml_blocks = re.findall(r"<[||]DSML[||]\s*invoke\s+name=['\"]([^'\"]+)['\"]\s*>(.*?)</[||]DSML[||]\s*invoke>",raw,flags=re.DOTALL | re.IGNORECASE,)if dsml_blocks:py_lines = []for inv_name, inv_body in dsml_blocks:dsml_params = re.findall(r"<[||]DSML[||]\s*parameter\s+name=['\"]([^'\"]+)['\"][^>]*>(.*?)</[||]DSML[||]\s*parameter>",inv_body,flags=re.DOTALL | re.IGNORECASE,)if inv_name in ("python_interpreter", "python", "code"):code_arg = next((v.strip() for k, v in dsml_params if k in ("arguments", "code", "script")), "")if code_arg:py_lines.append(code_arg)else:kwargs_parts = [f"{k}={json.dumps(v.strip(), ensure_ascii=False)}"for k, v in dsml_params]py_lines.append(f"print({inv_name}({', '.join(kwargs_parts)}))")if py_lines:return "\n".join(py_lines)return Nonedef _extract_valid_python(raw: str) -> str:converted = _convert_xml_tool_calls(raw)if converted is not None:raw = convertedlines = []for line in raw.splitlines():stripped = line.lstrip()17 unmodified linescontinuereturn "\n".join(lines).strip()converted_top = _convert_xml_tool_calls(text)if converted_top is not None:return f"{open_t}\n{_extract_valid_python(converted_top)}\n{close_t}"cleaned_text = re.sub(r"<\|[^|]+\|>", "", text)cleaned_text = re.sub(r"</?code[^>]*>\s*```", "<code>\n", cleaned_text, flags=re.IGNORECASE)cleaned_text = re.sub(r"```\s*</?code[^>]*>", "\n</code>", cleaned_text, flags=re.IGNORECASE)241 unmodified linesif isinstance(getattr(self, "kwargs", None), dict):self.kwargs["api_key"] = keyif model_name.startswith("groq/"):default_cap = 14.0elif model_name.startswith("openrouter/"):default_cap = 16.0else:default_cap = 24.0timeout = min(float(getattr(self, "timeout", None) or default_cap), default_cap)task_deadline = getattr(self, "deadline", None)if task_deadline is not None:12 unmodified linesself.kwargs["max_tokens"] = 1536if "qwen3" in model_name.lower():kwargs.setdefault("reasoning_effort", "none")kwargs.setdefault("reasoning_format", "hidden")if model_name.startswith("gemini/"):kwargs.setdefault("reasoning_effort", "low")if "gemini-3" in model_name.lower():129 unmodified lines"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, and NEVER import from 'tools'. ""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""- Never assign variables named 'log', 'print', or any tool name.\n""- Keep each Python code block fast (under 15 seconds) and avoid nested network loops.\n""- If inspect_youtube returns 'Transcript/Video Analysis Status: unavailable', do NOT call inspect_youtube again; immediately use web_search or search_wikipedia.\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"259 unmodified linesf"\n\nTask ID: {task_id}. The task attachment is downloaded at '{prefetched_path}'. "f"{tool_hint}")else:prompt += f"\n\nTask ID: {task_id}"if clean_file_name:prompt += f" (expected attachment filename: '{clean_file_name}')"prompt += (". If this task refers to an attached file, image, spreadsheet, audio, or document, "f"call download_task_file(task_id='{task_id}', preferred_filename='{clean_file_name}') first.")blocked_models = set(self._dead_models)blocked_providers = set()
app.py+83-4