diff --git a/openevolve/utils/code_utils.py b/openevolve/utils/code_utils.py index f4823fe34..5ef3f7cf0 100644 --- a/openevolve/utils/code_utils.py +++ b/openevolve/utils/code_utils.py @@ -243,8 +243,8 @@ def parse_full_rewrite(llm_response: str, language: str = "python") -> Optional[ if matches: return matches[0].strip() - # Fallback to any code block - code_block_pattern = r"```(.*?)```" + # Fallback to any code block, without its language tag if it has one + code_block_pattern = r"```(?:[^\s`]*[ \t]*\r?\n)?(.*?)```" matches = re.findall(code_block_pattern, llm_response, re.DOTALL) if matches: diff --git a/tests/test_code_utils.py b/tests/test_code_utils.py index d0a93a174..d1d08f7a9 100644 --- a/tests/test_code_utils.py +++ b/tests/test_code_utils.py @@ -51,6 +51,15 @@ def test_parse_full_rewrite_fallbacks(self): with self.subTest(response=response): self.assertEqual(parse_full_rewrite(response), "x = 1") + def test_parse_full_rewrite_other_language_tag(self): + for tag in ("py", "python3", "Python", "c++"): + for newline in ("\n", "\r\n"): + with self.subTest(tag=tag, newline=repr(newline)): + response = f"```{tag}{newline}x = 1{newline}```" + self.assertEqual(parse_full_rewrite(response), "x = 1") + response = "```js\nconsole.log(1)\n```" + self.assertEqual(parse_full_rewrite(response, "javascript"), "console.log(1)") + def test_extract_diffs(self): """Test extracting diffs from a response""" diff_text = """