From 75020dd2df5aa6793d5847b51480a32e15a4e420 Mon Sep 17 00:00:00 2001 From: Maurice Date: Thu, 3 Dec 2026 11:00:59 +0100 Subject: [PATCH] fix(llm-parse): read fenced booking JSON surrounded by prose Some booking models return a complete JSON code block followed by an explanation. Read the fenced payload when parsing the full answer fails, and leave the existing JSON and JSON5 behavior intact. Closes #3307 --- server/src/nest/llm-parse/lenient-json.ts | 43 ++++++++++++++++--- .../unit/nest/llm-parse/lenient-json.test.ts | 19 ++++++++ 2 files changed, 56 insertions(+), 6 deletions(-) diff --git a/server/src/nest/llm-parse/lenient-json.ts b/server/src/nest/llm-parse/lenient-json.ts index 83f05d3f5..d3429de11 100644 --- a/server/src/nest/llm-parse/lenient-json.ts +++ b/server/src/nest/llm-parse/lenient-json.ts @@ -13,27 +13,58 @@ import JSON5 from 'json5'; * the UI showed nothing. We try strict JSON first (the common, cheapest path) and fall * back to JSON5, which accepts exactly that relaxed superset. Returns `null` on failure. * - * The leading/trailing code-fence strip stays here because some models still wrap the - * payload in a ```json fence even when asked for raw JSON. + * Some models wrap the payload in a JSON code fence, sometimes with prose around it. */ export function parseLenientJson(content: string | undefined | null): unknown { if (!content) return null; - const stripped = content - .trim() + const text = content.trim(); + const stripped = text .replace(/^```(?:json)?/i, '') .replace(/```$/, '') .trim(); try { - return trimKeys(JSON.parse(stripped)); + return trimKeys(readJson(stripped) ?? readFencedJson(text)); + } catch { + return null; + } +} + +function readJson(text: string): unknown { + try { + return JSON.parse(text); } catch { try { - return trimKeys(JSON5.parse(stripped)); + return JSON5.parse(text); } catch { return null; } } } +function readFencedJson(text: string): unknown { + let open: { length: number; bodyStart: number; isJson: boolean } | undefined; + for (const match of text.matchAll(/^[ \t]*(`{3,})([^\r\n]*)$/gm)) { + const [, marker, suffix] = match; + const info = suffix.trim(); + if (!open) { + if (info.includes('`')) continue; + open = { + length: marker.length, + bodyStart: match.index + match[0].length, + isJson: /^(?:json5?)?$/i.test(info), + }; + } else if (marker.length >= open.length) { + // Check the whole payload before accepting a closing fence with an inline note. + if (open.isJson && (!info || /^[ \t]/.test(suffix))) { + const value = readJson(text.slice(open.bodyStart, match.index).trim()); + if (value !== null) return value; + } + if (!info) open = undefined; + } + } + return null; +} + /** * The value with whitespace trimmed off every object key, at any depth. * diff --git a/server/tests/unit/nest/llm-parse/lenient-json.test.ts b/server/tests/unit/nest/llm-parse/lenient-json.test.ts index a4954ef1e..433cf0c91 100644 --- a/server/tests/unit/nest/llm-parse/lenient-json.test.ts +++ b/server/tests/unit/nest/llm-parse/lenient-json.test.ts @@ -13,6 +13,25 @@ describe('parseLenientJson', () => { ]); }); + it('reads fenced booking JSON followed by explanatory text', () => { + const booking = { + bookings: [ + { kind: 'new_booking', reservations: [{ '@type': 'LodgingReservation', reservationNumber: 'TREK42' }] }, + ], + }; + const fence = '```'; + const response = [fence + 'json', JSON.stringify(booking), fence, 'I found one booking.'].join('\n'); + expect(parseLenientJson(response)).toEqual(booking); + expect(parseLenientJson('Extracted from the email:\r\n' + response.replaceAll('\n', '\r\n'))).toEqual(booking); + expect(parseLenientJson(response.replace(`${fence}\nI found`, `${fence} I found`))).toEqual(booking); + expect( + parseLenientJson(response.replace(`${fence}\nI found one booking.`, `${fence} I found \`TREK42\`.`)), + ).toEqual(booking); + const unrelatedCode = [fence + 'text', JSON.stringify({ example: true }), fence].join('\n'); + expect(parseLenientJson(`${unrelatedCode}\n\n${response}`)).toEqual(booking); + expect(parseLenientJson(`${unrelatedCode}\n\nI found no bookings.`)).toBeNull(); + }); + it('parses single-quoted, unquoted-key, trailing-comma output (Gemini, #1638)', () => { const gemini = `[ {