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)