Chatbot / app.py
saherPervaiz's picture
Update app.py
4874a99 verified
raw
history blame
2.29 kB
import os
import streamlit as st
from groq import Groq
# Initialize Groq client
API_KEY = os.getenv("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") # Ensure GROQ_API_KEY is set in your environment variables
if not API_KEY:
st.error("API key is missing. Please set the GROQ_API_KEY environment variable.")
st.stop()
client = Groq(api_key=API_KEY)
# Streamlit app configuration
st.set_page_config(page_title="AI Chatbot", page_icon="🤖", layout="wide")
st.title("AI-Powered Chatbot with Groq")
# Sidebar for user input
st.sidebar.header("Chatbot Settings")
chat_model = st.sidebar.selectbox("Select AI Model", ["llama-3.3-70b-versatile", "llama-2.0-50b-creative"])
# Chat interface
st.write("## Chat with AI")
if "messages" not in st.session_state:
st.session_state.messages = []
# Display conversation history
for msg in st.session_state.messages:
if msg["role"] == "user":
st.write(f"**You:** {msg['content']}")
else:
st.write(f"**AI:** {msg['content']}")
# User input for the chatbot
user_input = st.text_input("Enter your message:", key="user_input")
# On submit, process the input
if st.button("Send"):
if user_input:
# Add user input to the chat history
st.session_state.messages.append({"role": "user", "content": user_input})
# Call Groq API
with st.spinner("Thinking..."):
try:
chat_completion = client.chat.completions.create(
messages=st.session_state.messages,
model=chat_model,
)
ai_response = chat_completion.choices[0].message.content
# Add AI response to the chat history
st.session_state.messages.append({"role": "assistant", "content": ai_response})
# Display the AI's response
st.write(f"**AI:** {ai_response}")
except Exception as e:
st.error(f"Error: {e}")
else:
st.warning("Please enter a message before sending.")
# Clear conversation button
if st.button("Clear Conversation"):
st.session_state.messages = []
# Footer
st.markdown("""
---
Powered by [Groq](https://groq.com) | Deployed on [Hugging Face Spaces](https://huggingface.co/spaces)
""")