generated from dataprofessor/openai-chatbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
streamlit_app.py
38 lines (33 loc) · 1.54 KB
/
streamlit_app.py
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
# Code refactored from https://docs.streamlit.io/knowledge-base/tutorials/build-conversational-apps
import openai
import streamlit as st
with st.sidebar:
st.title('🤖💬 OpenAI Chatbot')
if 'OPENAI_API_KEY' in st.secrets:
st.success('API key already provided!', icon='✅')
openai.api_key = st.secrets['OPENAI_API_KEY']
else:
openai.api_key = st.text_input('Enter OpenAI API token:', type='password')
if not (openai.api_key.startswith('sk-') and len(openai.api_key) == 51):
st.warning('Please enter your credentials!', icon='⚠️')
else:
st.success('Proceed to entering your prompt message!', icon='👉')
if "messages" not in st.session_state:
st.session_state.messages = []
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
if prompt := st.chat_input("What is up?"):
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)
with st.chat_message("assistant"):
message_placeholder = st.empty()
full_response = ""
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": m["role"], "content": m["content"]} for m in st.session_state.messages]
)
full_response = response.choices[0].message["content"]
message_placeholder.markdown(full_response)
st.session_state.messages.append({"role": "assistant", "content": full_response})