File size: 1,672 Bytes
84a961c
 
 
e700f9c
84a961c
 
 
 
 
 
2441489
ffb5fad
 
 
 
 
 
 
 
 
 
 
 
 
 
84a961c
ffb5fad
 
 
e700f9c
 
84a961c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e700f9c
 
84a961c
 
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
62
63
import gradio as gr
from openai import OpenAI
import os

# Initialize OpenAI client
client = OpenAI(
    api_key=os.getenv("OPENAI_API_KEY")
)

# System Prompt
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."

"""

# Function for Gradio UI
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


# Gradio Interface
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."
)

# Launch app
demo.launch()