"""Helpers for extracting and validating Python code from model responses.""" from __future__ import annotations import re _PYTHON_FENCE_RE = re.compile(r"```(?:python|py)\s*\n?(.*?)\n?```", re.DOTALL | re.IGNORECASE) _PYTHON_OPEN_FENCE_RE = re.compile(r"```(?:python|py)\s*\n?(.*)", re.DOTALL | re.IGNORECASE) def extract_python_code(answer: str) -> str | None: """Extract the Python code from a response, even when the closing fence is missing.""" cleaned = answer.strip() if not cleaned: return None fenced = _PYTHON_FENCE_RE.search(cleaned) if fenced: code = fenced.group(1).strip() return code or None opened = _PYTHON_OPEN_FENCE_RE.search(cleaned) if opened: code = opened.group(1).strip() return code or None return None