forked from agent-lab/smolagents
probe internal PR #1
2 changed files with 78 additions and 2 deletions
|
|
@ -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<fence>[`~]{3,})(?P<info>[^\n]*)\r?\n"
|
||||
r"(?P<body>.*?)\r?\n"
|
||||
# Trailing characters on the closing line are tolerated because the agent
|
||||
# may append its configured closing tag (e.g. "</code>") 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
|
||||
|
|
|
|||
|
|
@ -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, ("<code>", "</code>"))
|
||||
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 ("<code>", "</code>"); 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```</code>",
|
||||
]
|
||||
for markdown_output in markdown_outputs:
|
||||
assert parse_code_blobs(markdown_output, ("<code>", "</code>")) == "Foo()"
|
||||
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def ipython_shell():
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue