Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions packages/core/src/infrastructure/ai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<{
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/modules/opportunities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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.',
Expand Down
9 changes: 2 additions & 7 deletions packages/core/src/modules/resume-reviews.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
Loading