MuhammadZainShahzad/ProgrammingTutorBot
0
1import gradio as gr
2import os
3import requests
4
5# Load GROQ API key from Hugging Face Secrets
6GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
7GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
8MODEL_NAME = "llama-3.1-8b-instant"
9
10
11# ==============================
12# PROGRAMMING TUTOR SYSTEM PROMPT
13# ==============================
14SYSTEM_PROMPT = """
15You are CodeMaster โ an expert programming tutor specializing in Python, C++, Java, and algorithms.
16You explain concepts clearly, give step-by-step solutions, fix code errors, and teach with simple examples.
17You are friendly, patient, and always respond with beginner-friendly explanations.
18When giving code, ensure it is clean, commented, and easy to understand.
19"""
20
21
22def query_groq(message, chat_history, difficulty):
23 # Modify response style based on UI difficulty dropdown
24 style_map = {
25 "Beginner": "Explain very simply with examples. Avoid jargon.",
26 "Intermediate": "Give clear explanations with moderate detail.",
27 "Advanced": "Use technical language and deep CS concepts.",
28 }
29
30 system_prompt = SYSTEM_PROMPT + "\nTone: " + style_map[difficulty]
31
32 headers = {
33 "Authorization": f"Bearer {GROQ_API_KEY}",
34 "Content-Type": "application/json"
35 }
36
37 messages = [{"role": "system", "content": system_prompt}]
38
39 # Restore previous messages
40 for user, bot in chat_history:
41 messages.append({"role": "user", "content": user})
42 messages.append({"role": "assistant", "content": bot})
43
44 # Add new user message
45 messages.append({"role": "user", "content": message})
46
47 response = requests.post(
48 GROQ_API_URL,
49 headers=headers,
50 json={
51 "model": MODEL_NAME,
52 "messages": messages,
53 "temperature": 0.4
54 }
55 )
56
57 if response.status_code == 200:
58 return response.json()["choices"][0]["message"]["content"]
59 else:
60 return f"Error {response.status_code}: {response.text}"
61
62
63def respond(message, difficulty, chat_history):
64 bot_reply = query_groq(message, chat_history, difficulty)
65 chat_history.append((message, bot_reply))
66 return "", chat_history
67
68
69# ==============================
70# BUILDING THE UI (With improvements)
71# ==============================
72with gr.Blocks() as demo:
73 gr.Markdown("## ๐จโ๐ป **CodeMaster โ Your Programming Tutor Chatbot**")
74
75 difficulty = gr.Dropdown(
76 ["Beginner", "Intermediate", "Advanced"],
77 label="Select explanation difficulty",
78 value="Beginner"
79 )
80
81 chatbot = gr.Chatbot()
82 msg = gr.Textbox(label="Ask any programming question...")
83 clear = gr.Button("Clear Chat")
84 state = gr.State([])
85
86 msg.submit(respond, [msg, difficulty, state], [msg, chatbot])
87 clear.click(lambda: ([], []), None, [chatbot, state])
88
89demo.launch()
90 