generated from nhcarrigan/template
fix: strip markdown fences and extract JSON from AI response
This commit is contained in:
@@ -84,9 +84,23 @@ const generateTicket = async(
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
// Strip markdown code fences the model may wrap the JSON in.
|
||||
const stripped = result.replaceAll(/```(?:json)?\s*/gu, "").trim();
|
||||
// Extract the outermost JSON object in case of surrounding prose.
|
||||
const jsonMatch = /\{[\s\S]*\}/u.exec(stripped);
|
||||
if (jsonMatch === null) {
|
||||
await logger.error(
|
||||
"generateTicket",
|
||||
new Error(`Non-JSON AI response: ${result.slice(0, 200)}`),
|
||||
);
|
||||
return null;
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Parsing known AI JSON output.
|
||||
return JSON.parse(result) as GeneratedTicket;
|
||||
} catch {
|
||||
return JSON.parse(jsonMatch[0]) as GeneratedTicket;
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
await logger.error("generateTicket", error);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user