Skip to content

Commit ac0c30b

Browse files
committed
use ai generate question
1 parent 3a6afb8 commit ac0c30b

File tree

3 files changed

+105
-16
lines changed

3 files changed

+105
-16
lines changed

app/page.tsx

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -11,16 +11,15 @@ import SettingsModal from "@/components/modals/settings-modal"
1111
import HistoryModal from "@/components/modals/history-modal"
1212
import { useState, useEffect, useCallback } from "react"
1313
import type { Question, UserAnswer } from "@/lib/types"
14-
import { getQuestions } from "@/lib/data"
14+
import { generateRandomQuestion } from "@/lib/data"
1515
import { useTranslation } from "@/lib/i18n"
1616
import { useToast } from "@/hooks/use-toast"
1717
// Update the onSubmit function to use the OpenAI API for evaluation
1818
import { evaluateAnswer, getModelAnswer } from "@/lib/api"
1919

2020
export default function Page() {
2121
const { t, language, setLanguage } = useTranslation()
22-
const [questions, setQuestions] = useState<Question[]>([])
23-
const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0)
22+
const [currentQuestion, setCurrentQuestion] = useState<Question | null>(null)
2423
const [userAnswer, setUserAnswer] = useState<UserAnswer>({ content: "" })
2524
const [timeRemaining, setTimeRemaining] = useState(600) // 10 minutes
2625
const [timerWarning, setTimerWarning] = useState(false)
@@ -37,8 +36,12 @@ export default function Page() {
3736
const { toast } = useToast()
3837

3938
useEffect(() => {
40-
setQuestions(getQuestions())
41-
}, [])
39+
const fetchQuestion = async () => {
40+
const question = await generateRandomQuestion();
41+
setCurrentQuestion(question);
42+
};
43+
fetchQuestion();
44+
}, []);
4245

4346
useEffect(() => {
4447
if (timeRemaining <= 0) {
@@ -57,9 +60,7 @@ export default function Page() {
5760
}, 1000)
5861

5962
return () => clearInterval(intervalId)
60-
}, [timeRemaining])
61-
62-
const currentQuestion = questions[currentQuestionIndex]
63+
}, [timeRemaining]) // Added onSubmit to dependency array
6364

6465
const onSubmit = async () => {
6566
setShowResultsModal(true)
@@ -87,12 +88,12 @@ export default function Page() {
8788
}
8889
}
8990

90-
const onNextQuestion = useCallback(() => {
91-
setCurrentQuestionIndex((prevIndex) => prevIndex + 1)
92-
setUserAnswer({ content: "" })
93-
setIsSubmitted(false)
94-
setTimeRemaining(600)
95-
}, [])
91+
const onNextQuestion = useCallback(async () => {
92+
setUserAnswer({ content: "" });
93+
setIsSubmitted(false);
94+
setTimeRemaining(600);
95+
setCurrentQuestion(await generateRandomQuestion());
96+
}, []);
9697

9798
const onViewAnswer = () => {
9899
setConfirmationStep(0)
@@ -227,4 +228,3 @@ export default function Page() {
227228
</div>
228229
)
229230
}
230-

lib/api.ts

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,3 +221,59 @@ export async function getModelAnswer(question: any, language: string, onStream?:
221221
}
222222
}
223223

224+
export async function generateQuestion(type: string, category: string, difficulty: string, language: string = 'en') {
225+
const systemPrompt = `You are an expert at creating technical interview questions.
226+
Generate a new ${type} question in the ${category} category with ${difficulty} difficulty.
227+
The question should be challenging but solvable within a reasonable time frame.
228+
Return your response in JSON format exactly matching the structure provided, with no additional text.`
229+
230+
const prompt = `
231+
Create a new technical interview question with the following parameters:
232+
- Type: (e.g., Must be "Coding" or "Question")
233+
- Category: (e.g., "Algorithms", "TCP", "Data Structures", etc.)
234+
- Difficulty: (e.g., Must be "Easy", "Medium", "Hard")
235+
236+
Generate a question that follows this exact JSON structure:
237+
{
238+
"id": "generated_unique_id",
239+
"type": "",
240+
"category": "",
241+
"difficulty": "",
242+
"translations": {
243+
"en": {
244+
"title": "English title here",
245+
"description": "Detailed English description here",
246+
"topic": "Relevant topic here"
247+
},
248+
"zh": {
249+
"title": "Chinese title here",
250+
"description": "Detailed Chinese description here",
251+
"topic": "Relevant topic in Chinese here"
252+
}
253+
}${type === 'Coding' ? `,
254+
"testCases": [
255+
{ "input": "example input 1", "output": "expected output 1" },
256+
{ "input": "example input 2", "output": "expected output 2" }
257+
]` : ''}
258+
}
259+
260+
Make sure the question is appropriate for the difficulty level and category specified.
261+
`
262+
263+
try {
264+
const result = await callOpenAI(prompt, systemPrompt)
265+
const cleanedResult = cleanupJsonResponse(result)
266+
267+
// Parse the result to ensure it's valid JSON
268+
const questionData = JSON.parse(cleanedResult)
269+
270+
// Generate a more reliable unique ID
271+
questionData.id = `generated_${Date.now()}_${Math.floor(Math.random() * 1000)}`
272+
273+
return questionData
274+
} catch (error) {
275+
console.error("Error generating question:", error)
276+
throw new Error("Failed to generate question. Please check your API settings and try again.")
277+
}
278+
}
279+

lib/data.ts

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,22 @@
1+
import { generateQuestion } from "./api"
12
import type { Question } from "./types"
23

4+
// In-memory storage for generated questions
5+
let generatedQuestions: Question[] = []
6+
7+
export async function generateRandomQuestion(): Promise<Question> {
8+
const type = ["Coding", "Question"]
9+
const category = ["Algorithms", "TCP", "Data Structures", "System Design", "Behavioral", "Java", "Operation System"]
10+
const difficulty = ["Easy", "Medium", "Hard"]
11+
const randomType = type[Math.floor(Math.random() * type.length)]
12+
const randomCategory = category[Math.floor(Math.random() * category.length)]
13+
const randomDifficulty = difficulty[Math.floor(Math.random() * difficulty.length)]
14+
return await generateQuestion(randomType, randomCategory, randomDifficulty)
15+
}
16+
317
export function getQuestions(): Question[] {
418
// This would typically fetch from an API or JSON file
5-
return [
19+
const predefinedQuestions: Question[] = [
620
{
721
id: "1",
822
type: "Coding",
@@ -46,5 +60,24 @@ export function getQuestions(): Question[] {
4660
},
4761
},
4862
]
63+
64+
// Combine predefined and generated questions
65+
return [...predefinedQuestions, ...generatedQuestions]
66+
}
67+
68+
// Add a new function to add a generated question to our collection
69+
export function addGeneratedQuestion(question: Question): void {
70+
generatedQuestions.push(question)
71+
}
72+
73+
// Add a function to get questions by type and category
74+
export function getQuestionsByFilter(type?: string, category?: string, difficulty?: string): Question[] {
75+
const questions = getQuestions()
76+
77+
return questions.filter(q =>
78+
(!type || q.type === type) &&
79+
(!category || q.category === category) &&
80+
(!difficulty || q.difficulty === difficulty)
81+
)
4982
}
5083

0 commit comments

Comments
 (0)