Spaces:
Runtime error
Runtime error
add app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from streamlit_chat import message
|
| 3 |
+
|
| 4 |
+
import openai
|
| 5 |
+
from config import open_api_key
|
| 6 |
+
openai.api_key = st.secrets["db_username"]
|
| 7 |
+
|
| 8 |
+
# openAI code
|
| 9 |
+
def openai_create(prompt):
|
| 10 |
+
response = openai.Completion.create(
|
| 11 |
+
model="text-davinci-003",
|
| 12 |
+
prompt=prompt,
|
| 13 |
+
temperature=0.9,
|
| 14 |
+
max_tokens=1000,
|
| 15 |
+
top_p=1,
|
| 16 |
+
frequency_penalty=0,
|
| 17 |
+
presence_penalty=0.6,
|
| 18 |
+
stop=[" Human:", " AI:"]
|
| 19 |
+
)
|
| 20 |
+
return response.choices[0].text
|
| 21 |
+
|
| 22 |
+
# Streamlit App
|
| 23 |
+
st.set_page_config(
|
| 24 |
+
page_title="Streamlit Chat - Demo",
|
| 25 |
+
page_icon=":robot:"
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
# st.header("GPT 3.5 with Streamlit\nChatGPT API即将到来")
|
| 29 |
+
|
| 30 |
+
if 'generated' not in st.session_state:
|
| 31 |
+
st.session_state['generated'] = []
|
| 32 |
+
|
| 33 |
+
if 'past' not in st.session_state:
|
| 34 |
+
st.session_state['past'] = []
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def get_text():
|
| 38 |
+
input_text = st.text_input("You: ", key="input")
|
| 39 |
+
return input_text
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
user_input = get_text()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
if user_input:
|
| 46 |
+
prompt = 'The following is a conversation with an AI assistant. The assistant is helpful, creative, clever, and very friendly.'
|
| 47 |
+
if st.session_state['generated']:
|
| 48 |
+
for past, generated in zip(st.session_state['past'], st.session_state['generated']):
|
| 49 |
+
if len(generated)>0:
|
| 50 |
+
prompt += f'\nHuman:{past}\nAI:{generated}'
|
| 51 |
+
prompt += f'\nHuman:{user_input}\nAI:'
|
| 52 |
+
logger.info(prompt)
|
| 53 |
+
output = openai_create(prompt)
|
| 54 |
+
logger.info(f'{user_input} -> {output}')
|
| 55 |
+
st.session_state.past.append(user_input)
|
| 56 |
+
st.session_state.generated.append(output)
|
| 57 |
+
|
| 58 |
+
if st.session_state['generated']:
|
| 59 |
+
for i in range(len(st.session_state['generated'])-1, -1, -1):
|
| 60 |
+
message(st.session_state["generated"][i], key=str(i))
|
| 61 |
+
message(st.session_state['past'][i], is_user=True, key=str(i) + '_user')
|