diff --git a/deeptutor/utils/json_parser.py b/deeptutor/utils/json_parser.py index 06f43a183..9c92078b2 100644 --- a/deeptutor/utils/json_parser.py +++ b/deeptutor/utils/json_parser.py @@ -107,12 +107,19 @@ def parse_json_response( except (json.JSONDecodeError, TypeError) as parse_error: log.debug(f"Complete response JSON parse failed: {parse_error}") - # Extract from markdown code blocks if present. + # Extract from markdown code blocks if present. Prefer the first block that + # holds a JSON object or array: a reply can show a code snippet (e.g. a + # ```python block) before the fenced payload. extracted_response = response if "```" in response: - json_match = re.search(r"```(?:json)?\s*\n?(.*?)```", response, re.DOTALL) - if json_match: - extracted_response = json_match.group(1).strip() + blocks = [ + match.group(1).strip() + for match in re.finditer(r"```(?:json)?\s*\n?(.*?)```", response, re.DOTALL) + ] + if blocks: + extracted_response = next( + (block for block in blocks if block.startswith(("{", "["))), blocks[0] + ) log.debug("Extracted JSON from markdown code block") # Parse an extracted fence before any stripping. diff --git a/tests/utils/test_json_parser.py b/tests/utils/test_json_parser.py index 392a81add..4de1ff183 100644 --- a/tests/utils/test_json_parser.py +++ b/tests/utils/test_json_parser.py @@ -64,6 +64,17 @@ class TestParseJsonResponseMarkdown: result = parse_json_response(response) assert result == {"a": 1} + def test_code_snippet_block_before_json_block(self) -> None: + response = ( + "The question uses this snippet:\n```python\nprint(len([1, 2]))\n```\n" + 'Here is the result:\n```json\n{"answer": 2}\n```' + ) + assert parse_json_response(response) == {"answer": 2} + + def test_malformed_json_block_after_code_snippet_is_repaired(self) -> None: + response = '```python\nx = 1\n```\n```json\n{"answer": 2,}\n```' + assert parse_json_response(response) == {"answer": 2} + def test_fenced_code_inside_json_string_is_not_extracted(self) -> None: payload = { "content": "Use this example:\n```python\nprint('hello')\n```",