Robustly strip markdown code fences from LLM-generated code. Handles edge cases that simple first/last fence stripping misses: - LLM self-correction mid-output ("Wait, I need to also write...") - Multiple code blocks in a single response - Stray ``` markers embedded in the middle of
(content: str)
| 4 | |
| 5 | |
| 6 | def _strip_code_fences(content: str) -> str: |
| 7 | """Robustly strip markdown code fences from LLM-generated code. |
| 8 | |
| 9 | Handles edge cases that simple first/last fence stripping misses: |
| 10 | - LLM self-correction mid-output ("Wait, I need to also write...") |
| 11 | - Multiple code blocks in a single response |
| 12 | - Stray ``` markers embedded in the middle of code |
| 13 | |
| 14 | Strategy: if multiple fenced code blocks exist, pick the longest |
| 15 | complete block (most likely the full file). If no fenced blocks are |
| 16 | detected, just strip any stray ``` lines. |
| 17 | """ |
| 18 | content = (content or "").strip() |
| 19 | if not content: |
| 20 | return content |
| 21 | |
| 22 | # --- Phase 1: extract code blocks delimited by ```...``` --- |
| 23 | blocks: list[str] = [] |
| 24 | lines = content.split("\n") |
| 25 | inside = False |
| 26 | block_lines: list[str] = [] |
| 27 | for line in lines: |
| 28 | stripped = line.strip() |
| 29 | if not inside and stripped.startswith("```"): |
| 30 | inside = True |
| 31 | block_lines = [] |
| 32 | continue |
| 33 | if inside and stripped == "```": |
| 34 | inside = False |
| 35 | blocks.append("\n".join(block_lines)) |
| 36 | continue |
| 37 | if inside: |
| 38 | block_lines.append(line) |
| 39 | |
| 40 | if blocks: |
| 41 | # Prefer the longest block (most likely the complete file) |
| 42 | best = max(blocks, key=len) |
| 43 | return best.strip() |
| 44 | |
| 45 | # --- Phase 2: no matched pairs — handle single opening fence --- |
| 46 | if lines[0].strip().startswith("```"): |
| 47 | lines = lines[1:] |
| 48 | # Also remove trailing fence if present |
| 49 | if lines and lines[-1].strip().startswith("```"): |
| 50 | lines = lines[:-1] |
| 51 | cleaned = "\n".join(lines).strip() |
| 52 | if cleaned: |
| 53 | return cleaned |
| 54 | |
| 55 | # --- Phase 3: remove any remaining stray ``` lines --- |
| 56 | cleaned_lines = [l for l in lines if l.strip() != "```"] |
| 57 | return "\n".join(cleaned_lines).strip() |
no test coverage detected