import os import streamlit as st from groq import Groq # Fetch the Groq API key from environment variables set in Hugging Face Space GROQ_API_KEY = os.environ.get("GROQ_API_KEY") if not GROQ_API_KEY: st.error("Error: GROQ_API_KEY environment variable is not set.") st.stop() # Stop execution if API key is not found # Initialize Groq client try: client = Groq(api_key=GROQ_API_KEY) except Exception as e: st.error(f"Error initializing Groq client: {e}") st.stop() # Stop execution if client initialization fails def get_response(prompt, chat_history): try: # Include chat history in the request messages = [{"role": "user", "content": msg["user"]} if "user" in msg else {"role": "assistant", "content": msg["bot"]} for msg in chat_history] messages.append({"role": "user", "content": prompt}) chat_completion = client.chat.completions.create( messages=messages, model="llama-3.3-70b-versatile" # Or any other available model ) return chat_completion.choices[0].message.content except Exception as e: st.error(f"Error generating response: {e}") return "An error occurred while generating the response." # Streamlit app layout st.title("Interactive Chatbot") # Initialize session state for chat history if "chat_history" not in st.session_state: st.session_state.chat_history = [] # Input box for user message user_input = st.text_input("You: ", key="user_input") if user_input: # Get bot response bot_response = get_response(user_input, st.session_state.chat_history) # Append to chat history st.session_state.chat_history.append({"user": user_input, "bot": bot_response}) # Display chat history st.subheader("Conversation") for chat in st.session_state.chat_history: st.write(f"You: {chat['user']}") st.write(f"Bot: {chat['bot']}")