Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import openai
|
3 |
+
import os
|
4 |
+
|
5 |
+
# Set the OpenAI API key from Hugging Face Secrets
|
6 |
+
openai.api_key = os.getenv('API_KEY')
|
7 |
+
|
8 |
+
st.title("ChatGPT-powered Chatbot")
|
9 |
+
|
10 |
+
# Initialize session state to store the conversation
|
11 |
+
if 'messages' not in st.session_state:
|
12 |
+
st.session_state.messages = []
|
13 |
+
|
14 |
+
# Display previous messages
|
15 |
+
for message in st.session_state.messages:
|
16 |
+
st.write(f"**{message['role'].capitalize()}:** {message['content']}")
|
17 |
+
|
18 |
+
# Input for user message
|
19 |
+
user_input = st.text_input("You:", "")
|
20 |
+
|
21 |
+
if user_input:
|
22 |
+
# Add user message to session state
|
23 |
+
st.session_state.messages.append({"role": "user", "content": user_input})
|
24 |
+
|
25 |
+
# Prepare messages for API call
|
26 |
+
messages = [{"role": msg["role"], "content": msg["content"]} for msg in st.session_state.messages]
|
27 |
+
|
28 |
+
# Call OpenAI API
|
29 |
+
response = openai.ChatCompletion.create(
|
30 |
+
model="gpt-3.5-turbo",
|
31 |
+
messages=messages
|
32 |
+
)
|
33 |
+
|
34 |
+
# Get assistant's reply
|
35 |
+
assistant_reply = response['choices'][0]['message']['content']
|
36 |
+
|
37 |
+
# Add assistant's reply to session state
|
38 |
+
st.session_state.messages.append({"role": "assistant", "content": assistant_reply})
|
39 |
+
|
40 |
+
# Display assistant's reply
|
41 |
+
st.write(f"**Assistant:** {assistant_reply}")
|