File size: 2,152 Bytes
2c67e66
164aa22
 
855c5f2
164aa22
855c5f2
 
b42f40c
1f41403
 
ee79f0b
164aa22
1f41403
164aa22
 
 
 
 
 
ee79f0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164aa22
 
 
 
f8336fe
1f41403
164aa22
 
 
a309875
ee79f0b
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
import os
import openai
import gradio as gr
from dotenv import load_dotenv

# Load API key from .env file
load_dotenv()
api_key = os.getenv("openai")

if not api_key:
    raise ValueError("API Key not found! Ensure you have set 'OPENAI_API_KEY' in your .env file.")

# Set up OpenAI API Key
openai.api_key = api_key

# Define chatbot function
def python_tutor_bot(user_input):
    if not user_input.strip():
        return "Please enter a valid question."
    
    try:
        response = openai.ChatCompletion.create(
            model="gpt-4-turbo",  # Corrected model name
            messages=[
                {
                    "role": "system",
                    "content": (
                        "You are a Python tutor bot designed to help beginners learn and troubleshoot Python programming. "
                        "Explain concepts in simple terms, provide clear examples, and help debug user code.\n\n"
                        "### Guidelines:\n"
                        "- Use beginner-friendly language, as if explaining to an 8th grader.\n"
                        "- Offer simple code examples to illustrate concepts.\n"
                        "- Identify and fix errors in user-provided code with explanations.\n"
                        "- Encourage follow-up questions to ensure understanding.\n"
                    ),
                },
                {"role": "user", "content": user_input}
            ],
            temperature=0.1,
            max_tokens=1000,
            top_p=0.9,
            frequency_penalty=0,
            presence_penalty=0.3
        )
        return response["choices"][0]["message"]["content"]
    
    except openai.error.OpenAIError as e:
        return f"Error: {str(e)}"

# Create Gradio chat interface
chatbot_ui = gr.Interface(
    fn=python_tutor_bot,
    inputs=gr.Textbox(lines=3, placeholder="Ask me anything about Python..."),
    outputs=gr.Textbox(),
    title="Python Tutor Bot for beginners",
    description="A friendly Python tutor bot to help you learn and troubleshoot Python. Ask any question!"
)

# Launch Gradio UI
if __name__ == "__main__":
    chatbot_ui.launch()