fix: pick the JSON fence when a code snippet fence comes first

parse_json_response extracted only the first fenced block, so a reply
that shows a code snippet (for example a ```python block) before the
fenced JSON payload lost the payload: it returned a list literal from the
snippet or the fallback. Prefer the first fenced block that holds a JSON
object or array, and keep the first block otherwise.
This commit is contained in:
Mohammad Hijjawi
2026-11-07 10:41:08 +00:00
parent 60fb3bdfdd
commit e27aa512df
2 changed files with 22 additions and 4 deletions

View File

@@ -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 <think> stripping.

View File

@@ -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```",