diff --git a/deeptutor/utils/json_parser.py b/deeptutor/utils/json_parser.py index 06f43a183..ebbbc7abe 100644 --- a/deeptutor/utils/json_parser.py +++ b/deeptutor/utils/json_parser.py @@ -107,13 +107,23 @@ 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. + # Explicit JSON fences take precedence over unlabeled examples. Consume + # every fence so a closing delimiter cannot masquerade as another opener. 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() + fence = re.compile(r"```([A-Za-z0-9_-]*)[ \t]*\n?(.*?)```", re.DOTALL) + matches = list(fence.finditer(response)) + blocks = [m[2].strip() for m in matches if m[1].lower() == "json"] + if not blocks: + blocks = [m[2].strip() for m in matches if not m[1]] + if blocks: + extracted_response = next( + (block for block in blocks if block.startswith(("{", "["))), blocks[0] + ) log.debug("Extracted JSON from markdown code block") + elif matches: + # Other languages are examples, not candidate response payloads. + extracted_response = fence.sub("", response) # Parse an extracted fence before any stripping. try: diff --git a/tests/utils/test_json_parser.py b/tests/utils/test_json_parser.py index 392a81add..1a5f3e6c1 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```", @@ -222,3 +233,13 @@ class TestParseJsonResponseThinkTags: def test_unclosed_think_prelude_without_braces(self) -> None: response = 'reasoning here, no JSON yet\n{"real":1}' assert parse_json_response(response, fallback=None) == {"real": 1} + + +def test_explicit_json_fence_wins_over_unlabeled_example() -> None: + response = '```\n{"example": "longer example value"}\n```\n```JSON\n{"answer": 2}\n```' + assert parse_json_response(response) == {"answer": 2} + + +def test_other_language_fences_are_not_json_candidates() -> None: + response = '```javascript\n{"example": "longer example value"}\n```\n{"answer": 2}' + assert parse_json_response(response) == {"answer": 2}