abubakaraabi786's picture
Back to Version 3
adcbb92 verified
raw
history blame
11.3 kB
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)