Beginner 11 minEducation

Teacher: generate exercices

Direct response

To generate exercises locally, serve Qwen 3.5 9B (6.6 GB) with Ollama or LM Studio, save your prompt in a custom template, request multiple-choice questions in script-validated JSON, and have code calculate the numeric answers instead of the model. The French national education system’s usage framework allows this use, provided you verify everything and disclose it.

Preparing exercises, answer keys, and adapted versions takes many long evenings, and AI can help if you retain control of the content. This guide sets up a local workstation for multiple-choice questions, exercises, and their adaptation, based on one guiding principle: the model drafts, the code calculates and checks, and the teacher verifies. It builds on the framework for AI use in education published in 2025.

By Mohamed Meguedmi·Update 2026-09-30·Tested on Windows, macOS, and Linux

#Why prepare your exercises with a local model

The framework for AI use in education published by the ministry in June 2025, as summarized by the regional education authorities, permits use for lesson preparation, assessment, and grading, with two obligations for teachers: systematically verify AI-generated work and be transparent about its use. It expressly prohibits using personal or confidential data in public-facing AI systems and encourages favoring open-source solutions. A local model meets all three points: nothing leaves the computer, no registration is required, and open-weight models are open-source solutions in the usual sense of the term.

One argument often made needs some nuance: preparing a math exercise with a consumer service is still allowed as long as no personal data is entered. The value of local deployment lies elsewhere. It lets you work with documents containing names, such as student papers or assessments, without exposing students. It works offline. And it provides stable behavior: a saved instruction and a model that does not change from one month to the next.

Students and copies
Never enter a name, identifiable copy, or opinion into an online service. Locally, the risk of transfer disappears, but minimization is still a good habit.
Cost
No subscription. The hardware already exists if your recent computer has 16 GB of memory; otherwise, a small model is enough for simple exercises.
Offline
Useful in a teachers’ room or in a school whose network filters AI services.
Stability
A prompt saved in a custom model produces consistent briefs from week to week.

#The minimal stack

The Local AI Kit

Your private ChatGPT, free, on your own machine in an hour — LM Studio, Ollama, Open WebUI, your documents, no cloud.

  • Lifetime online access
  • PDF + files
  • Lifetime updates

Two software options are available for serving the model: Ollama, from the command line, or LM Studio, with a more accessible graphical interface if the terminal puts you off. On the model side, Qwen 3.5 with 9 billion parameters weighs 6.6 GB in the Ollama library and advertises 256,000 context tokens: it fits on an 8 GB card or in the memory of a recent computer. Mistral Small 24B weighs 14 GB and requires more memory. A larger model is not a guarantee of accuracy; your review is.

To avoid retyping your prompt, create a custom model with a Modelfile: the SYSTEM instruction defines the system message applied to every conversation. The file below locks in the role, level, and style of your briefs.

Modelfile for an exercise assistant
FROM qwen3.5:9b
PARAMETER temperature 0.4
PARAMETER num_ctx 8192
SYSTEM """Tu aides un professeur de collège à préparer des exercices conformes aux programmes
français du cycle 4. Vocabulaire adapté à l'âge des élèves. Tu ne donnes que des
corrigés dont tu es sûr ; sinon tu écris : à vérifier. Tu n'inventes jamais de citation,
de date ou de source."""
Create and run the model
ollama create prof-exos -f Modelfile
ollama run prof-exos

#Generate usable multiple-choice quizzes, not just readable ones

A multiple-choice quiz requested as free-form text is difficult to reuse: you have to retype it into the classroom tool. It is better to request a structured format that the code can then validate. Ollama can constrain the response to a JSON schema: according to its documentation, you pass it in the format field. The model writes the questions; the script checks that there are four distinct choices and only one correct answer, then writes an importable file.

Generate and validate a multiple-choice quiz
import json, requests, re

SCHEMA = {'type': 'object', 'properties': {'questions': {'type': 'array', 'items': {
  'type': 'object', 'properties': {
    'enonce': {'type': 'string'},
    'choix': {'type': 'array', 'items': {'type': 'string'}},
    'bonne_reponse': {'type': 'integer'},
    'explication': {'type': 'string'}},
  'required': ['enonce', 'choix', 'bonne_reponse', 'explication']}}},
  'required': ['questions']}

def generer(sujet, niveau, n=10, modele='prof-exos'):
    consigne = (f'Rédige {n} questions à choix multiple sur : {sujet}. Niveau : {niveau}. '
      'Quatre choix par question, dont un seul correct ; bonne_reponse est l\'indice (0 à 3). '
      'Les mauvais choix doivent être plausibles. Une phrase d\'explication. '
      'Réponds par un JSON conforme à : ' + json.dumps(SCHEMA))
    r = requests.post('http://localhost:11434/api/chat', json={
        'model': modele, 'stream': False, 'format': SCHEMA,
        'messages': [{'role': 'user', 'content': consigne}]})
    return json.loads(r.json()['message']['content'])['questions']

def valides(questions):
    ok, rejets, vus = [], [], set()
    for q in questions:
        c = q.get('choix', [])
        if (len(c) != 4 or len({x.strip().lower() for x in c}) != 4
                or q.get('bonne_reponse') not in (0, 1, 2, 3) or q['enonce'].strip().lower() in vus):
            rejets.append(q); continue
        vus.add(q['enonce'].strip().lower()); ok.append(q)
    return ok, rejets

def esc(s):
    return re.sub(r'([~=#{}:])', r'\\\1', s)

def vers_gift(questions):
    blocs = []
    for i, q in enumerate(questions, 1):
        lignes = [('=' if j == q['bonne_reponse'] else '~') + esc(c) for j, c in enumerate(q['choix'])]
        blocs.append(f"::Q{i}::{esc(q['enonce'])} {{\n" + '\n'.join(lignes) + '\n}\n')
    return '\n'.join(blocs)

The GIFT format, used by Moodle, is a simple text file that can be imported into a question bank. If your institution uses another tool, adapt the last function: the principle remains to produce a file from the validated data, not to copy and paste the model's text. What the script does not verify is whether the questions are correct—which is why there is a section on verification.

→
The prompt that improves quality the most
Specify the authorized source. “Ask questions only about the following text” and pasting an excerpt from your course produces verifiable questions, whereas an open-ended topic (“the French Revolution”) makes the model rely on its memory, where it is most likely to invent things.

#Anchor each question to a passage from your course

The safest method against invented facts is to require, for every question, the course passage that supports it. You paste in your text, add a passage field to the schema, and the script checks that the passage exists word for word in the supplied text. A question whose passage cannot be found is discarded: either the model invented it or paraphrased it without a source. This check does not prove that the question is good, but it guarantees that it is grounded in your course rather than in the model’s approximate memory.

Verify that the cited passage appears in the course
def normaliser(t):
    return ' '.join(t.split()).lower()

def ancrees(questions, cours):
    base = normaliser(cours)
    bonnes, douteuses = [], []
    for q in questions:
        (bonnes if normaliser(q.get('passage', '')) in base else douteuses).append(q)
    return bonnes, douteuses

The schema and instruction complement each other accordingly: add passage to the properties and required fields, and write in the instruction, “copy the passage from the text that justifies the correct answer word for word.” Questions about facts absent from the course, such as dates never mentioned, will not pass the filter, which is precisely the point.

#Math exercises: Python calculates, the model dresses it up

A 9-billion-parameter model makes mistakes on simple operations, especially with decimals and carrying. For calculation exercises, it is better to reverse the roles: the code randomly selects the numbers, calculates the exact result, and generates the answer key; the model writes the word problems around those numbers, which it does well. This way, the answers in your worksheets never depend on its arithmetic.

Decimal calculation exercises with exact answers
import random
from decimal import Decimal

def fr(d):
    return str(d.normalize() if d == d.to_integral() else d).replace('.', ',')

def exercices_decimaux(n=8, graine=None):
    hasard = random.Random(graine)
    sortie = []
    for i in range(n):
        nb = 2 if i < 2 else hasard.choice([3, 3, 4])
        vals = [Decimal(hasard.randint(10, 9999)) / hasard.choice([10, 100]) for _ in range(nb)]
        signes = ['+'] + [hasard.choice(['+', '-']) for _ in vals[1:]]
        total = sum(v if s == '+' else -v for v, s in zip(vals, signes))
        if total < 0:
            continue
        enonce = ' '.join((s + ' ' if k else '') + fr(v) for k, (v, s) in enumerate(zip(vals, signes)))
        sortie.append((enonce, fr(total)))
    return sortie

for e, r in exercices_decimaux(graine=42):
    print(e, '=', r)

A fixed seed lets you regenerate exactly the same worksheet, for example to produce the corrected version the next day. The same principle applies to unit conversions, percentages, first-degree equations—anything that can be calculated: code generates and verifies it, while the model formats it. Languages are different, however: that is the model’s domain. It generates the sentences to complete, fill-in-the-blank dialogues, and instructions, which you must review.

Prompt for an English exercise
Prépare pour des élèves de 5e (niveau A2 du CECRL) une fiche sur le present simple
et le present continuous : 5 phrases à conjuguer, 3 phrases à transformer, un court
dialogue à trous. Vocabulaire courant uniquement. Donne le corrigé à la fin, séparé
par une ligne « CORRIGÉ », et signale entre crochets toute phrase où les deux temps
sont possibles.

#Corrections: ask, then cross-check

Ask for the answer key in a second message so the model keeps the prompt in context, specifying what you expect: the final answer, the step-by-step reasoning, the rule applied, and the typical mistake to avoid. The answer key is the riskiest part of the worksheet: a student can confidently learn the wrong answer. Two practices reduce the risk.

Calculate rather than make it calculate
When the answer can be calculated, get it from the code, not the model.
Generate twice and compare
For reasoning exercises, ask for the solution twice, using slightly different instructions. If the final answers differ, review the exercise manually.
Have another model solve it
A second model, from a different size or family, solves the problem statement without seeing the answer key. Disagreement indicates likely errors. It is not proof, just a filter.
Proofread everything that will be distributed
No automated check replaces the teacher’s review, and the teacher remains responsible for the content.

#Adapt a worksheet to the students' level

Differentiation is where the model adds the most value, because rephrasing is its strength. Start with a validated worksheet and ask for variants, keeping the same numbers and answers so the answer key remains valid. Have a colleague review the variant before distributing it: a simpler rephrasing can change the meaning of a question, which is a classic flaw of these rewrites.

Differentiation instructions based on a validated fact sheet
NeedPrompt to provideCheck next
Struggling studentRephrase the statements as short sentences, add a solved example before the first exercise, and keep the same numbersThat the answers have not changed
Advanced studentAdds three advanced exercises that use the same concepts in a more abstract contextThat the new exercises are feasible and correct
Special requirementsReduce it to four exercises, with short sentences and one solved example before each exercise; formatting remains your responsibilityThe agreement with the accommodations planned for the student
Oral versionTurns statements into questions to ask aloud, with one instruction per sentenceOral readability

#Check accuracy, discipline by discipline

Where the model gets things wrong, and how to spot it
DisciplineMain riskVerification
MathematicsRetention, sign, and comma errorsCalculate with code; redo every exercise
History and geographyInvented or shifted dates, names, and figuresCross-check against the manual or an official source
LanguagesIncorrect forms, unnatural sentencesReview by a colleague or a native speaker
ScienceFormulas, units, numerical valuesCheck every formula and unit
FrenchNonexistent or misattributed citationsCheck each citation against the work

The common thread is that the model writes with the same confidence when it is right and when it is wrong. The ministerial framework also calls for systematic verification of AI output. In practice, set aside five minutes to review each worksheet, and keep a small log of errors you find: after a month, you will know which subjects the model is reliable for you in.

#A realistic production pace

  1. 01
    List the week's concepts
    Three to five concepts, with the course excerpts to use as the source.
  2. 02
    Generate from your sources
    Paste the course excerpt into the prompt: the questions remain grounded in what you taught.
  3. 03
    Have the code calculate the answer keys
    For anything encrypted, use a script like the one above.
  4. 04
    Review and correct
    Read the entry as a student would: a grading error is costly.
  5. 05
    Format the page and disclose usage
    Export to PDF or to your classroom tool, and tell students that AI helped prepare the worksheet, in accordance with the transparency requirement.
i
Measure your gains instead of assuming them
Time your usual preparation, then your preparation with the tool, over three weeks, including review. The improvement depends heavily on discipline and skill level. If it is small on answer keys, keep the tool for variants and differentiation.
FAQ
Can a teacher use AI to prepare lessons?+
Yes: the French Ministry of National Education’s June 2025 usage framework, as summarized by the academies, authorizes AI for lesson preparation, assessment, and grading. It requires systematic verification of outputs and transparency about their use, and prohibits entering personal data into consumer services.
Which local model should you choose to generate exercises?+
Qwen 3.5 9B (6.6 GB, 256,000 advertised tokens) works on a computer with 8 GB of video memory or 16 GB of memory. Mistral Small 24B (14 GB) requires more. For calculation exercises, the model should not produce the answers: have a Python script calculate them instead, which is more reliable than a model.
Can you trust AI-generated answer keys?+
No, not without verification. A model writes an incorrect answer key with the same confidence as a correct one. Calculate numerical answers with code, compare two generations for reasoning exercises, and proofread every handout before distributing it. The ministry framework also requires systematic verification.
Should you tell students that a handout was generated by AI?+
The French Ministry of Education’s framework for use calls for transparency about AI use. Stating on the sheet that it was prepared with the help of AI and reviewed by the teacher is simple, honest, and educational. It is also an opportunity to remind students that these tools can make mistakes.
How do I import generated MCQs into Moodle or another tool?+
Have it generate the questions in a controlled JSON format, verify with a script that there are four distinct choices and a valid answer, then convert them into a GIFT file, a text format that Moodle imports into a question bank. For another tool, adapt the conversion: the data stays the same.
Can you enter student papers into a local model?+
Technically, no data leaves the computer, eliminating the risk of transfer. Even so, keep good habits: remove names before any processing, keep files on a protected workstation, and follow your institution's guidelines. Assisted grading is the teacher's responsibility, and the teacher retains the final decision.
Did this guide help you?

Feedback, an error, or a clarification? Let us know—it improves the guide for everyone.