Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files1258 unmodified lines125912601261126212631264126512661267126812691270127112723 unmodified lines127612771278127212731279128012811282128312841285128612871288128928 unmodified lines131813191320131113211322132313242 unmodified lines1327132813291320133013311332133313241334133513361337133813291339134013411342108 unmodified lines145114521453144414541455145614575 unmodified lines14631464146514561466146714681469147014718 unmodified lines148014811482148314841485147314861487148814892 unmodified lines1492149314941482149514961497149864 unmodified lines1563156415651553155415551556156615571558155915601561156215671568156957 unmodified lines16271628162916261630163116321633163431 unmodified lines16661667166816641669167016711672166816731674167542 unmodified lines171817191720172117221723172417251726353 unmodified lines20802081208220762077208320842085208620871258 unmodified lines if 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.parameters code_open_tag, code_close_tag = ("<code>", "</code>") if supports_custom_tags else ("```py", "```")
class SafeLiteLLMModel(LiteLLMModel): open_tag = code_open_tag close_tag = code_close_tag
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._explicit_api_key = kwargs.get("api_key")3 unmodified lines if self._explicit_api_base: self.api_base = self._explicit_api_base
@staticmethod def _sanitize_code_tags(text: str) -> str: @classmethod def _sanitize_code_tags(cls, text: str) -> str: import ast import re
open_t = cls.open_tag close_t = cls.close_tag
def _extract_valid_python(raw: str) -> str: lines = [] for line in raw.splitlines():28 unmodified lines inner = 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>" 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"<code>\n{_extract_valid_python(inner)}\n</code>" 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"<code>\n{_extract_valid_python(stripped_orphan_tags)}\n</code>" 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"<code>\n{extracted}\n</code>" return f"{open_t}\n{extracted}\n{close_t}"
return cleaned_text
108 unmodified lines f"print({fn_name}(**{json.dumps(parsed_args, ensure_ascii=False)}))" ) if rendered_calls: content_str = "<code>\n" + "\n".join(rendered_calls) + "\n</code>" 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 lines content_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>' 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 lines
try: msg.content = cleaned msg.tool_calls = None except Exception: pass if getattr(msg, "content", None) != cleaned: if getattr(msg, "content", None) != cleaned or getattr(msg, "tool_calls", None) is not None: try: from smolagents.models import ChatMessage except ImportError:2 unmodified lines cm_kwargs = { "role": getattr(msg, "role", "assistant"), "content": cleaned, "tool_calls": getattr(msg, "tool_calls", None), "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"] = False model_instance = self._model_cls(**kwargs) return 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_instance
def _probe_candidate(model_name: str) -> tuple[str, bool]: api_key = self._get_api_key(model_name)57 unmodified lines
exact_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" 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>", "</code>"), "code_block_tags": (code_open_tag, code_close_tag), "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 lines f"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 lines
if space_id_startup: # Print repo URLs if SPACE_ID is found print(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") 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