import os from dotenv import load_dotenv import gradio as gr from groq import Groq load_dotenv() GROQ_API_KEY = os.getenv("GROQ_API_KEY") client = Groq(api_key=GROQ_API_KEY) if GROQ_API_KEY else None def chatbot_response(user_input, action, language, conversation_history, name, proficiency_level): if not client: error_msg = "โš ๏ธ Error: Missing GROQ_API_KEY. Please check your .env file." conversation_history.append((user_input, error_msg)) return conversation_history system_message = f"""You are a {language} tutor for {name or 'a student'} ({proficiency_level} level). Provide personalized, level-appropriate responses. Use their name occasionally. If the user doesn't enter their name don't use it. For games, maintain context until completion. Acknowledge different dialects where relevant. **Important**: The user is communicating via text - focus on written errors. Only provide pronunciation help if explicitly requested. When correcting errors: 1. Clearly indicate the error with ๐ŸšจError Alret๐Ÿšจ 2. Explain why it's incorrect 3. Provide the correct version 4. Offer a brief practice example""" if action == "vocabulary": user_message = f"Provide 5 {language} vocabulary words for {proficiency_level} learners." elif action == "grammar": user_message = f"Explain a {language} grammar concept suitable for {proficiency_level} learners." elif action == "conversation": user_message = f"Start a {language} conversation practice. First offer 3 topic choices." elif action == "game": user_message = f"Create an interactive {language} language game for {proficiency_level} learners. Maintain game context." else: user_message = user_input conversation_history.append((user_message, "")) try: messages = [{"role": "system", "content": system_message}] for msg, response in conversation_history: messages.append({"role": "user", "content": msg}) if response: messages.append({"role": "assistant", "content": response.replace(f"**{language} Tutor:** ", "")}) completion = client.chat.completions.create( model="llama-3.3-70b-versatile", messages=messages, temperature=0.7, max_tokens=2000, stream=True, ) chatbot_message = "" for chunk in completion: if chunk.choices[0].delta.content: chatbot_message += chunk.choices[0].delta.content conversation_history[-1] = (user_message, f"**{language} Tutor:** {chatbot_message}") yield conversation_history except Exception as e: error_msg = f"โš ๏ธ Error: {str(e)}. Please try again or reload." conversation_history[-1] = (user_message, f"**{language} Tutor:** {error_msg}") yield conversation_history def clear_chat(): return [], [] with gr.Blocks(theme=gr.themes.Default(primary_hue="green")) as demo: gr.Markdown("# ๐ŸŒ Multi-Language Learning Buddy") gr.Markdown("Welcome! Practice vocabulary, grammar, conversation, and play language games in multiple languages.") with gr.Row(): language = gr.Dropdown(["French", "Spanish", "German", "Italian", "Portuguese"], label="Language", value="French") proficiency = gr.Dropdown(["Beginner", "Intermediate", "Advanced"], label="Your Level", value="Beginner") name = gr.Textbox(label="Your Name", placeholder="Enter your name...") chatbot = gr.Chatbot(height=500) conversation_history = gr.State([]) with gr.Row(): user_input = gr.Textbox(placeholder="Type here or choose an activity below...", show_label=False) send_btn = gr.Button("Send", variant="primary") with gr.Row(): vocab_btn = gr.Button("๐Ÿ“š Daily Vocabulary") grammar_btn = gr.Button("๐Ÿ“– Grammar Lesson") conv_btn = gr.Button("๐Ÿ’ฌ Practice Conversation") game_btn = gr.Button("๐ŸŽฎ Language Game") clear_btn = gr.Button("๐Ÿ”„ Clear Chat") input_components = [user_input, gr.State("chat"), language, conversation_history, name, proficiency] send_btn.click( chatbot_response, inputs=input_components, outputs=chatbot ).then(lambda: "", None, user_input) user_input.submit( chatbot_response, inputs=input_components, outputs=chatbot ).then(lambda: "", None, user_input) action_btns = [vocab_btn, grammar_btn, conv_btn, game_btn] for btn, action in zip(action_btns, ["vocabulary", "grammar", "conversation", "game"]): btn.click( chatbot_response, inputs=[gr.State(""), gr.State(action)] + input_components[2:], outputs=chatbot ) clear_btn.click( clear_chat, outputs=[chatbot, conversation_history], ) if __name__ == "__main__": if not GROQ_API_KEY: print("โŒ Error: GROQ_API_KEY missing. Create a .env file with your key.") else: demo.launch()