File size: 2,055 Bytes
8bb6db3
 
 
 
e1249d6
8bb6db3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19f9fc7
8bb6db3
 
93fdaa7
19f9fc7
8bb6db3
d940f8a
4bb4836
0527ae9
 
 
 
 
 
 
 
 
 
 
 
 
8bb6db3
0527ae9
 
 
d940f8a
9d3b0bb
 
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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'])