File size: 2,368 Bytes
378a4c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecbc249
 
10bfdae
378a4c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import gradio as gr
import os
import requests

# Load GROQ API key from Hugging Face Secrets
GROQ_API_KEY = os.environ.get("GROQ_API_KEY")

GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
MODEL_NAME = "llama-3.1-8b-instant"


# System Prompt (Chatbot Personality)
SYSTEM_PROMPT = """
You are CodeMentor AI, a friendly and expert programming tutor.
You help students learn programming concepts clearly and patiently.

Your behavior:
- Explain concepts step-by-step
- Use simple language
- Give Python examples when possible
- Encourage learning and curiosity
- Correct mistakes politely
"""

def query_groq(message, chat_history, temperature):
    headers = {
        "Authorization": f"Bearer {GROQ_API_KEY}",
        "Content-Type": "application/json"
    }

    messages = [{"role": "system", "content": SYSTEM_PROMPT}]

    for user, bot in chat_history:
        messages.append({"role": "user", "content": user})
        messages.append({"role": "assistant", "content": bot})

    messages.append({"role": "user", "content": message})

    response = requests.post(
        GROQ_API_URL,
        headers=headers,
        json={
            "model": MODEL_NAME,
            "messages": messages,
            "temperature": temperature
        }
    )

    if response.status_code == 200:
        return response.json()["choices"][0]["message"]["content"]
    else:
        return f"Error {response.status_code}: {response.text}"

def respond(message, chat_history, temperature):
    bot_reply = query_groq(message, chat_history, temperature)
    chat_history.append((message, bot_reply))
    return "", chat_history

with gr.Blocks(theme=gr.themes.Soft()) as demo:

    gr.Markdown("## 💻 Kashif's CodeMentor AI – Your Programming Tutor")

    chatbot = gr.Chatbot(height=400)
    state = gr.State([])

    with gr.Row():
        msg = gr.Textbox(label="Ask a programming question")
    
    # UI Improvement (Requirement #4)
    temperature = gr.Slider(
        0.1, 1.0, value=0.7, step=0.1,
        label="Response Creativity Level"
    )

    with gr.Row():
        send = gr.Button("Send")
        clear = gr.Button("Clear Chat")

    send.click(respond, [msg, state, temperature], [msg, chatbot])
    msg.submit(respond, [msg, state, temperature], [msg, chatbot])
    clear.click(lambda: ([], []), None, [chatbot, state])

demo.launch()