Quiz Variables Prompt Generator Using Google Generative AI
Introduction
In educational technology, generating quizzes tailored to specific criteria can significantly enhance learning experiences. This article outlines a step-by-step guide to creating a Streamlit application that utilizes Google’s Generative AI to generate quiz prompts based on user-defined variables. By allowing users to specify question types, difficulty levels, and additional features, this application is a versatile tool for educators and learners alike.
Step-by-Step Implementation
Prerequisites
Ensure you have the following installed:
- Python 3.x
- Streamlit
- Google Generative AI SDK
- python-docx
- dotenv
Install the necessary packages using pip:
pip install streamlit google-generativeai python-docx python-dotenv
Step 1: Set Up Environment Variables
Create a `.env` file in your project directory and add your Google Generative AI API key:
GOOGLE_GENERATIVE_AI_API_KEY=your_api_key_here
Step 2: Import Required Libraries
Create a new Python file (e.g., `quiz_generator.py`) and import the necessary libraries:
import google.generativeai as genai
from dotenv import load_dotenv
import os
from docx import Document
from io import BytesIO
from datetime import datetime
import streamlit as st
#Load environment variables from .env file
load_dotenv()
Set up the Google Generative AI API key
api_key = os.getenv("GOOGLE_GENERATIVE_AI_API_KEY")
genai.configure(api_key=api_key)
Step 3: Build the Streamlit User Interface
Title and Input Fields
Set up the title and user input fields for quiz parameters:
#Title of the Quiz Prompt Generator
st.title("Quiz Variables Prompt Generator")
User Input Interface - Question Type
question_type = st.selectbox(
"Select Question Type:",
["Multiple Choice", "True/False", "Short Answer", "Essay", "Matching"]
)
#Difficulty Input
difficulty = st.selectbox(
"Select Difficulty:",
["Easy", "Medium", "Hard", "Expert"]
)
#Extra Features Input
extra_feature = st.multiselect(
"Choose Extra Features:",
["Educational level (e.g. primary school, high school, college)",
"Experience (e.g. beginners, intermediate, advanced)",
"Time limit (e.g. quickfire, timed, untimed)",
"Complexity (e.g. simple, moderate, difficult)"]
)
#Quantity Slider
quantity = st.slider(
"Select Quantity of Questions:",
min_value=1,
max_value=100,
value=5,
step=1
)
# Age Range Slider
age_range = st.slider(
"Select Age Range for the Quiz:",
min_value=0,
max_value=100,
value=(10, 18), Default range from 10 to 18 years
step=1,
format="Age: %d"
)
# Subject Input
subject = st.text_input("Enter Subject (e.g. Mathematics, Science, History):", "General Knowledge")
Step 4: Define Safety Settings
Set up safety settings for content generation:
# Safety Settings (adjust as necessary)
safety_settings = [
{"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"},
{"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_NONE"},
{"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"},
]
Step 5: Generate Quiz Prompt
Create a function to generate the quiz prompt based on user inputs:
quiz_prompt = ""
doc_file = None
if st.button("Generate Quiz Prompt"):
input_prompt = f"""
Create a quiz based on the following parameters:
Quiz Type: {question_type}
Difficulty: {difficulty}
Subject: {subject}
Quantity: {quantity}
Age Range: {age_range[0]} to {age_range[1]} years
Extra Features:
{"; ".join(extra_feature) if extra_feature else "None"}
"""
model = genai.GenerativeModel("gemini-1.5-flash-latest", safety_settings=safety_settings)
try:
response = model.generate_content(input_prompt)
quiz_prompt = response.text.strip()
quiz_prompt = quiz_prompt.replace("", '').replace("", '')
st.write(" Generated Quiz Prompt:")
st.code(quiz_prompt)
#Create a new Document for download
doc = Document()
doc.add_heading("Quiz Prompt Document", level=1).bold = True
Add quiz details to the document
doc.add_heading("Quiz Details", level=2)
doc.add_paragraph(f"Question Type: {question_type}")
doc.add_paragraph(f"Difficulty: {difficulty}")
doc.add_paragraph(f"Subject: {subject}")
doc.add_paragraph(f"Quantity of Questions: {quantity}")
doc.add_paragraph(f"Age Range: {age_range[0]} to {age_range[1]} years")
doc.add_paragraph("Extra Features: " + (", ".join(extra_feature) if extra_feature else "None"))
Add generated quiz prompt to the document
doc.add_heading("Generated Quiz Prompt", level=2)
doc.add_paragraph(quiz_prompt)
Save the document to a BytesIO object for download
doc_file = BytesIO()
doc.save(doc_file)
doc_file.seek(0)
except Exception as e:
st.error(f"An error occurred while generating the quiz prompt: {e}")
Step 6: Provide Download Option
Enable users to download the generated quiz document:
if doc_file is not None:
st.download_button(
label="Download Quiz Document",
data=doc_file,
file_name=f"quiz_prompt_{datetime.now().strftime('%Y%m%d_%H%M%S')}.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
help="Click here to download the quiz prompt as a Word document."
)
Step 7:Run the Streamlit Application
Open a terminal or command prompt, navigate to the directory where your app.py file is located, and run the following command:
streamlit run quiz_generator.py
The Final Result:
Conclusion
This guide provides a clear framework for developing a Quiz Variables Prompt Generator using Streamlit and Google Generative AI. Following these steps, you can create an interactive tool that generates customized quizzes based on user-defined parameters, enhancing teaching and learning experiences. Further improvements could include refining user input options and expanding safety settings for content generation.
Thanks for reading If you love this tutorial, give some claps.
Connect with me on FB, Github,linkedin,my blog, PyPi, and my YouTube channel,Email:falahgs07@gmail.com