grok_chatbot / app.py
Memoona648's picture
Update app.py
c633fc3 verified
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']}")