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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
+
import requests
|
| 4 |
+
import json
|
| 5 |
+
from typing import List, Tuple
|
| 6 |
+
|
| 7 |
+
# Load GROQ API key from environment (set it in Hugging Face secrets)
|
| 8 |
+
GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
|
| 9 |
+
GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
|
| 10 |
+
|
| 11 |
+
# Available models
|
| 12 |
+
MODELS = {
|
| 13 |
+
"Llama 3 (8B) - Fast": "llama3-8b-8192",
|
| 14 |
+
"Llama 3 (70B) - Powerful": "llama3-70b-8192",
|
| 15 |
+
"Mixtral (8x7B) - Balanced": "mixtral-8x7b-32768"
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
# 🎯 Customize this system prompt based on your bot's role
|
| 19 |
+
SYSTEM_PROMPT = """You are CodeMentor, a friendly and knowledgeable programming tutor.
|
| 20 |
+
Your role is to help users learn programming concepts, debug code, and understand different programming languages.
|
| 21 |
+
|
| 22 |
+
Key personality traits:
|
| 23 |
+
1. Patient and encouraging - never make users feel bad for not knowing something
|
| 24 |
+
2. Explain concepts clearly with simple analogies first
|
| 25 |
+
3. Provide practical code examples
|
| 26 |
+
4. When debugging, guide users to discover the solution rather than just giving the answer
|
| 27 |
+
5. Adapt explanations to the user's skill level
|
| 28 |
+
6. Include best practices and common pitfalls
|
| 29 |
+
7. Be enthusiastic about programming!
|
| 30 |
+
|
| 31 |
+
Always format code examples with proper syntax highlighting using markdown code blocks.
|
| 32 |
+
If a user asks about something non-programming related, gently steer the conversation back to programming topics."""
|
| 33 |
+
|
| 34 |
+
def query_groq_api(message: str, chat_history: List[Tuple[str, str]], model: str, temperature: float, max_tokens: int) -> str:
|
| 35 |
+
"""Send request to GROQ API and get response"""
|
| 36 |
+
|
| 37 |
+
if not GROQ_API_KEY:
|
| 38 |
+
return "⚠️ API Key not configured. Please set GROQ_API_KEY in environment variables."
|
| 39 |
+
|
| 40 |
+
headers = {
|
| 41 |
+
"Authorization": f"Bearer {GROQ_API_KEY}",
|
| 42 |
+
"Content-Type": "application/json"
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
# Build messages list
|
| 46 |
+
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
|
| 47 |
+
|
| 48 |
+
# Add chat history
|
| 49 |
+
for user_msg, bot_msg in chat_history:
|
| 50 |
+
messages.append({"role": "user", "content": user_msg})
|
| 51 |
+
messages.append({"role": "assistant", "content": bot_msg})
|
| 52 |
+
|
| 53 |
+
# Add current message
|
| 54 |
+
messages.append({"role": "user", "content": message})
|
| 55 |
+
|
| 56 |
+
# Prepare payload
|
| 57 |
+
payload = {
|
| 58 |
+
"model": model,
|
| 59 |
+
"messages": messages,
|
| 60 |
+
"temperature": temperature,
|
| 61 |
+
"max_tokens": max_tokens,
|
| 62 |
+
"top_p": 0.9,
|
| 63 |
+
"stream": False
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
try:
|
| 67 |
+
response = requests.post(GROQ_API_URL, headers=headers, json=payload)
|
| 68 |
+
|
| 69 |
+
if response.status_code == 200:
|
| 70 |
+
data = response.json()
|
| 71 |
+
return data["choices"][0]["message"]["content"]
|
| 72 |
+
else:
|
| 73 |
+
return f"❌ Error {response.status_code}: {response.text}"
|
| 74 |
+
|
| 75 |
+
except requests.exceptions.RequestException as e:
|
| 76 |
+
return f"🚫 Connection error: {str(e)}"
|
| 77 |
+
except Exception as e:
|
| 78 |
+
return f"⚠️ Unexpected error: {str(e)}"
|
| 79 |
+
|
| 80 |
+
def respond(message: str, chat_history: List[Tuple[str, str]], model: str, temperature: float, max_tokens: int):
|
| 81 |
+
"""Process user message and return bot response"""
|
| 82 |
+
|
| 83 |
+
if not message.strip():
|
| 84 |
+
return "", chat_history
|
| 85 |
+
|
| 86 |
+
# Get bot response
|
| 87 |
+
bot_reply = query_groq_api(message, chat_history, model, temperature, max_tokens)
|
| 88 |
+
|
| 89 |
+
# Add to chat history
|
| 90 |
+
chat_history.append((message, bot_reply))
|
| 91 |
+
|
| 92 |
+
return "", chat_history
|
| 93 |
+
|
| 94 |
+
def clear_chat():
|
| 95 |
+
"""Clear chat history"""
|
| 96 |
+
return [], []
|
| 97 |
+
|
| 98 |
+
def update_example_questions(programming_language: str):
|
| 99 |
+
"""Update example questions based on selected programming language"""
|
| 100 |
+
|
| 101 |
+
examples = {
|
| 102 |
+
"Python": [
|
| 103 |
+
"Explain list comprehensions with examples",
|
| 104 |
+
"How do decorators work in Python?",
|
| 105 |
+
"What's the difference between 'is' and '=='?",
|
| 106 |
+
"Show me how to handle exceptions properly"
|
| 107 |
+
],
|
| 108 |
+
"JavaScript": [
|
| 109 |
+
"Explain promises and async/await",
|
| 110 |
+
"What is the event loop?",
|
| 111 |
+
"How does 'this' keyword work?",
|
| 112 |
+
"Explain closure with an example"
|
| 113 |
+
],
|
| 114 |
+
"Java": [
|
| 115 |
+
"Explain polymorphism with examples",
|
| 116 |
+
"Difference between abstract class and interface",
|
| 117 |
+
"How does garbage collection work?",
|
| 118 |
+
"What are Java Streams?"
|
| 119 |
+
],
|
| 120 |
+
"General": [
|
| 121 |
+
"What's the difference between SQL and NoSQL?",
|
| 122 |
+
"Explain REST API principles",
|
| 123 |
+
"What are design patterns?",
|
| 124 |
+
"How does Git branching work?"
|
| 125 |
+
]
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
return examples.get(programming_language, examples["General"])
|
| 129 |
+
|
| 130 |
+
# Create Gradio interface
|
| 131 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="CodeMentor - Programming Tutor") as demo:
|
| 132 |
+
|
| 133 |
+
# Store chat history in state
|
| 134 |
+
chat_state = gr.State([])
|
| 135 |
+
|
| 136 |
+
gr.Markdown("""
|
| 137 |
+
# 👨💻 CodeMentor - Your Personal Programming Tutor
|
| 138 |
+
|
| 139 |
+
Hi! I'm CodeMentor, your friendly AI programming assistant. I can help you with:
|
| 140 |
+
- Learning programming concepts
|
| 141 |
+
- Debugging code
|
| 142 |
+
- Understanding different languages
|
| 143 |
+
- Best practices and design patterns
|
| 144 |
+
|
| 145 |
+
Select your preferences below and start asking questions!
|
| 146 |
+
""")
|
| 147 |
+
|
| 148 |
+
with gr.Row():
|
| 149 |
+
with gr.Column(scale=1):
|
| 150 |
+
# UI Improvements (as required in assignment)
|
| 151 |
+
gr.Markdown("### ⚙️ Settings")
|
| 152 |
+
|
| 153 |
+
# Model selection dropdown
|
| 154 |
+
model_dropdown = gr.Dropdown(
|
| 155 |
+
choices=list(MODELS.keys()),
|
| 156 |
+
value="Llama 3 (8B) - Fast",
|
| 157 |
+
label="Select AI Model",
|
| 158 |
+
info="Choose the model for responses"
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
# Programming language selection
|
| 162 |
+
language_dropdown = gr.Dropdown(
|
| 163 |
+
choices=["Python", "JavaScript", "Java", "C++", "General"],
|
| 164 |
+
value="Python",
|
| 165 |
+
label="Programming Language Focus",
|
| 166 |
+
info="Get language-specific examples"
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
# Temperature slider
|
| 170 |
+
temperature_slider = gr.Slider(
|
| 171 |
+
minimum=0.1,
|
| 172 |
+
maximum=1.0,
|
| 173 |
+
value=0.7,
|
| 174 |
+
step=0.1,
|
| 175 |
+
label="Creativity (Temperature)",
|
| 176 |
+
info="Lower = more focused, Higher = more creative"
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
# Response length slider
|
| 180 |
+
max_tokens_slider = gr.Slider(
|
| 181 |
+
minimum=100,
|
| 182 |
+
maximum=2000,
|
| 183 |
+
value=500,
|
| 184 |
+
step=100,
|
| 185 |
+
label="Response Length (Tokens)",
|
| 186 |
+
info="Maximum length of responses"
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
# Example questions based on selected language
|
| 190 |
+
gr.Markdown("### 💡 Try These Questions")
|
| 191 |
+
example_questions = gr.Dataset(
|
| 192 |
+
components=[gr.Textbox(visible=False)],
|
| 193 |
+
samples=update_example_questions("Python"),
|
| 194 |
+
label="Click a question to ask:",
|
| 195 |
+
type="index"
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
# Clear button
|
| 199 |
+
clear_btn = gr.Button("🧹 Clear Chat", variant="secondary")
|
| 200 |
+
|
| 201 |
+
with gr.Column(scale=2):
|
| 202 |
+
# Chat interface
|
| 203 |
+
chatbot = gr.Chatbot(
|
| 204 |
+
value=[],
|
| 205 |
+
label="CodeMentor",
|
| 206 |
+
height=500,
|
| 207 |
+
bubble_full_width=False
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
# Message input
|
| 211 |
+
msg = gr.Textbox(
|
| 212 |
+
placeholder="Type your programming question here... (Press Enter to send)",
|
| 213 |
+
label="Your Question",
|
| 214 |
+
lines=2
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
# Send button
|
| 218 |
+
send_btn = gr.Button("🚀 Send", variant="primary")
|
| 219 |
+
|
| 220 |
+
# Update example questions when language changes
|
| 221 |
+
language_dropdown.change(
|
| 222 |
+
fn=update_example_questions,
|
| 223 |
+
inputs=language_dropdown,
|
| 224 |
+
outputs=example_questions
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
# Handle example question clicks
|
| 228 |
+
example_questions.click(
|
| 229 |
+
fn=lambda x: x,
|
| 230 |
+
inputs=[example_questions],
|
| 231 |
+
outputs=msg
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
# Handle message submission
|
| 235 |
+
msg.submit(
|
| 236 |
+
fn=respond,
|
| 237 |
+
inputs=[msg, chat_state, model_dropdown, temperature_slider, max_tokens_slider],
|
| 238 |
+
outputs=[msg, chatbot]
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
send_btn.click(
|
| 242 |
+
fn=respond,
|
| 243 |
+
inputs=[msg, chat_state, model_dropdown, temperature_slider, max_tokens_slider],
|
| 244 |
+
outputs=[msg, chatbot]
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
# Handle clear button
|
| 248 |
+
clear_btn.click(
|
| 249 |
+
fn=clear_chat,
|
| 250 |
+
inputs=None,
|
| 251 |
+
outputs=[chatbot, chat_state]
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
# Footer
|
| 255 |
+
gr.Markdown("""
|
| 256 |
+
---
|
| 257 |
+
### ℹ️ About
|
| 258 |
+
- **Powered by**: GROQ API with Llama 3
|
| 259 |
+
- **Theme**: Programming Tutor
|
| 260 |
+
- **UI Features**: Model selection, language focus, temperature control, response length slider
|
| 261 |
+
- **Deployed on**: Hugging Face Spaces
|
| 262 |
+
|
| 263 |
+
⚠️ Note: This is an educational tool. Always verify critical code before production use.
|
| 264 |
+
""")
|
| 265 |
+
|
| 266 |
+
if __name__ == "__main__":
|
| 267 |
+
demo.launch(debug=False)
|