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
3 changes: 3 additions & 0 deletions metagpt/utils/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,9 @@ def parse_code(cls, text: str, lang: str = "", block: Optional[str] = None) -> s
logger.error(text)
# raise Exception
return text # just assume original text is code
# Strip LLM-injected filename header (e.g., "## quickSort.js") from code blocks.
# The LLM sometimes echoes the filename marker inside the code block instead of outside.
code = re.sub(r'^##\s+\S+\.\w+[ \t]*\n+', '', code)
return code

@classmethod
Expand Down
14 changes: 14 additions & 0 deletions tests/metagpt/utils/test_code_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,20 @@ def test_parse_file_list(self, parser, text):
print(result)
assert "game.py" in result

def test_parse_code_strips_filename_header(self, parser):
"""LLM sometimes echoes the filename marker inside the code block instead of outside it."""
text = "```python\n## sort.py\n\ndef sort(arr):\n return sorted(arr)\n```"
result = parser.parse_code(block="", text=text, lang="python")
assert not result.startswith("##"), "filename header should be stripped from extracted code"
assert "def sort" in result

def test_parse_code_strips_filename_header_no_blank_line(self, parser):
"""Filename header immediately followed by code with no blank line."""
text = "```javascript\n## quickSort.js\nfunction quickSort(arr) { return arr; }\n```"
result = parser.parse_code(block="", text=text, lang="javascript")
assert not result.startswith("##"), "filename header should be stripped"
assert "function quickSort" in result


if __name__ == "__main__":
t = TestCodeParser()
Expand Down
Loading