Groq_trail / app.py
Sameer1234567's picture
Update app.py
e6f65d5 verified
import streamlit as st
import os
from groq import Groq
# Load the API key from Hugging Face's secrets
api_key = st.secrets["GROQ_API_KEY"] # Access the API key stored in Secrets
if not api_key:
st.error("API key not found in the Hugging Face secrets.")
st.stop()
# Initialize the Groq client
client = Groq(api_key=api_key)
# Streamlit app
st.title("GroqCloud Chatbot")
# Initialize chat messages in session state
if "messages" not in st.session_state:
st.session_state.messages = []
chat_container = st.container()
with chat_container:
for message in st.session_state.messages:
role = "You" if message["role"] == "user" else "AI"
st.markdown(f"**{role}:** {message['content']}")
# A function to handle sending the message
def send_message():
user_input = st.session_state.user_input.strip()
if user_input:
# Add user's message to the chat history
st.session_state.messages.append({"role": "user", "content": user_input})
# Update the chat container to show the user's message immediately
with chat_container:
st.markdown(f"**You:** {user_input}")
# Call the GroqCloud API to get the AI response
try:
chat_completion = client.chat.completions.create(
messages=st.session_state.messages,
model="deepseek-r1-distill-llama-70b",
)
# Append the AI's response to the chat history
assistant_response = chat_completion.choices[0].message.content
st.session_state.messages.append({"role": "assistant", "content": assistant_response})
# Update the chat container with the AI's response
with chat_container:
st.markdown(f"**AI:** {assistant_response}")
except Exception as e:
st.error(f"An error occurred: {str(e)}")
# Clear the input field after sending the message
st.session_state.user_input = "" # Clear the message input
# Using st.form to handle message submission with a button or Enter key
with st.form("chat_form", clear_on_submit=True):
user_input = st.text_input("Your message:", key="user_input", placeholder="Type your message here...")
# Form submit button that triggers sending the message
send_button = st.form_submit_button("Send", on_click=send_message)
# Add a "Clear Chat" button
if st.button("Clear Chat"):
st.session_state.messages = [] # Clear the chat history
chat_container.empty() # Clear the chat container