| | import os |
| | import gradio as gr |
| | from openai import OpenAI |
| | from dotenv import load_dotenv |
| |
|
| | |
| | load_dotenv() |
| | api_key = os.getenv("OPENAI_API_KEY") |
| | client = OpenAI(api_key=api_key) |
| |
|
| | |
| | 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 |
| |
|
| | |
| | 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." |
| |
|
| | |
| | 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() |
| |
|