Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from streamlit_chat import message # For chat bubble UI
|
3 |
+
import openai
|
4 |
+
|
5 |
+
# Load API key securely
|
6 |
+
API_KEY = os.getenv("NV_API_KEY", "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")
|
7 |
+
if not API_KEY:
|
8 |
+
st.error("API key is missing! Please set NV_API_KEY as an environment variable.")
|
9 |
+
st.stop()
|
10 |
+
|
11 |
+
client = OpenAI(
|
12 |
+
base_url="https://integrate.api.nvidia.com/v1",
|
13 |
+
api_key=API_KEY
|
14 |
+
)
|
15 |
+
|
16 |
+
# Initialize the conversation history
|
17 |
+
if "messages" not in st.session_state:
|
18 |
+
st.session_state.messages = [{"role": "assistant", "content": "Hi! I'm your chatbot. How can I assist you today?"}]
|
19 |
+
|
20 |
+
# Function to get a response from OpenAI
|
21 |
+
def get_chatbot_response(user_input):
|
22 |
+
try:
|
23 |
+
response = openai.ChatCompletion.create(
|
24 |
+
model="gpt-3.5-turbo", # Use GPT-4 if you have access for better responses
|
25 |
+
messages=st.session_state.messages + [{"role": "user", "content": user_input}],
|
26 |
+
)
|
27 |
+
return response['choices'][0]['message']['content']
|
28 |
+
except Exception as e:
|
29 |
+
return f"Error: {str(e)}"
|
30 |
+
|
31 |
+
# App layout
|
32 |
+
st.set_page_config(page_title="ChatGPT-like Chatbot", page_icon="🤖", layout="wide")
|
33 |
+
st.title("ChatGPT-like Chatbot 🤖")
|
34 |
+
|
35 |
+
# Display the chat conversation
|
36 |
+
for msg in st.session_state.messages:
|
37 |
+
if msg["role"] == "assistant":
|
38 |
+
message(msg["content"], is_user=False, key=f"assistant_{msg['content']}")
|
39 |
+
else:
|
40 |
+
message(msg["content"], is_user=True, key=f"user_{msg['content']}")
|
41 |
+
|
42 |
+
# User input section
|
43 |
+
user_input = st.text_input(
|
44 |
+
"Type your message:", key="user_input", placeholder="Type here and press Enter..."
|
45 |
+
)
|
46 |
+
|
47 |
+
if user_input:
|
48 |
+
# Append user message to session state
|
49 |
+
st.session_state.messages.append({"role": "user", "content": user_input})
|
50 |
+
|
51 |
+
# Get chatbot response
|
52 |
+
chatbot_response = get_chatbot_response(user_input)
|
53 |
+
|
54 |
+
# Append chatbot response to session state
|
55 |
+
st.session_state.messages.append({"role": "assistant", "content": chatbot_response})
|
56 |
+
|
57 |
+
# Clear the input field
|
58 |
+
st.session_state.user_input = ""
|