File size: 2,209 Bytes
37d9828 f0cb605 37d9828 f0cb605 37d9828 | 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 61 | import os
import gradio as gr
from openai import OpenAI
from dotenv import load_dotenv
# π Load API key
load_dotenv()
api_key = os.getenv("OPENAI_API_KEY")
client = OpenAI(api_key=api_key)
# π Python Tutor Function
def python_tutor(user_input):
response = client.chat.completions.create(
model="gpt-4.1-mini",
messages=[
{
"role": "system",
"content": """You are a Python tutor. Help users understand Python with short examples. Be kind, clear, and only answer Python-related questions.
1. Confirm if the question is Python-related. If not, politely inform the user and refrain from answering.
2. Provide a concise initial answer:
- Include a brief explanation.
- Provide a straightforward code example.
3. Keep the quiz simple and give options to choose. If wrong answers are selected, correct them with an explanation.
"""
},
{"role": "user", "content": user_input}
],
temperature=0.1,
max_tokens=500
)
return response.choices[0].message.content
# π Simple Quiz Generator (fixed question for now)
def ask_question():
return "What is the output of print(2 + 3 * 4)?"
def evaluate_answer(user_answer):
correct_answer = "14"
if user_answer.strip() == correct_answer:
return "β
Correct! Great job!"
else:
return "β Incorrect. Try again. Hint: Use BODMAS."
# π¨ Gradio UI with Two Pages
with gr.Blocks() as app:
with gr.Tab("π Python Tutor"):
gr.Markdown("### Ask your Python question:")
question_input = gr.Textbox(lines=2, label="Your Question")
answer_output = gr.Textbox(label="Tutor's Answer")
gr.Button("Ask").click(python_tutor, inputs=question_input, outputs=answer_output)
with gr.Tab("π§ͺ Mini Quiz"):
gr.Markdown("### Let's test your Python basics!")
quiz_question = gr.Textbox(label="Question", interactive=False, value=ask_question())
user_response = gr.Textbox(label="Your Answer")
result_output = gr.Textbox(label="Result")
gr.Button("Submit Answer").click(evaluate_answer, inputs=user_response, outputs=result_output)
app.launch()
|