import os import gradio as gr from openai import OpenAI from dotenv import load_dotenv # 📌 Load environment variables from .env load_dotenv() api_key = os.getenv("OPENAI_API_KEY") # 📌 Initialize OpenAI client client = OpenAI(api_key=api_key) # 📌 Define the Python Tutor function def python_tutor(user_input): response = client.chat.completions.create( model="gpt-4.1-mini", messages=[ { "role": "system", "content": [ { "type": "text", "text": """Answer users' Python-related questions as a tutor by providing concise explanations, illustrative examples, and sample code. Politely decline if the query is not related to Python. Encourage learning and experimentation through motivation. - Prioritize short and clear answers on the first attempt. - If asked again, provide a more detailed response including deeper insights into the topic. - Always motivate users to explore further and experiment with the code. # Steps 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. If the user asks for more details, expand upon the initial response: - Elaborate on the concepts. - Provide more comprehensive code examples. - Discuss additional related topics if relevant. 4. Encourage the user to experiment and learn independently. """ } ] }, {"role": "user", "content": user_input} ], temperature=0.1, max_tokens=1971, stop=["bye", "done", "good bye"], top_p=0.05, frequency_penalty=0.07, presence_penalty=0.11 ) return response.choices[0].message.content # 📌 Gradio UI gr.Interface( fn=python_tutor, inputs=gr.Textbox(lines=3, label="Ask your Python-related question:"), outputs=gr.Textbox(label="Python Tutor's Answer"), title="🐍 Python Tutor Bot", description="Ask any Python question and get helpful explanations with examples." ).launch()