File size: 11,307 Bytes
4bad81b adcbb92 587b95e adcbb92 4bad81b adcbb92 4bad81b 587b95e 4bad81b adcbb92 587b95e adcbb92 587b95e adcbb92 587b95e adcbb92 587b95e adcbb92 587b95e adcbb92 587b95e adcbb92 587b95e adcbb92 587b95e adcbb92 793e095 adcbb92 587b95e adcbb92 587b95e adcbb92 587b95e adcbb92 587b95e adcbb92 587b95e adcbb92 587b95e adcbb92 587b95e adcbb92 587b95e adcbb92 587b95e adcbb92 587b95e adcbb92 587b95e adcbb92 793e095 4bad81b adcbb92 | 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 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 | import gradio as gr
import os
import requests
import json
from typing import List, Tuple
import time
# Load GROQ API key from environment (set it in Hugging Face secrets)
GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
# β
UPDATED: Correct GROQ model names (as of Dec 2024)
MODELS = {
"Llama 3.2 (3B) - Fast": "llama-3.2-3b-preview",
"Llama 3.2 (1B) - Light": "llama-3.2-1b-preview",
"Llama 3.2 (90B Text) - Powerful": "llama-3.2-90b-text-preview",
"Llama 3.2 (11B Text) - Balanced": "llama-3.2-11b-text-preview",
"Mixtral (8x7B)": "mixtral-8x7b-32768",
"Gemma 2 (9B)": "gemma2-9b-it"
}
# π― Customize this system prompt based on your bot's role
SYSTEM_PROMPT = """You are CodeMentor, a friendly and knowledgeable programming tutor.
Your role is to help users learn programming concepts, debug code, and understand different programming languages.
Key personality traits:
1. Patient and encouraging - never make users feel bad for not knowing something
2. Explain concepts clearly with simple analogies first
3. Provide practical code examples
4. When debugging, guide users to discover the solution rather than just giving the answer
5. Adapt explanations to the user's skill level
6. Include best practices and common pitfalls
7. Be enthusiastic about programming!
Always format code examples with proper syntax highlighting using markdown code blocks.
If a user asks about something non-programming related, gently steer the conversation back to programming topics."""
def query_groq_api(message: str, chat_history: List[Tuple[str, str]], model: str, temperature: float, max_tokens: int) -> str:
"""Send request to GROQ API and get response"""
if not GROQ_API_KEY:
return "β οΈ API Key not configured. Please set GROQ_API_KEY in environment variables."
headers = {
"Authorization": f"Bearer {GROQ_API_KEY}",
"Content-Type": "application/json"
}
# Build messages list
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
# Add chat history
for user_msg, bot_msg in chat_history:
messages.append({"role": "user", "content": user_msg})
messages.append({"role": "assistant", "content": bot_msg})
# Add current message
messages.append({"role": "user", "content": message})
# β
Get the actual model name from the dictionary
actual_model = MODELS.get(model, "llama-3.2-3b-preview")
# Prepare payload
payload = {
"model": actual_model,
"messages": messages,
"temperature": temperature,
"max_tokens": max_tokens,
"top_p": 0.9,
"stream": False
}
try:
response = requests.post(GROQ_API_URL, headers=headers, json=payload, timeout=30)
if response.status_code == 200:
data = response.json()
return data["choices"][0]["message"]["content"]
elif response.status_code == 404:
# β
Specific error for model not found
return f"β Error: Model '{actual_model}' not found. Available models are: {', '.join(MODELS.values())}"
else:
return f"β Error {response.status_code}: {response.text}"
except requests.exceptions.Timeout:
return "β° Request timeout. Please try again."
except requests.exceptions.RequestException as e:
return f"π« Connection error: {str(e)}"
except Exception as e:
return f"β οΈ Unexpected error: {str(e)}"
def respond(message: str, chat_history: List[Tuple[str, str]], model: str, temperature: float, max_tokens: int):
"""Process user message and return bot response"""
if not message.strip():
return "", chat_history
# Show typing indicator
chat_history.append((message, "π€ Thinking..."))
yield "", chat_history
# Get bot response
bot_reply = query_groq_api(message, chat_history[:-1], model, temperature, max_tokens)
# Replace typing indicator with actual response
chat_history[-1] = (message, bot_reply)
return "", chat_history
def clear_chat():
"""Clear chat history"""
return [], []
def update_example_questions(programming_language: str):
"""Update example questions based on selected programming language"""
examples = {
"Python": [
"Explain list comprehensions with examples",
"How do decorators work in Python?",
"What's the difference between 'is' and '=='?",
"Show me how to handle exceptions properly"
],
"JavaScript": [
"Explain promises and async/await",
"What is the event loop?",
"How does 'this' keyword work?",
"Explain closure with an example"
],
"Java": [
"Explain polymorphism with examples",
"Difference between abstract class and interface",
"How does garbage collection work?",
"What are Java Streams?"
],
"General": [
"What's the difference between SQL and NoSQL?",
"Explain REST API principles",
"What are design patterns?",
"How does Git branching work?"
]
}
return gr.update(choices=examples.get(programming_language, examples["General"]))
# Create Gradio interface
with gr.Blocks(theme=gr.themes.Soft(), title="CodeMentor - Programming Tutor") as demo:
# Store chat history in state
chat_state = gr.State([])
gr.Markdown("""
# π¨βπ» CodeMentor - Your Personal Programming Tutor
Hi! I'm CodeMentor, your friendly AI programming assistant. I can help you with:
- Learning programming concepts
- Debugging code
- Understanding different languages
- Best practices and design patterns
Select your preferences below and start asking questions!
β οΈ **Note**: Using GROQ API with free tier (limited requests per minute)
""")
with gr.Row():
with gr.Column(scale=1):
# UI Improvements
gr.Markdown("### βοΈ Settings")
# Model selection dropdown
model_dropdown = gr.Dropdown(
choices=list(MODELS.keys()),
value="Llama 3.2 (3B) - Fast",
label="Select AI Model",
info="β
Updated with correct GROQ model names"
)
# Programming language selection
language_dropdown = gr.Dropdown(
choices=["Python", "JavaScript", "Java", "C++", "General"],
value="Python",
label="Programming Language Focus",
info="Get language-specific examples"
)
# Temperature slider
temperature_slider = gr.Slider(
minimum=0.1,
maximum=1.0,
value=0.7,
step=0.1,
label="Creativity (Temperature)",
info="Lower = more focused, Higher = more creative"
)
# Response length slider
max_tokens_slider = gr.Slider(
minimum=100,
maximum=2000,
value=500,
step=100,
label="Response Length (Tokens)",
info="Maximum length of responses"
)
# Example questions dropdown
gr.Markdown("### π‘ Example Questions")
example_dropdown = gr.Dropdown(
choices=[
"Explain list comprehensions with examples",
"How do decorators work in Python?",
"What's the difference between 'is' and '=='?",
"Show me how to handle exceptions properly"
],
label="Quick Questions",
info="Select a question to ask",
allow_custom_value=True
)
# Quick action buttons
gr.Markdown("### β‘ Quick Actions")
with gr.Row():
clear_btn = gr.Button("π§Ή Clear Chat", variant="secondary", size="sm")
reset_btn = gr.Button("π Reset Settings", variant="secondary", size="sm")
with gr.Column(scale=2):
# Chat interface
chatbot = gr.Chatbot(
value=[],
label="CodeMentor",
height=500,
bubble_full_width=False
)
# Message input
msg = gr.Textbox(
placeholder="Type your programming question here... (Press Enter to send)",
label="Your Question",
lines=2
)
with gr.Row():
send_btn = gr.Button("π Send", variant="primary")
stop_btn = gr.Button("βΉοΈ Stop", variant="stop")
# Update example questions when language changes
language_dropdown.change(
fn=update_example_questions,
inputs=language_dropdown,
outputs=example_dropdown
)
# Handle example question selection
example_dropdown.change(
fn=lambda x: x,
inputs=[example_dropdown],
outputs=msg
)
# Handle message submission
msg.submit(
fn=respond,
inputs=[msg, chat_state, model_dropdown, temperature_slider, max_tokens_slider],
outputs=[msg, chatbot]
)
send_btn.click(
fn=respond,
inputs=[msg, chat_state, model_dropdown, temperature_slider, max_tokens_slider],
outputs=[msg, chatbot]
)
# Handle clear button
clear_btn.click(
fn=clear_chat,
inputs=None,
outputs=[chatbot, chat_state]
)
# Handle reset button
def reset_settings():
return [
"Llama 3.2 (3B) - Fast", # model_dropdown
"Python", # language_dropdown
0.7, # temperature_slider
500, # max_tokens_slider
"Explain list comprehensions with examples" # example_dropdown
]
reset_btn.click(
fn=reset_settings,
inputs=None,
outputs=[model_dropdown, language_dropdown, temperature_slider, max_tokens_slider, example_dropdown]
)
# Footer with troubleshooting info
gr.Markdown("""
---
### βΉοΈ About & Troubleshooting
**Powered by**: GROQ API
**Current Models Available**:
- `llama-3.2-3b-preview` (Fast, 3B parameters)
- `llama-3.2-1b-preview` (Lightweight, 1B)
- `llama-3.2-90b-text-preview` (Most powerful, 90B)
- `llama-3.2-11b-text-preview` (Balanced, 11B)
- `mixtral-8x7b-32768` (Mixture of experts)
- `gemma2-9b-it` (Google's model)
**If you see "model not found" error**:
1. Check GROQ Console for available models
2. Ensure your API key has access to the selected model
3. Try a different model from the dropdown
**Note**: Free tier has rate limits. If requests fail, wait 1 minute and try again.
""")
if __name__ == "__main__":
demo.launch(debug=False, server_name="0.0.0.0", server_port=7860) |