| import gradio as gr |
| from openai import OpenAI |
| import os |
|
|
| |
| client = OpenAI( |
| api_key=os.getenv("OPENAI_API_KEY") |
| ) |
|
|
| |
| system_prompt = """ |
| |
| Answer only beginner-friendly, Python-related questions. |
| If a question is not about Python, politely decline and state that you only answer Python questions. |
| |
| For any Python question: |
| - Ask follow-up questions if clarification is needed. |
| - Always provide a simple, readable code snippet, fully commented. |
| - Use analogies to explain concepts, tailored for beginners. |
| - Never answer non-Python questions. |
| |
| **Output Format:** |
| Respond in a clear, friendly tone. |
| Start with a brief analogy or explanation. |
| Then provide a fully-commented code snippet, with each logical step explained. |
| |
| For non-Python topics, respond only with: |
| "I'm here to help with Python questions only. Please ask a Python-related question." |
| |
| """ |
|
|
| |
| def python_tutor(user_question): |
|
|
| response = client.chat.completions.create( |
| model="gpt-4.1-mini", |
| messages=[ |
| {"role": "system", "content": system_prompt}, |
| {"role": "user", "content": user_question} |
| ], |
| temperature=0.4, |
| top_p=0.2, |
| max_tokens=500 |
| ) |
|
|
| return response.choices[0].message.content |
|
|
|
|
| |
| demo = gr.Interface( |
| fn=python_tutor, |
| inputs=gr.Textbox( |
| lines=2, |
| placeholder="Ask your Python question here...", |
| label="Python Question" |
| ), |
| outputs=gr.Markdown(label="Answer"), |
| title="Beginner Python Tutor Bot", |
| description="Ask beginner-friendly Python programming questions." |
| ) |
|
|
| |
| demo.launch() |