fix(json_parser): strip <think> reasoning tags before parsing (#675)

Reasoning models (Qwen, DeepSeek, etc.) emit chain-of-thought inside
<think>...</think> 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 <think> blocks only on the direct-parse failure path, so a valid
JSON payload whose string values legitimately contain the substring
'<think>' is preserved exactly. Also drop an unclosed leading <think>
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>
This commit is contained in:
Cyriellewu
2026-07-24 16:04:42 +08:00
committed by GitHub
parent ebcac74b8f
commit b020686ced
2 changed files with 88 additions and 1 deletions

View File

@@ -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 <think> stripping so a valid
# JSON payload whose string values legitimately contain "<think>" 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 <think> 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 "<think" in extracted_response.lower():
cleaned = re.sub(
r"<think\b[^>]*>.*?</think>",
"",
extracted_response,
flags=re.DOTALL | re.IGNORECASE,
)
# Also drop an unclosed leading <think> prelude up to the first opener.
cleaned = re.sub(
r"^\s*<think\b[^>]*>.*?(?=[{\[])",
"",
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 <think> 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()

View File

@@ -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 — <think> reasoning tags (issue #673)
# ---------------------------------------------------------------------------
class TestParseJsonResponseThinkTags:
def test_think_block_before_json(self) -> None:
response = (
"<think>\n1. Analyze user intent...\n2. Determine target audience...\n</think>\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 = (
'<think>maybe output {"draft": true} or [a, b]</think>\n'
'{"title":"Real","description":"D"}'
)
assert parse_json_response(response) == {"title": "Real", "description": "D"}
def test_think_block_with_markdown_fence(self) -> None:
response = '<think>reasoning here</think>\n```json\n{"answer": 42}\n```'
assert parse_json_response(response) == {"answer": 42}
def test_think_tag_case_insensitive(self) -> None:
response = '<THINK>step by step</THINK>{"ok": true}'
assert parse_json_response(response) == {"ok": True}
def test_only_think_block_returns_fallback(self) -> None:
response = "<think>just reasoning, no payload</think>"
assert parse_json_response(response) == {}
assert parse_json_response(response, fallback=None) is None
def test_multiple_think_blocks_stripped(self) -> None:
response = '<think>one</think>{"a":1}<think>two {b}</think>'
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 <think> must not be altered."""
response = '{"x":"literal <think>keep</think> value"}'
assert parse_json_response(response, fallback=None) == {
"x": "literal <think>keep</think> value"
}
def test_unclosed_think_prelude_without_braces(self) -> None:
response = '<think>reasoning here, no JSON yet\n{"real":1}'
assert parse_json_response(response, fallback=None) == {"real": 1}