Sample_ChatBot / old_3_app.py
DanishShahzad's picture
Rename app.py to old_3_app.py
39c20e7 verified
Raw History Blame Contribute Delete
3 kB
# app.py
import streamlit as st
import json
from groq_chat import chat_with_groq
st.set_page_config(page_title="Groq Chatbot", page_icon="πŸ€–", layout="centered")
st.title("πŸ€– Groq Chatbot (Kimi)")
st.markdown("Chat with a blazing-fast Moonshot AI's Kimi model powered by Groq API.")
# Session state init
if "chat_history" not in st.session_state:
st.session_state.chat_history = []
if "system_prompt" not in st.session_state:
st.session_state.system_prompt = "You are a helpful AI assistant."
if "temperature" not in st.session_state:
st.session_state.temperature = 0.7
# Sidebar - Settings
with st.sidebar:
st.markdown("## πŸ”§ Settings")
st.session_state.temperature = st.slider("Temperature", 0.0, 1.0, st.session_state.temperature, 0.05)
st.session_state.system_prompt = st.text_area("System Prompt", value=st.session_state.system_prompt)
st.markdown("---")
# Download chat history
if st.session_state.chat_history:
chat_json = json.dumps(st.session_state.chat_history, indent=2)
st.download_button("πŸ’Ύ Download Chat", chat_json, file_name="chat_history.json", mime="application/json")
# Upload previous chat
uploaded = st.file_uploader("πŸ“‚ Load Previous Chat", type=["json"])
if uploaded:
st.session_state.chat_history = json.load(uploaded)
st.success("Chat loaded successfully.")
st.rerun()
# Switch theme (guide)
st.markdown("---")
st.info("πŸ’‘ Use βš™οΈ in top-right to change theme.")
# Clear button
if st.button("🧹 Clear Chat"):
st.session_state.chat_history = []
st.rerun()
# Display chat
for msg in st.session_state.chat_history:
avatar = "πŸ‘€" if msg["role"] == "user" else "πŸ€–"
with st.chat_message(msg["role"], avatar=avatar):
st.markdown(msg["content"])
# Chat input
prompt = st.chat_input("Type your message here...")
if prompt:
st.session_state.chat_history.append({"role": "user", "content": prompt})
with st.chat_message("user", avatar="πŸ‘€"):
st.markdown(prompt)
with st.spinner("Groq is thinking..."):
try:
response = chat_with_groq(
prompt,
history=st.session_state.chat_history,
system_prompt=st.session_state.system_prompt,
temperature=st.session_state.temperature
)
reply = response["choices"][0]["message"]["content"]
st.session_state.chat_history.append({"role": "assistant", "content": reply})
with st.chat_message("assistant", avatar="πŸ€–"):
st.markdown(reply)
# Display token usage if available
if "usage" in response:
st.sidebar.markdown(f"πŸ“Š **Tokens Used:** {response['usage']['total_tokens']}")
# Raw response toggle
with st.expander("πŸ” Raw API Response"):
st.json(response)
except Exception as e:
st.error(f"πŸ’₯ API Error: {e}")