From b020686cedbc5d979fc8b0ec68896ac07e722dd2 Mon Sep 17 00:00:00 2001 From: Cyriellewu <145443827+Cyriellewu@users.noreply.github.com> Date: Fri, 24 Jul 2026 16:04:42 +0800 Subject: [PATCH] fix(json_parser): strip reasoning tags before parsing (#675) Reasoning models (Qwen, DeepSeek, etc.) emit chain-of-thought inside ... blocks before the JSON payload. parse_json_response() did not account for this: a brace inside the reasoning was picked up by the raw_decode scan and returned instead of the real object, silently yielding wrong or empty data (e.g. empty BookEngine proposal fields). Strip blocks only on the direct-parse failure path, so a valid JSON payload whose string values legitimately contain the substring '' is preserved exactly. Also drop an unclosed leading prelude up to the first JSON opener, and return the fallback when the response is reasoning-only with no payload. Fixes #673 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- deeptutor/utils/json_parser.py | 34 +++++++++++++++++++- tests/utils/test_json_parser.py | 55 +++++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+), 1 deletion(-) diff --git a/deeptutor/utils/json_parser.py b/deeptutor/utils/json_parser.py index 8049040b7..8343b7818 100644 --- a/deeptutor/utils/json_parser.py +++ b/deeptutor/utils/json_parser.py @@ -78,12 +78,44 @@ def parse_json_response( extracted_response = json_match.group(1).strip() log.debug("Extracted JSON from markdown code block") - # Strategy 1: Direct parsing + # Strategy 1: Direct parsing. Done before any stripping so a valid + # JSON payload whose string values legitimately contain "" is + # preserved exactly. try: return json.loads(extracted_response) except (json.JSONDecodeError, TypeError) as parse_error: log.debug(f"Direct JSON parse failed: {parse_error}") + # Strategy 1b: strip chain-of-thought reasoning that models like + # Qwen/DeepSeek emit before the JSON payload, then retry. Only reached once + # direct parsing has failed, so it never rewrites already-valid JSON. Left + # in place, a brace inside the reasoning is picked up by the raw_decode scan + # below and returned instead of the real object (see issue #673). + if "]*>.*?", + "", + extracted_response, + flags=re.DOTALL | re.IGNORECASE, + ) + # Also drop an unclosed leading prelude up to the first opener. + cleaned = re.sub( + r"^\s*]*>.*?(?=[{\[])", + "", + cleaned, + count=1, + flags=re.DOTALL | re.IGNORECASE, + ) + cleaned = cleaned.strip() + if cleaned != extracted_response.strip(): + if not cleaned: + log.warning("LLM response contained only reasoning, no JSON payload") + return fallback + try: + return json.loads(cleaned) + except (json.JSONDecodeError, TypeError): + extracted_response = cleaned + # Prefer raw_decode before repair so trailing brace-prose cannot become a wrapping array. if isinstance(extracted_response, str): stripped = extracted_response.lstrip() diff --git a/tests/utils/test_json_parser.py b/tests/utils/test_json_parser.py index 49def6eb2..7a78fbbbc 100644 --- a/tests/utils/test_json_parser.py +++ b/tests/utils/test_json_parser.py @@ -128,3 +128,58 @@ class TestParseJsonResponseTrailingProse: raw = '[{"id":1},{"id":2}] trailing {x}' result = parse_json_response(raw, fallback=None) assert result == [{"id": 1}, {"id": 2}] + + +# --------------------------------------------------------------------------- +# parse_json_response — reasoning tags (issue #673) +# --------------------------------------------------------------------------- + + +class TestParseJsonResponseThinkTags: + def test_think_block_before_json(self) -> None: + response = ( + "\n1. Analyze user intent...\n2. Determine target audience...\n\n" + '{"title":"T","description":"D","scope":"S","rationale":"R"}' + ) + assert parse_json_response(response) == { + "title": "T", + "description": "D", + "scope": "S", + "rationale": "R", + } + + def test_think_block_containing_braces_does_not_leak(self) -> None: + """Braces inside the reasoning must not be returned instead of the real object.""" + response = ( + 'maybe output {"draft": true} or [a, b]\n' + '{"title":"Real","description":"D"}' + ) + assert parse_json_response(response) == {"title": "Real", "description": "D"} + + def test_think_block_with_markdown_fence(self) -> None: + response = 'reasoning here\n```json\n{"answer": 42}\n```' + assert parse_json_response(response) == {"answer": 42} + + def test_think_tag_case_insensitive(self) -> None: + response = 'step by step{"ok": true}' + assert parse_json_response(response) == {"ok": True} + + def test_only_think_block_returns_fallback(self) -> None: + response = "just reasoning, no payload" + assert parse_json_response(response) == {} + assert parse_json_response(response, fallback=None) is None + + def test_multiple_think_blocks_stripped(self) -> None: + response = 'one{"a":1}two {b}' + assert parse_json_response(response) == {"a": 1} + + def test_literal_think_in_valid_json_preserved(self) -> None: + """A valid JSON string value that literally contains must not be altered.""" + response = '{"x":"literal keep value"}' + assert parse_json_response(response, fallback=None) == { + "x": "literal keep value" + } + + 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}