File size: 1,888 Bytes
9bfae5f
1542d75
9bfae5f
618f204
a4c1f18
 
 
 
 
 
1542d75
9bfae5f
1542d75
 
 
 
 
618f204
2ee0a75
1542d75
2ee0a75
 
 
1542d75
2ee0a75
 
1542d75
 
 
 
 
 
 
 
 
2ee0a75
 
 
 
 
1542d75
 
 
2ee0a75
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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']}")