Spaces:
Runtime error
Runtime error
import streamlit as st | |
from streamlit_chat import message | |
import openai | |
openai.api_key = st.secrets["open_api_key"] | |
# openAI code | |
def openai_create(prompt): | |
response = openai.Completion.create( | |
model="text-davinci-003", | |
prompt=prompt, | |
temperature=0.9, | |
max_tokens=1000, | |
top_p=1, | |
frequency_penalty=0, | |
presence_penalty=0.6, | |
stop=[" Human:", " AI:"] | |
) | |
return response.choices[0].text | |
# Streamlit App | |
st.set_page_config( | |
page_title="Streamlit Chat - Demo", | |
page_icon=":robot:" | |
) | |
# st.header("GPT 3.5 with Streamlit\nChatGPT API即将到来") | |
if 'generated' not in st.session_state: | |
st.session_state['generated'] = [] | |
if 'past' not in st.session_state: | |
st.session_state['past'] = [] | |
def get_text(): | |
input_text = st.text_input("You: ", key="input0") | |
return input_text | |
if 'key' not in st.session_state: | |
st.session_state['key'] = st.text_input("key: ", key="input1") | |
elif st.session_state['key'] == st.secrets["login_key"]: | |
user_input = get_text() | |
if user_input: | |
prompt = 'The following is a conversation with an AI assistant. The assistant is helpful, creative, clever, and very friendly.' | |
if st.session_state['generated']: | |
for past, generated in zip(st.session_state['past'], st.session_state['generated']): | |
if len(generated)>0: | |
prompt += f'\nHuman:{past}\nAI:{generated}' | |
prompt += f'\nHuman:{user_input}\nAI:' | |
print(prompt) | |
output = openai_create(prompt) | |
print(f'{user_input} -> {output}') | |
st.session_state.past.append(user_input) | |
st.session_state.generated.append(output) | |
if st.session_state['generated']: | |
for i in range(len(st.session_state['generated'])-1, -1, -1): | |
message(st.session_state["generated"][i], key=str(i)) | |
message(st.session_state['past'][i], is_user=True, key=str(i) + '_user') | |
elif st.session_state['key'] != st.secrets["login_key"]: | |
st.warning('wrong key!') | |
print(st.session_state['key']) |