Merge PR #2513: fix: pick the JSON fence when a code snippet fence comes first

Prefer explicit JSON fences over unlabeled examples, ignore other language fences, and cover both precedence and embedded JSON preservation.
This commit is contained in:
Bingxi Zhao (Frank)
2026-11-14 23:07:03 +08:00
2 changed files with 35 additions and 4 deletions

View File

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

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```",
@@ -222,3 +233,13 @@ class TestParseJsonResponseThinkTags:
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}
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}