import streamlit as st import os from groq import Groq # ----------------------- # PAGE CONFIG # ----------------------- st.set_page_config( page_title="Krish AI Chatbot 🤖", page_icon="🤖", layout="centered" ) # ----------------------- # MOBILE RESPONSIVE UI 🔥 # ----------------------- st.markdown(""" """, unsafe_allow_html=True) # ----------------------- # HEADER # ----------------------- st.markdown('
💬 Krish AI Chatbot
', unsafe_allow_html=True) st.markdown('
Smart, Fast & Beautiful AI Chat 🚀
', unsafe_allow_html=True) # ----------------------- # API KEY (Secrets + fallback) # ----------------------- api_key = os.getenv("GROQ_API_KEY") if not api_key: api_key = st.sidebar.text_input("Enter Groq API Key 🔑", type="password") if not api_key: st.warning("Please enter your Groq API key") st.stop() client = Groq(api_key=api_key) # ----------------------- # MODEL # ----------------------- MODEL = "llama-3.1-8b-instant" # ----------------------- # SESSION STATE # ----------------------- if "messages" not in st.session_state: st.session_state.messages = [] # ----------------------- # DISPLAY CHAT # ----------------------- for msg in st.session_state.messages: if msg["role"] == "user": st.markdown(f"""
{msg["content"]}
""", unsafe_allow_html=True) else: st.markdown(f"""
{msg["content"]}
""", unsafe_allow_html=True) # ----------------------- # INPUT # ----------------------- user_input = st.chat_input("Type your message...") if user_input: # Save user message st.session_state.messages.append({"role": "user", "content": user_input}) # Show instantly st.markdown(f"""
{user_input}
""", unsafe_allow_html=True) # Placeholder for streaming placeholder = st.empty() full_response = "" try: stream = client.chat.completions.create( model=MODEL, messages=st.session_state.messages, stream=True ) for chunk in stream: content = chunk.choices[0].delta.content or "" full_response += content placeholder.markdown(f"""
{full_response}▌
""", unsafe_allow_html=True) # Final message placeholder.markdown(f"""
{full_response}
""", unsafe_allow_html=True) # Save st.session_state.messages.append( {"role": "assistant", "content": full_response} ) except Exception as e: st.error(f"Error: {e}")