diff --git a/packages/core/src/infrastructure/ai.ts b/packages/core/src/infrastructure/ai.ts index 8ac1415c3..3c307f92b 100644 --- a/packages/core/src/infrastructure/ai.ts +++ b/packages/core/src/infrastructure/ai.ts @@ -264,6 +264,21 @@ export async function getChatCompletion({ return success(message); } +/** + * Removes a Markdown code fence (ie: ```json ... ```) from an AI response. + * Some models add one even when asked for only JSON, which breaks + * `JSON.parse`. Text without a fence is returned trimmed. + * + * @param text - The raw text from the AI response. + * @returns The text without the surrounding code fence. + */ +export function stripCodeFence(text: string): string { + return text + .trim() + .replace(/^```(?:json)?\s*/, '') + .replace(/\s*```$/, ''); +} + // "Rerank Documents" type RerankDocumentsOptions = Partial<{ diff --git a/packages/core/src/modules/opportunities.ts b/packages/core/src/modules/opportunities.ts index cafbd8514..fac58355b 100644 --- a/packages/core/src/modules/opportunities.ts +++ b/packages/core/src/modules/opportunities.ts @@ -9,7 +9,7 @@ import { db } from '@oyster/db'; import { ISO8601Date, nullableField } from '@oyster/types'; import { id } from '@oyster/utils'; -import { getChatCompletion } from '@/infrastructure/ai'; +import { getChatCompletion, stripCodeFence } from '@/infrastructure/ai'; import { job, registerWorker } from '@/infrastructure/bull'; import { type GetBullJobData, @@ -781,7 +781,7 @@ export async function refineOpportunity( let json: JSON; try { - json = JSON.parse(completionResult.data); + json = JSON.parse(stripCodeFence(completionResult.data)); } catch (e) { console.debug( 'Failed to parse JSON from AI response.', diff --git a/packages/core/src/modules/resume-reviews.ts b/packages/core/src/modules/resume-reviews.ts index bea943522..72f366ed0 100644 --- a/packages/core/src/modules/resume-reviews.ts +++ b/packages/core/src/modules/resume-reviews.ts @@ -6,7 +6,7 @@ import { z } from 'zod'; import { db, relativeTime } from '@oyster/db'; import { id } from '@oyster/utils'; -import { getChatCompletion } from '@/infrastructure/ai'; +import { getChatCompletion, stripCodeFence } from '@/infrastructure/ai'; import { job, registerWorker } from '@/infrastructure/bull'; import { type GetBullJobData, @@ -184,12 +184,7 @@ export async function reviewResume({ }); try { - const json = completionResult.data - .trim() - .replace(/^```(?:json)?\s*/, '') - .replace(/\s*```$/, ''); - - const object = JSON.parse(json); + const object = JSON.parse(stripCodeFence(completionResult.data)); const feedback = ResumeFeedback.parse(object); await db