Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion openevolve/utils/code_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ def parse_full_rewrite(llm_response: str, language: str = "python") -> Optional[
Returns:
Extracted code or None if not found
"""
code_block_pattern = r"```" + language + r"\n(.*?)```"
code_block_pattern = r"```" + re.escape(language) + r"\r?\n(.*?)```"
matches = re.findall(code_block_pattern, llm_response, re.DOTALL)

if matches:
Expand Down
21 changes: 21 additions & 0 deletions tests/test_code_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,33 @@
apply_diff,
extract_diffs,
format_diff_summary,
parse_full_rewrite,
)


class TestCodeUtils(unittest.TestCase):
"""Tests for code utilities"""

def test_parse_full_rewrite_line_endings(self):
for newline in ("\n", "\r\n"):
with self.subTest(newline=repr(newline)):
code = f"def solve():{newline} return 42"
response = f"Updated program:{newline}```python{newline}{code}{newline}```"
result = parse_full_rewrite(response)
self.assertEqual(result, code)
namespace = {}
exec(result, namespace)
self.assertEqual(namespace["solve"](), 42)

def test_parse_full_rewrite_literal_language(self):
response = "```c\nint wrong;\n```\n```c++\nint correct;\n```"
self.assertEqual(parse_full_rewrite(response, "c++"), "int correct;")

def test_parse_full_rewrite_fallbacks(self):
for response in ("```\nx = 1\n```", "x = 1"):
with self.subTest(response=response):
self.assertEqual(parse_full_rewrite(response), "x = 1")

def test_extract_diffs(self):
"""Test extracting diffs from a response"""
diff_text = """
Expand Down