Skip to content

Commit 21a85a0

Browse files
author
Miriad
committed
fix: strip markdown code fences from Gemini JSON responses
Gemini 2.5-flash wraps JSON in ```json code fences even when asked not to. Added stripCodeFences() helper to lib/gemini.ts and applied it in the ingest cron parser.
1 parent 8aa8d16 commit 21a85a0

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

app/api/cron/ingest/route.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ export const fetchCache = "force-no-store";
22

33
import type { NextRequest } from "next/server";
44

5-
import { generateWithGemini } from "@/lib/gemini";
5+
import { generateWithGemini, stripCodeFences } from "@/lib/gemini";
66
import { writeClient } from "@/lib/sanity-write-client";
77

88
// ---------------------------------------------------------------------------
@@ -333,7 +333,9 @@ export async function GET(request: NextRequest) {
333333

334334
let script: GeneratedScript;
335335
try {
336-
script = JSON.parse(rawResponse) as GeneratedScript;
336+
// Strip markdown code fences if present (Gemini sometimes wraps JSON in ```json ... ```)
337+
const cleaned = stripCodeFences(rawResponse);
338+
script = JSON.parse(cleaned) as GeneratedScript;
337339
} catch (parseErr) {
338340
console.error(
339341
"[CRON/ingest] Failed to parse Gemini response:",

lib/gemini.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,11 @@ export async function generateWithGemini(
2020
const response = result.response;
2121
return response.text();
2222
}
23+
24+
/**
25+
* Strip markdown code fences from a string.
26+
* Gemini often wraps JSON responses in ```json ... ``` blocks.
27+
*/
28+
export function stripCodeFences(text: string): string {
29+
return text.replace(/^```(?:\w+)?\s*\n?/i, '').replace(/\n?```\s*$/i, '').trim();
30+
}

0 commit comments

Comments
 (0)