Spaces:
Running
Running
| 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']}") |