Skip to content

Instantly share code, notes, and snippets.

@HarisChandio
Last active June 13, 2024 08:54
Show Gist options
  • Save HarisChandio/bf771ef4458a11d1202b23f6c9876d78 to your computer and use it in GitHub Desktop.
Save HarisChandio/bf771ef4458a11d1202b23f6c9876d78 to your computer and use it in GitHub Desktop.
Generate Coding Questions using GPT
// Required parameters for this function:
// @param {string} topic - The topic of the coding questions (e.g., array, linked list, etc.)
// @param {string} level - The difficulty level of the questions (e.g., easy, medium, hard)
import dotenv from "dotenv";
import OpenAI from "openai";
dotenv.config();
const openai = new OpenAI(process.env.OPENAI_API_KEY);
export async function generateCodingTestQuestions(topic, difficultyLevel) {
const prompt = `
Scrape 5 coding questions from LeetCode based on the specified difficulty level. Format the output as a JSON object with the following fields:
**Topic:** ${topic}
**Difficulty:** ${
difficultyLevel.charAt(0).toUpperCase() + difficultyLevel.slice(1)
}
Each JSON should include:
*title: A brief, descriptive name for the question.
*problem_statement: A detailed description of the coding problem, similar to LeetCode's format, including an example.
*expected_input: An example of the input data for the problem.
*expected_output: The expected output corresponding to the provided input.
**Example:**
{
"title":"Two Sum",
"problem_statement": "Write a function that reverse an string",
"expected_input": "\\"Hello, world!\\"",
"expected_output": "!dlrow ,olleH"
}
`;
try {
const res = await openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages: [
{
role: "user",
content: prompt,
},
],
max_tokens: 1500,
n: 1,
});
const message = res.choices[0].message.content;
console.log(message);
//parsing the questions
const questions = parseQuestions(message);
return questions;
} catch (error) {
throw new Error(`Error while generating questions: ${error.message}`);
}
}
function parseQuestions(response) {
const questions = [];
const regex = /{[^}]*}/g;
let match;
while ((match = regex.exec(response)) !== null) {
try {
const questionJson = JSON.parse(match[0]);
if (
[
"title",
"problem_statement",
"expected_input",
"expected_output",
].every((key) => key in questionJson)
) {
questions.push(questionJson);
}
} catch (error) {
console.error("Failed to parse the response as valid JSON.", error);
}
}
if (questions.length === 0) {
throw new Error("No valid questions found in the AI response.");
}
return questions;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment