Skip to content
Aditya Bhalsod
← AI
AIIntermediate

Parsing and Scoring Gemini Quiz JSON in a Flask Learning App

What happens between Gemini's JSON reply and a learner's score in Quiz System With AI, a Flask app, covering parsing, fallbacks, stored answer keys and plain-code triggers.

  • #flask
  • #gemini
  • #llm
  • #python
Contents
  1. Ask for a shape, and say it twice
  2. Parse defensively, fall back quietly
  3. Generate once, score against the stored copy
  4. Plain code decides when, the model decides what
  5. Where this stops working

Quiz System With AI is a Flask app that collects a learner profile, runs a diagnostic quiz, asks Gemini for an 8-week study plan and then serves a quiz for each module. It uses Flask 3, SQLite through SQLAlchemy by default and the google-genai SDK. The model defaults to gemini-2.0-flash-001 and can be changed with GOOGLE_AI_MODEL.

The prompts are the easy part. This post is about the code between the model's reply and the number a learner sees: how the JSON is parsed, what happens when it is unusable, and which decisions I kept out of the model's hands. It also covers one place where I put that boundary in the wrong spot. The README's roadmap lists tests and better validation around the AI JSON as future work, and the code agrees. This is a small app, not a hardened one.

Ask for a shape, and say it twice

The quiz prompt in google_ai.py spells out the exact JSON shape, and a system instruction repeats that the reply must be JSON only. Quiz calls use a temperature of 0.5, while the learning plan uses 0.7.

Python
prompt = f"""
Generate {count} multiple-choice quiz questions for the topic: {topic}
Difficulty level: {difficulty}

Respond with ONLY a JSON array, no markdown, no code blocks:
[
    {{
        "question": "Question text",
        "options": ["A) Option 1", "B) Option 2", "C) Option 3", "D) Option 4"],
        "correct_answer": "A",
        "explanation": "Why this answer is correct",
        "difficulty": "{difficulty}"
    }}
]
"""

The doubled braces are f-string escapes. The letter convention matters later. The quiz templates submit option[:1], the first character of the chosen option, and scoring is a plain string comparison against correct_answer.

Parse defensively, fall back quietly

The prompt says no code blocks, but the parser strips a Markdown fence anyway, then calls json.loads and checks only that the result is a non-empty list. Anything else is logged and returns None.

Python
def _parse_quiz_questions(self, content: str) -> Optional[List[Dict[str, Any]]]:
    try:
        content = content.strip()
        # ... strip a Markdown code fence if the model added one ...
        questions = json.loads(content)

        if isinstance(questions, list) and len(questions) > 0:
            return questions

    except json.JSONDecodeError as e:
        self.logger.error(f"JSON parsing error for quiz: {e}")
        self.logger.error(f"Content: {content[:500]}")

    return None

None means "use the built-in questions". The diagnostic asks for 12 questions and accepts the AI result only if at least 10 come back, otherwise it uses a hard-coded bank. Each AI call has its own failure path:

CallTemperatureMax tokensWhen it fails
Learning plan0.73000A static default plan
Quiz questions0.52000Caller uses built-in questions
Quiz feedback0.6500Canned text for the score band
Recalculated plan0.73000A fallback with an empty weeks list

The plan prompt asks for "exactly 8 weeks", but the plan parser only checks that learning_plan and weeks exist. If duration_weeks is missing it fills it from len(weeks). So "8-week" is an instruction to the model, not something the code enforces. The default plan is also titled "Default Python Learning Path" whatever the learner's goal is, and generate_path stores it with the model name attached, so nothing marks it as a fallback.

Generate once, score against the stored copy

A model can return different questions every time you ask. The module quiz handles this: it stores the questions in the session when the page loads, scores from that copy and then clears it.

Python
# module_quiz(): generate once and remember
questions = get_module_quiz_questions(module)
session[f'quiz_questions_{module_id}'] = questions

# submit_module_quiz(): score the stored copy
questions = session.get(f'quiz_questions_{module_id}')
for i, question in enumerate(questions):
    user_answer = answers.get(str(i), '')
    correct = user_answer == question['correct_answer']

# submit_diagnostic(): no stored copy, so it asks again
questions = get_diagnostic_questions(career_goal)

Plain code decides when, the model decides what

The adaptive part is mostly ordinary Python. The recalculation service keeps its thresholds in one dictionary.

Python
self.recalculation_triggers = {
    'weekly': 7,  # Review every 7 days
    'modules_completed': 5,  # Review after every 5 modules
    'poor_performance': 3,  # Review after 3 consecutive poor scores (<60%)
    'excellent_performance': 5  # Review after 5 consecutive excellent scores (>90%)
}

should_recalculate checks them in that order against the learner's activity since the latest recommendation and returns a reason string. Only then does the model get involved. Python computes the average, a trend, pace and engagement level, and the prompt asks for a replacement plan. The performance snapshot and the reason are saved in recalculation_metadata next to the new plan.

After a module quiz, the score band (90 or above, 70 or above, below 70) picks a branch and a database query picks the modules to suggest. Gemini adds only a short feedback message. The quiz itself is not adapted per learner: the prompt receives module.difficulty_level, which came from the plan.

The diagnostic reaches the plan only through one line of the prompt. generate_path passes diagnostic.score, which is a count of correct answers, into a template that prints it with a percent sign.

Python
- Assessment Score: {assessment_score}% ({assessment_percentage}/100)

A learner with 7 of 12 correct reaches the model as 7.0% (58.333333333333336/100). The stored skill_level comes from the profile's experience_level, not from the diagnostic.

Where this stops working

Splitting rules from model output fits a small app, because every AI call returns None or a default instead of raising, so pages still render without a key. It stops working wherever a wrong answer has a cost. These are the things I would fix first:

  • Validate each question: four options and a correct_answer in A to D, with one retry before falling back. Today a reply like "A)" marks every answer wrong, and a missing key raises a KeyError at scoring.
  • Store the diagnostic questions the way the module quiz does.
  • Replace tag strings with real columns. Week, order and recommendation are encoded in a comma-separated tags column and found with LIKE, so %recommendation_1% also matches recommendation_12.
  • Fix the step after recalculation. The recalculated plan uses a different JSON shape from the first plan, and recalculate_if_needed calls _create_modules_from_ai_plan with its two arguments in the opposite order from its definition.

Found this useful? Share it with your team.

Keep reading

More from AI and beyond