Spaces:
Sleeping
Sleeping
| 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() | |