education / utils.py
amirkhanbloch's picture
Update utils.py
54d9bfb verified
import gradio as gr
from groq import Groq
import os
# Initialize Groq client
client = Groq(api_key=os.environ["GROQ_API_KEY"])
def generate_tutor_output(chapter, difficulty, student_input):
prompt = f"""
You are an expert 10th-grade physics tutor at the {difficulty} level.
The student has selected the following chapter: "{chapter}" and provided this input: "{student_input}"
Please generate an unsolved test with:
1. Multiple Choice Questions (MCQs)
2. Short Answer Questions
3. Long Answer Questions
Format your response as a JSON object with keys: "mcqs", "short_questions", "long_questions"
"""
completion = client.chat.completions.create(
messages=[
{
"role": "system",
"content": "You are the world's best AI tutor specializing in 10th-grade physics, adept at creating customized tests. Generate MCQs, short questions, and long questions based on the provided chapter."
},
{
"role": "user",
"content": prompt,
}
],
model="llama3-groq-70b-8192-tool-use-preview",
max_tokens=1000,
)
print("Raw Model Output:", completion.choices[0].message.content) # Debugging output
return completion.choices[0].message.content
with gr.Blocks() as demo:
gr.Markdown("# ๐ŸŽ“ 10th Grade Physics Tutor - Test Generator")
with gr.Row():
with gr.Column(scale=2):
chapter = gr.Dropdown(
["Chapter 1: Kinematics", "Chapter 2: Dynamics", "Chapter 3: Energy", "Chapter 4: Waves"],
label="Select Chapter",
info="Choose the chapter for the test"
)
difficulty = gr.Radio(
["Beginner", "Intermediate", "Advanced"],
label="Difficulty Level",
info="Select your proficiency level"
)
student_input = gr.Textbox(
placeholder="Enter additional details...",
label="Your Input",
info="Specify 'MCQs', 'short questions', or 'long questions' if needed"
)
submit_button = gr.Button("Generate Test", variant="primary")
with gr.Column(scale=3):
mcq_output = gr.Markdown(label="MCQs")
short_question_output = gr.Markdown(label="Short Questions")
long_question_output = gr.Markdown(label="Long Questions")
gr.Markdown("""
### Instructions
1. Select a chapter to generate questions from.
2. Choose your difficulty level.
3. Provide any additional details if needed.
4. Specify 'MCQs', 'short questions', or 'long questions' to filter the output, or leave blank for all types.
5. Click 'Generate Test' to receive questions based on the chapter.
""")
def process_output(output, user_input):
try:
# Parse the JSON output
parsed = eval(output)
# Filter based on the user input
mcqs, short_questions, long_questions = "", "", ""
if "mcq" in user_input.lower():
mcqs = "\n".join([f"**Q:** {mcq['question']} - Options: {', '.join(mcq['options'])}" for mcq in parsed.get("mcqs", [])])
if "short" in user_input.lower():
short_questions = "\n".join([sq["question"] for sq in parsed.get("short_questions", [])])
if "long" in user_input.lower():
long_questions = "\n".join([lq["question"] for lq in parsed.get("long_questions", [])])
# Default to all types if no specific type is mentioned
if not any(keyword in user_input.lower() for keyword in ["mcq", "short", "long"]):
mcqs = "\n".join([f"**Q:** {mcq['question']} - Options: {', '.join(mcq['options'])}" for mcq in parsed.get("mcqs", [])])
short_questions = "\n".join([sq["question"] for sq in parsed.get("short_questions", [])])
long_questions = "\n".join([lq["question"] for lq in parsed.get("long_questions", [])])
return mcqs or "No MCQs available", short_questions or "No short questions available", long_questions or "No long questions available"
except Exception as e:
print("Error processing output:", e) # Additional error message for debugging
return "Error parsing output", "No short questions available", "No long questions available"
submit_button.click(
fn=lambda c, d, i: process_output(generate_tutor_output(c, d, i), i),
inputs=[chapter, difficulty, student_input],
outputs=[mcq_output, short_question_output, long_question_output]
)
if __name__ == "__main__":