From 45c78079d03cae108764f5d379839c76b4c1b899 Mon Sep 17 00:00:00 2001 From: ossfix26 Date: Fri, 27 Nov 2026 17:14:40 +0000 Subject: [PATCH] fix: parse Markdown code fences robustly in model output parse_code_blobs fell back to a single regex requiring a lowercase ```python/```py fence with a newline immediately before the closing fence. Common LLM variants were rejected (bare fences, capitalized ```Python, indented and tilde fences), and the info string of a ```python3 fence leaked into the extracted code. Replace the fallback with extract_markdown_code_from_text, which recognizes CommonMark-style fences (backticks or tildes, optional indentation, optional case-insensitive python/py info string with an optional version suffix), strips the info string, normalizes CRLF and de-indenes fenced bodies. Non-Python blocks and unclosed fences are ignored, preserving the existing ValueError/ast-parse fallbacks. Adds deterministic unit tests covering the reported variants. Fixes #201. Co-Authored-By: Claude Fable 5 --- src/smolagents/utils.py | 44 +++++++++++++++++++++++++++++++++++++++-- tests/test_utils.py | 36 +++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 2 deletions(-) diff --git a/src/smolagents/utils.py b/src/smolagents/utils.py index 69ade343..3b8f75f8 100644 --- a/src/smolagents/utils.py +++ b/src/smolagents/utils.py @@ -195,6 +195,46 @@ def extract_code_from_text(text: str, code_block_tags: tuple[str, str]) -> str | return None +_MARKDOWN_CODE_BLOCK_PATTERN = re.compile( + r"(?m)^[ \t]*(?P[`~]{3,})(?P[^\n]*)\r?\n" + r"(?P.*?)\r?\n" + # Trailing characters on the closing line are tolerated because the agent + # may append its configured closing tag (e.g. "") to model output. + r"^[ \t]*(?P=fence)[^\n]*", + re.DOTALL, +) +_PYTHON_CODE_BLOCK_INFO_PATTERN = re.compile(r"^(?:python|py)(?:\d+(?:\.\d+)*)?$", re.IGNORECASE) + + +def extract_markdown_code_from_text(text: str) -> str | None: + """Extract code from Markdown fenced code blocks emitted by LLMs. + + Tolerates the formatting variants commonly observed in model outputs: + bare fences (no info string), a case-insensitive ``python``/``py`` info + string with an optional version suffix (e.g. ``python3``), indented fences, + tilde fences and CRLF line endings. Blocks declaring another language + (e.g. ``javascript`` or ``bash``) are ignored, and the info string is never + included in the extracted code. + + Args: + text (`str`): LLM's output text to parse. + + Returns: + `str` or `None`: The extracted code blocks joined, or `None` if no + matching fenced code block is found. + """ + matches = [] + for match in _MARKDOWN_CODE_BLOCK_PATTERN.finditer(text): + info = match.group("info").strip() + info_token = info.split()[0] if info else "" + if info_token and not _PYTHON_CODE_BLOCK_INFO_PATTERN.fullmatch(info_token): + continue + body = match.group("body").replace("\r\n", "\n").replace("\r", "\n") + # Remove indentation shared with the opening fence (e.g. fences nested in lists) + matches.append(dedent(body).strip()) + return "\n\n".join(matches) if matches else None + + def parse_code_blobs(text: str, code_block_tags: tuple[str, str]) -> str: """Extract code blocs from the LLM's output. @@ -210,8 +250,8 @@ def parse_code_blobs(text: str, code_block_tags: tuple[str, str]) -> str: ValueError: If no valid code block is found in the text. """ matches = extract_code_from_text(text, code_block_tags) - if not matches: # Fallback to markdown pattern - matches = extract_code_from_text(text, ("```(?:python|py)", "\n```")) + if not matches: # Fallback to Markdown fenced code blocks + matches = extract_markdown_code_from_text(text) if matches: return matches # Maybe the LLM outputted a code blob directly diff --git a/tests/test_utils.py b/tests/test_utils.py index 740ee394..89c27229 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -24,6 +24,7 @@ from smolagents import Tool from smolagents.tools import tool from smolagents.utils import ( create_agent_gradio_app_template, + extract_markdown_code_from_text, get_source, instance_to_source, is_valid_name, @@ -142,6 +143,41 @@ import numpy as np result = parse_code_blobs(test_input, ("", "")) assert result == "Foo\n\ncode_a\n\ncode_b" + def test_extract_markdown_code_from_text(self): + # Bare fences and case variants of the language tag should be extracted. + assert extract_markdown_code_from_text("```\nFoo()\n```") == "Foo()" + assert extract_markdown_code_from_text("```Python\nFoo()\n```") == "Foo()" + assert extract_markdown_code_from_text("```PYTHON\nFoo()\n```") == "Foo()" + # The info string must not leak into the extracted code. + assert extract_markdown_code_from_text("```python3\nFoo()\n```") == "Foo()" + assert extract_markdown_code_from_text("```py3.11\nFoo()\n```") == "Foo()" + # Indented fences and tilde fences should be extracted and de-indented. + assert extract_markdown_code_from_text(" ```python\n Foo()\n ```") == "Foo()" + assert extract_markdown_code_from_text("~~~\nFoo()\n~~~") == "Foo()" + # CRLF line endings should be normalized. + assert extract_markdown_code_from_text("```python\r\nFoo()\r\n```") == "Foo()" + # Several blocks are joined with two newlines. + assert extract_markdown_code_from_text("```python\nA()\n```\ntext\n```\nB()\n```") == "A()\n\nB()" + # Relative indentation inside the code is preserved. + assert extract_markdown_code_from_text("```python\ndef f():\n return 1\n```") == "def f():\n return 1" + # Non-Python blocks are ignored. + assert extract_markdown_code_from_text("```javascript\nFoo()\n```") is None + assert extract_markdown_code_from_text("not a fenced block") is None + + def test_parse_code_blobs_markdown_fallbacks(self): + # Real LLM outputs use Markdown fences although the agent's + # configured tags are ("", ""); see issue #201. + markdown_outputs = [ + "Here is the code:\n```\nFoo()\n```", + "Here is the code:\n```Python\nFoo()\n```", + "Here is the code:\n```python3\nFoo()\n```", + "```\n Foo()\n```", + "Here is the code:\n~~~\nFoo()\n~~~", + "Here is the code:\n```python\nFoo()\n```", + ] + for markdown_output in markdown_outputs: + assert parse_code_blobs(markdown_output, ("", "")) == "Foo()" + @pytest.fixture(scope="function") def ipython_shell(): -- 2.47.3