File size: 8,979 Bytes
4bad81b | 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 | import gradio as gr
import os
import requests
import json
from typing import List, Tuple
# 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"
# Available models
MODELS = {
"Llama 3 (8B) - Fast": "llama3-8b-8192",
"Llama 3 (70B) - Powerful": "llama3-70b-8192",
"Mixtral (8x7B) - Balanced": "mixtral-8x7b-32768"
}
# π― 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})
# Prepare payload
payload = {
"model": 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)
if response.status_code == 200:
data = response.json()
return data["choices"][0]["message"]["content"]
else:
return f"β Error {response.status_code}: {response.text}"
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
# Get bot response
bot_reply = query_groq_api(message, chat_history, model, temperature, max_tokens)
# Add to chat history
chat_history.append((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 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!
""")
with gr.Row():
with gr.Column(scale=1):
# UI Improvements (as required in assignment)
gr.Markdown("### βοΈ Settings")
# Model selection dropdown
model_dropdown = gr.Dropdown(
choices=list(MODELS.keys()),
value="Llama 3 (8B) - Fast",
label="Select AI Model",
info="Choose the model for responses"
)
# 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 based on selected language
gr.Markdown("### π‘ Try These Questions")
example_questions = gr.Dataset(
components=[gr.Textbox(visible=False)],
samples=update_example_questions("Python"),
label="Click a question to ask:",
type="index"
)
# Clear button
clear_btn = gr.Button("π§Ή Clear Chat", variant="secondary")
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
)
# Send button
send_btn = gr.Button("π Send", variant="primary")
# Update example questions when language changes
language_dropdown.change(
fn=update_example_questions,
inputs=language_dropdown,
outputs=example_questions
)
# Handle example question clicks
example_questions.click(
fn=lambda x: x,
inputs=[example_questions],
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]
)
# Footer
gr.Markdown("""
---
### βΉοΈ About
- **Powered by**: GROQ API with Llama 3
- **Theme**: Programming Tutor
- **UI Features**: Model selection, language focus, temperature control, response length slider
- **Deployed on**: Hugging Face Spaces
β οΈ Note: This is an educational tool. Always verify critical code before production use.
""")
if __name__ == "__main__":
demo.launch(debug=False) |