Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files1258 unmodified lines12591260126112621263126412653 unmodified lines1269127012711272127312741275127612771278127928 unmodified lines13081309131013111312131313142 unmodified lines1317131813191320132113221323132413251326132713281329133013311332108 unmodified lines14411442144314441445144614475 unmodified lines14531454145514561457145814598 unmodified lines1468146914701471147214731474147514762 unmodified lines147914801481148214831484148564 unmodified lines155015511552155315541555155615571558155915601561156215631564156557 unmodified lines162316241625162616271628162931 unmodified lines1661166216631664166516661667166816691670167142 unmodified lines171417151716171717181719353 unmodified lines207320742075207620772078207920801258 unmodified linesif not self.working_models:raise RuntimeError("No models available for the configured API keys.")class SafeLiteLLMModel(LiteLLMModel):def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)self._explicit_api_key = kwargs.get("api_key")3 unmodified linesif self._explicit_api_base:self.api_base = self._explicit_api_base@staticmethoddef _sanitize_code_tags(text: str) -> str:import astimport redef _extract_valid_python(raw: str) -> str:lines = []for line in raw.splitlines():28 unmodified linesinner = re.sub(r"```(?:py|python)?\s*\n?", "", inner, flags=re.IGNORECASE)inner = re.sub(r"\n?```", "", inner)inner = re.sub(r"</?code[^>]*>", "", inner, flags=re.IGNORECASE)return f"<code>\n{_extract_valid_python(inner)}\n</code>"md_match = re.search(r"```(?:py|python)?\s*\n(.*?)```",2 unmodified lines)if md_match:inner = re.sub(r"</?code[^>]*>", "", md_match.group(1), flags=re.IGNORECASE)return f"<code>\n{_extract_valid_python(inner)}\n</code>"stripped_orphan_tags = re.sub(r"</?code[^>]*>", "", cleaned_text, flags=re.IGNORECASE).strip()if stripped_orphan_tags != cleaned_text.strip() and stripped_orphan_tags:return f"<code>\n{_extract_valid_python(stripped_orphan_tags)}\n</code>"if "final_answer(" in cleaned_text:extracted = _extract_valid_python(cleaned_text)if "final_answer(" in extracted:return f"<code>\n{extracted}\n</code>"return cleaned_text108 unmodified linesf"print({fn_name}(**{json.dumps(parsed_args, ensure_ascii=False)}))")if rendered_calls:content_str = "<code>\n" + "\n".join(rendered_calls) + "\n</code>"if not content_str and reasoning_str:code_match = re.search(5 unmodified linescontent_str = code_match.group(1).strip()else:first_line = reasoning_str.splitlines()[0].replace('"', "'")content_str = f'<code>\nprint(ask_web("{first_line[:120]}")) # fallback from reasoning\n</code>'if not content_str:raise RuntimeError(8 unmodified linestry:msg.content = cleanedexcept Exception:passif getattr(msg, "content", None) != cleaned:try:from smolagents.models import ChatMessageexcept ImportError:2 unmodified linescm_kwargs = {"role": getattr(msg, "role", "assistant"),"content": cleaned,"tool_calls": getattr(msg, "tool_calls", None),"raw": getattr(msg, "raw", None),"token_usage": getattr(msg, "token_usage", None),}64 unmodified lines"num_retries": 0,"timeout": 45,}if model_name.startswith("groq/"):kwargs["tool_choice"] = "auto"kwargs["parallel_tool_calls"] = Falsemodel_instance = self._model_cls(**kwargs)if model_name.startswith("groq/"):for attr_name in ("kwargs", "completion_kwargs", "model_kwargs"):target_dict = getattr(model_instance, attr_name, None)if isinstance(target_dict, dict):target_dict["tool_choice"] = "auto"return model_instancedef _probe_candidate(model_name: str) -> tuple[str, bool]:api_key = self._get_api_key(model_name)57 unmodified linesexact_match_rule = ("CRITICAL OUTPUT RULES FOR EXACT MATCH EVALUATION:\n""- Always write valid Python code inside <code> and </code> tags. NEVER put 'Thought:' or ``` fences inside the code block.\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"31 unmodified lines"time",],"instructions": exact_match_rule,"code_block_tags": ("<code>", "</code>"),"max_steps": 10,"verbosity_level": 0,}sig = inspect.signature(CodeAgent.__init__)filtered_agent_kwargs = {k: v for k, v in agent_kwargs.items() if k in sig.parameters}self.agent = CodeAgent(**filtered_agent_kwargs)42 unmodified linesf"or image, use download_task_file(task_id='{task_id}') to inspect it.")blocked_models = getattr(self, "_blocked_models", None)if blocked_models is None:blocked_models = set()353 unmodified linesif space_id_startup: # Print repo URLs if SPACE_ID is foundprint(f"✅ SPACE_ID found: {space_id_startup}")print(f" Repo URL: [https://huggingface.co/spaces/](https://huggingface.co/spaces/){space_id_startup}")print(f" Repo Tree URL: [https://huggingface.co/spaces/](https://huggingface.co/spaces/){space_id_startup}/tree/main")else:print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")1258 unmodified lines125912601261126212631264126512661267126812691270127112723 unmodified lines1276127712781279128012811282128312841285128612871288128928 unmodified lines13181319132013211322132313242 unmodified lines1327132813291330133113321333133413351336133713381339134013411342108 unmodified lines14511452145314541455145614575 unmodified lines1463146414651466146714681469147014718 unmodified lines14801481148214831484148514861487148814892 unmodified lines149214931494149514961497149864 unmodified lines156315641565156615671568156957 unmodified lines1627162816291630163116321633163431 unmodified lines166616671668166916701671167216731674167542 unmodified lines171817191720172117221723172417251726353 unmodified lines208020812082208320842085208620871258 unmodified linesif not self.working_models:raise RuntimeError("No models available for the configured API keys.")sig = inspect.signature(CodeAgent.__init__)supports_custom_tags = "code_block_tags" in sig.parameterscode_open_tag, code_close_tag = ("<code>", "</code>") if supports_custom_tags else ("```py", "```")class SafeLiteLLMModel(LiteLLMModel):open_tag = code_open_tagclose_tag = code_close_tagdef __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)self._explicit_api_key = kwargs.get("api_key")3 unmodified linesif self._explicit_api_base:self.api_base = self._explicit_api_base@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():28 unmodified linesinner = re.sub(r"```(?:py|python)?\s*\n?", "", inner, flags=re.IGNORECASE)inner = re.sub(r"\n?```", "", inner)inner = re.sub(r"</?code[^>]*>", "", inner, flags=re.IGNORECASE)return f"{open_t}\n{_extract_valid_python(inner)}\n{close_t}"md_match = re.search(r"```(?:py|python)?\s*\n(.*?)```",2 unmodified lines)if md_match:inner = re.sub(r"</?code[^>]*>", "", md_match.group(1), flags=re.IGNORECASE)return f"{open_t}\n{_extract_valid_python(inner)}\n{close_t}"stripped_orphan_tags = re.sub(r"</?code[^>]*>", "", cleaned_text, flags=re.IGNORECASE).strip()if stripped_orphan_tags != cleaned_text.strip() and stripped_orphan_tags:return f"{open_t}\n{_extract_valid_python(stripped_orphan_tags)}\n{close_t}"if "final_answer(" in cleaned_text:extracted = _extract_valid_python(cleaned_text)if "final_answer(" in extracted:return f"{open_t}\n{extracted}\n{close_t}"return cleaned_text108 unmodified linesf"print({fn_name}(**{json.dumps(parsed_args, ensure_ascii=False)}))")if rendered_calls:content_str = f"{cls.open_tag}\n" + "\n".join(rendered_calls) + f"\n{cls.close_tag}"if not content_str and reasoning_str:code_match = re.search(5 unmodified linescontent_str = code_match.group(1).strip()else:first_line = reasoning_str.splitlines()[0].replace('"', "'")content_str = (f'{cls.open_tag}\nprint(ask_web("{first_line[:120]}")) # fallback from reasoning\n{cls.close_tag}')if not content_str:raise RuntimeError(8 unmodified linestry:msg.content = cleanedmsg.tool_calls = Noneexcept Exception:passif getattr(msg, "content", None) != cleaned or getattr(msg, "tool_calls", None) is not None:try:from smolagents.models import ChatMessageexcept ImportError:2 unmodified linescm_kwargs = {"role": getattr(msg, "role", "assistant"),"content": cleaned,"tool_calls": None,"raw": getattr(msg, "raw", None),"token_usage": getattr(msg, "token_usage", None),}64 unmodified lines"num_retries": 0,"timeout": 45,}return self._model_cls(**kwargs)def _probe_candidate(model_name: str) -> tuple[str, bool]:api_key = self._get_api_key(model_name)57 unmodified linesexact_match_rule = ("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""- 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"31 unmodified lines"time",],"instructions": exact_match_rule,"code_block_tags": (code_open_tag, code_close_tag),"max_steps": 10,"verbosity_level": 0,}filtered_agent_kwargs = {k: v for k, v in agent_kwargs.items() if k in sig.parameters}self.agent = CodeAgent(**filtered_agent_kwargs)42 unmodified linesf"or image, use download_task_file(task_id='{task_id}') to inspect it.")blocked_models = set()blocked_providers = set()blocked_models = getattr(self, "_blocked_models", None)if blocked_models is None:blocked_models = set()353 unmodified linesif space_id_startup: # Print repo URLs if SPACE_ID is foundprint(f"✅ SPACE_ID found: {space_id_startup}")print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")else:print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
app.py+32-25