Skip to content

openai: improve result parsing #31

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Dec 2, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
13 changes: 4 additions & 9 deletions src/ext/openai/openai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
import { createLogger } from '@/logger';
import { type EvaluationSummaryInput } from '@/service/EvaluationService';
import { env } from '@/env';
import { parseArray, parseObject } from '@/utils';

const openai = new OpenAI({
apiKey: env.OPENAI_API_KEY,
Expand Down Expand Up @@ -54,7 +55,7 @@ export const requestEvaluation = async (
);
const result = await queryOpenAI(prompt);
logger.info('Application evaluation complete', { result });
return JSON.parse(removeJsonCodeBlocks(result));
return parseObject(result) as EvaluationSummaryInput;
};

export const requestEvaluationQuestions = async (
Expand All @@ -64,11 +65,5 @@ export const requestEvaluationQuestions = async (
const prompt: string = createEvaluationQuestionPrompt(roundMetadata);
const result = await queryOpenAI(prompt);
logger.info('Received evaluation questions from OpenAI', { result });
return JSON.parse(removeJsonCodeBlocks(result)).map(line =>
line.replace(/^\d+\.\s*/, '').trim()
);
};

const removeJsonCodeBlocks = (str: string): string => {
return str.replace(/```json/g, '').replace(/```/g, '');
};
return parseArray(result).map(line => line.replace(/^\d+\.\s*/, '').trim());
};
2 changes: 1 addition & 1 deletion src/ext/openai/prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export const createAiEvaluationPrompt = (
${questionsString}

Your question answers should NOT be 'yes', 'no', or 'uncertain'. Please use always 0 for 'yes', 1 for 'no', and 2 for 'uncertain'.
Please respond with ONLY the following JSON structure and NOTHING else:
Please respond with a valid JSON structure and NOTHING else:
{
"questions": [
{
Expand Down
39 changes: 39 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,42 @@ export async function isPoolManager<T>(
return false;
}
}

export function parseObject(s): object {
const jsonObjPattern = /\{(?:[^{}]*|(?:\{(?:[^{}]*|(?:\{[^{}]*\}))*\}))*\}/g;

// Find all matches for JSON objects
const jsonObjs = s.match(jsonObjPattern) ?? [];

// Parse the matches
return jsonObjs
.map(obj => {
try {
return JSON.parse(obj as string);
} catch (e) {
console.error('Failed to parse JSON object:', obj);
return null;
}
})
.filter(obj => obj !== null)[0];
}

export function parseArray(s): string[] {
// Regular expression to find JSON arrays
const jsonArrayPattern = /\[[^[\]]*\]/g;

// Find all matches for JSON arrays
const jsonArrays = s.match(jsonArrayPattern) ?? [];

// Parse the matches
return jsonArrays
.map(arr => {
try {
return JSON.parse(arr as string);
} catch (e) {
console.error('Failed to parse JSON array:', arr);
return null;
}
})
.filter(arr => arr !== null)[0];
}
Loading