| import gradio as gr |
| import os |
| import requests |
| import json |
| from typing import List, Tuple |
|
|
| |
| GROQ_API_KEY = os.environ.get("GROQ_API_KEY") |
| GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions" |
|
|
| |
| MODELS = { |
| "Llama 3 (8B) - Fast": "llama3-8b-8192", |
| "Llama 3 (70B) - Powerful": "llama3-70b-8192", |
| "Mixtral (8x7B) - Balanced": "mixtral-8x7b-32768" |
| } |
|
|
| |
| 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" |
| } |
| |
| |
| messages = [{"role": "system", "content": SYSTEM_PROMPT}] |
| |
| |
| for user_msg, bot_msg in chat_history: |
| messages.append({"role": "user", "content": user_msg}) |
| messages.append({"role": "assistant", "content": bot_msg}) |
| |
| |
| messages.append({"role": "user", "content": message}) |
| |
| |
| 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 |
| |
| |
| bot_reply = query_groq_api(message, chat_history, model, temperature, max_tokens) |
| |
| |
| 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"]) |
|
|
| |
| with gr.Blocks(theme=gr.themes.Soft(), title="CodeMentor - Programming Tutor") as demo: |
| |
| |
| 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): |
| |
| gr.Markdown("### ⚙️ Settings") |
| |
| |
| model_dropdown = gr.Dropdown( |
| choices=list(MODELS.keys()), |
| value="Llama 3 (8B) - Fast", |
| label="Select AI Model", |
| info="Choose the model for responses" |
| ) |
| |
| |
| language_dropdown = gr.Dropdown( |
| choices=["Python", "JavaScript", "Java", "C++", "General"], |
| value="Python", |
| label="Programming Language Focus", |
| info="Get language-specific examples" |
| ) |
| |
| |
| 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" |
| ) |
| |
| |
| max_tokens_slider = gr.Slider( |
| minimum=100, |
| maximum=2000, |
| value=500, |
| step=100, |
| label="Response Length (Tokens)", |
| info="Maximum length of responses" |
| ) |
| |
| |
| 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_btn = gr.Button("🧹 Clear Chat", variant="secondary") |
| |
| with gr.Column(scale=2): |
| |
| chatbot = gr.Chatbot( |
| value=[], |
| label="CodeMentor", |
| height=500, |
| bubble_full_width=False |
| ) |
| |
| |
| msg = gr.Textbox( |
| placeholder="Type your programming question here... (Press Enter to send)", |
| label="Your Question", |
| lines=2 |
| ) |
| |
| |
| send_btn = gr.Button("🚀 Send", variant="primary") |
| |
| |
| language_dropdown.change( |
| fn=update_example_questions, |
| inputs=language_dropdown, |
| outputs=example_questions |
| ) |
| |
| |
| example_questions.click( |
| fn=lambda x: x, |
| inputs=[example_questions], |
| outputs=msg |
| ) |
| |
| |
| 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] |
| ) |
| |
| |
| clear_btn.click( |
| fn=clear_chat, |
| inputs=None, |
| outputs=[chatbot, chat_state] |
| ) |
| |
| |
| 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) |