File size: 2,400 Bytes
46827cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import json
from groq import Groq

GROQ_API_KEY = "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"


def generate_quiz(topic, level, num_questions, q_type):
    if q_type != "Mixed":
        type_instruction = "All questions must be type: " + q_type + "."
    else:
        type_instruction = "Mix these types: Multiple Choice, True/False, Fill in the Blank, Short Answer."

    prompt = (
        "Generate " + str(num_questions) + " quiz questions about '" + topic + "' at " + level + " level.\n"
        + type_instruction + "\n\n"
        "Return ONLY a JSON object with key 'questions' (array).\n"
        "Each question needs:\n"
        "  - type: one of 'Multiple Choice', 'True/False', 'Fill in the Blank', 'Short Answer'\n"
        "  - question: the question text (for Fill in the Blank, use ___ for the blank)\n"
        "  - options: 4 strings for MC, ['True','False'] for TF, [] for others\n"
        "  - answer: the correct answer string\n"
        "  - explanation: one sentence explaining why\n\n"
        "JSON only, no markdown, no backticks, no extra text."
    )

    try:
        client = Groq(api_key=GROQ_API_KEY)
        r = client.chat.completions.create(
            model="llama-3.3-70b-versatile",
            messages=[{"role": "user", "content": prompt}],
            max_tokens=1500
        )
        raw = r.choices[0].message.content.strip()
        if raw.startswith("```"):
            raw = raw.split("```", 2)[1]
            if raw.startswith("json"):
                raw = raw[4:]
        data = json.loads(raw.strip())
        return {
            "title": topic.title() + " Quiz",
            "topic": topic.title(),
            "difficulty": level,
            "questions": data["questions"]
        }
    except Exception as e:
        # Fallback single question so app never crashes
        return {
            "title": topic.title() + " Quiz",
            "topic": topic.title(),
            "difficulty": level,
            "questions": [
                {
                    "type": "Short Answer",
                    "question": f"Quiz generation failed ({str(e)}). Please retry.",
                    "options": [],
                    "answer": "retry",
                    "explanation": "An error occurred while generating the quiz."
                }
            ]
        }