mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 09:54:14 +00:00
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:
@@ -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.
|
||||
*
|
||||
|
||||
Reference in New Issue
Block a user