FatimaMohsin12/programming_tutor
0
1import gradio as gr2import os3import requests4 5# ================= CONFIG =================6GROQ_API_KEY = os.environ.get("GROQ_API_KEY")7 8GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"9MODEL_NAME = "llama-3.1-8b-instant"10 11SYSTEM_PROMPT = """12You are CodeMentor, a friendly and patient programming tutor.13You explain concepts clearly with examples.14You help beginners understand programming step by step.15"""16 17# ================= GROQ CALL =================18def call_groq(user_message, history, mode):19 if not GROQ_API_KEY:20 return "❌ GROQ_API_KEY missing. Add it in Hugging Face → Settings → Secrets."21 22 headers = {23 "Authorization": f"Bearer {GROQ_API_KEY}",24 "Content-Type": "application/json",25 }26 27 messages = [{"role": "system", "content": SYSTEM_PROMPT.strip()}]28 29 for msg in history:30 if isinstance(msg, dict) and "role" in msg and "content" in msg:31 messages.append({32 "role": str(msg["role"]),33 "content": str(msg["content"])34 })35 36 if mode == "Overview":37 user_message = "Respond gently and calmly.\n\n" + user_message38 elif mode == "Logical Breakdown":39 user_message = "Explain step-by-step with clarity.\n\n" + user_message40 elif mode == "Short Response":41 user_message = "Give a short and direct answer.\n\n" + user_message42 43 messages.append({"role": "user", "content": user_message})44 45 payload = {46 "model": MODEL_NAME,47 "messages": messages,48 "temperature": 0.6,49 "max_tokens": 512,50 }51 52 try:53 response = requests.post(54 GROQ_API_URL,55 headers=headers,56 json=payload,57 timeout=30,58 )59 60 if response.status_code != 200:61 return f"❌ Groq API Error {response.status_code}: {response.text}"62 63 data = response.json()64 return data["choices"][0]["message"]["content"].strip()65 66 except Exception as e:67 return f"⚠️ Request failed: {e}"68 69# ================= CHAT HANDLER =================70def respond(user_input, history, mode):71 reply = call_groq(user_input, history, mode)72 73 history.append({"role": "user", "content": user_input})74 history.append({"role": "assistant", "content": reply})75 76 return "", history77 78# ================= UI =================79with gr.Blocks() as demo:80 gr.Markdown(81 """82 # 🧠 Code Mentor 83 ### Your AI Programming Tutor84 """85 )86 87 chatbot = gr.Chatbot(height=420)88 89 msg = gr.Textbox(90 label="Your Question",91 )92 93 mode = gr.Radio(94 ["Overview", "Logical Breakdown", "Short Response"],95 value="Overview",96 label="Response Style",97 )98 99 with gr.Row():100 send = gr.Button("Send")101 clear = gr.Button("Clear Chat")102 103 send.click(respond, [msg, chatbot, mode], [msg, chatbot])104 msg.submit(respond, [msg, chatbot, mode], [msg, chatbot])105 106 clear.click(lambda: [], None, chatbot)107 108demo.launch()