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
This commit is contained in:
Maurice
2026-12-03 11:00:59 +01:00
parent ca201ab4d0
commit 75020dd2df
2 changed files with 56 additions and 6 deletions
+37 -6
View File
@@ -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.
*
@@ -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 = `[
{