fix(utils): return the longest decodable JSON value, not the first (#692)

The raw_decode scan added for trailing brace-prose returned the first
decodable value in the response. DeepSeek-style reasoning preludes often
embed a small schema example (e.g. {"chapters": []}) before the real
payload, so the example shadowed the actual object and BookEngine's
SpineAgent fell back to a single Overview chapter. Scan every top-level
candidate and keep the longest decode instead.
This commit is contained in:
Bingxi Zhao (Frank)
2026-07-24 17:39:00 +08:00
parent 308a0606f9
commit 34ca1cb27c
2 changed files with 69 additions and 9 deletions

View File

@@ -31,6 +31,38 @@ logger = logging.getLogger(__name__)
_UNSET = object()
def _decode_longest_json_value(text: str) -> Any:
"""Return the longest top-level JSON value decodable from *text*.
LLM responses may surround the payload with prose on either side, and that
prose can itself contain small valid JSON fragments (e.g. schema examples
in a reasoning prelude — issues #673/#692). Decoding every candidate and
keeping the longest one picks the actual payload over such fragments.
Returns ``_UNSET`` when nothing decodes.
"""
decoder = json.JSONDecoder()
best: Any = _UNSET
best_length = 0
pos = 0
while True:
starts = [i for i in (text.find("{", pos), text.find("[", pos)) if i != -1]
if not starts:
return best
start = min(starts)
try:
parsed, consumed = decoder.raw_decode(text[start:])
except json.JSONDecodeError as err:
# Resume past the failure point: an opener inside the failed span
# could only yield a fragment of it, and repair handles those.
pos = start + max(1, err.pos)
continue
except RecursionError:
return best
if consumed > best_length:
best, best_length = parsed, consumed
pos = start + consumed
def parse_json_response(
response: str,
logger_instance: Any = None,
@@ -116,16 +148,14 @@ def parse_json_response(
except (json.JSONDecodeError, TypeError):
extracted_response = cleaned
# Prefer raw_decode before repair so trailing brace-prose cannot become a wrapping array.
# Prefer raw_decode before repair so brace-bearing prose around the payload
# cannot corrupt it (json-repair would wrap payload + trailing prose into
# an array). The longest decodable value wins, so a schema example inside
# a reasoning prelude never shadows the real payload behind it (#692).
if isinstance(extracted_response, str):
stripped = extracted_response.lstrip()
for idx, ch in enumerate(stripped):
if ch in "{[":
try:
parsed, _end = json.JSONDecoder().raw_decode(stripped[idx:])
return parsed
except json.JSONDecodeError:
break
decoded = _decode_longest_json_value(extracted_response)
if decoded is not _UNSET:
return decoded
# Strategy 2: Try json-repair if available
if repair_json is None:

View File

@@ -130,6 +130,36 @@ class TestParseJsonResponseTrailingProse:
assert result == [{"id": 1}, {"id": 2}]
class TestParseJsonResponseLeadingProse:
"""Untagged reasoning preludes with JSON fragments inside (issue #692)."""
def test_leading_prose_with_brace_example_keeps_payload(self) -> None:
raw = (
'The output format is {"chapters": []} so I will fill it in.\n'
'{"chapters":[{"title":"C1"},{"title":"C2"},{"title":"C3"}]}'
)
result = parse_json_response(raw, fallback=None)
assert result == {"chapters": [{"title": "C1"}, {"title": "C2"}, {"title": "C3"}]}
def test_two_concatenated_objects_longest_wins(self) -> None:
raw = '{"plan": "six chapters"}\n{"chapters":[{"title":"C1"},{"title":"C2"}]}'
result = parse_json_response(raw, fallback=None)
assert result == {"chapters": [{"title": "C1"}, {"title": "C2"}]}
def test_prose_on_both_sides_keeps_payload(self) -> None:
raw = (
'Schema: {"chapters": []}.\n'
'{"chapters":[{"title":"C1"}]}\n'
"Note: each entry follows {title} form."
)
result = parse_json_response(raw, fallback=None)
assert result == {"chapters": [{"title": "C1"}]}
def test_single_small_object_still_returned(self) -> None:
raw = 'Prefix prose {"only": 1} suffix prose'
assert parse_json_response(raw, fallback=None) == {"only": 1}
# ---------------------------------------------------------------------------
# parse_json_response — <think> reasoning tags (issue #673)
# ---------------------------------------------------------------------------