File size: 837 Bytes
d06797b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
"""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