import streamlit as st from groq import Groq import os from dotenv import load_dotenv # 🔐 Load .env file load_dotenv() # 🔐 Get API key safely api_key = os.getenv("GROQ_API_KEY") # ❌ Safety check (IMPORTANT) if not api_key: st.error("GROQ_API_KEY not found. Please check your .env file.") st.stop() # 🤖 Create Groq client client = Groq(api_key=api_key) # 🔤 Manual Tokenizer def manual_tokenizer(text): text = text.lower() text = text.replace(".", "").replace(",", "").replace("!", "").replace("?", "") return text.split() # 💬 Chat function def chat_with_groq(user_input, messages): tokens = manual_tokenizer(user_input) processed_text = " ".join(tokens) messages.append({"role": "user", "content": processed_text}) response = client.chat.completions.create( model="llama-3.1-8b-instant", messages=messages ) reply = response.choices[0].message.content messages.append({"role": "assistant", "content": reply}) return reply # 🎨 Streamlit UI st.set_page_config(page_title="Chatbot", page_icon="💬") st.title("💬 AI Chatbot (Groq + Streamlit)") # 🧠 Session memory if "messages" not in st.session_state: st.session_state.messages = [ {"role": "system", "content": "You are a helpful chatbot."} ] # 💬 Input box user_input = st.text_input("You:") if st.button("Send") and user_input: reply = chat_with_groq(user_input, st.session_state.messages) # 📜 Display chat history for msg in st.session_state.messages[1:]: if msg["role"] == "user": st.write(f"👤 You: {msg['content']}") else: st.write(f"🤖 Bot: {msg['content']}")