File size: 1,827 Bytes
34eaf06
 
 
 
bc6f217
 
5d863e9
34eaf06
bc6f217
 
 
5d863e9
bc6f217
34eaf06
bc6f217
34eaf06
bc6f217
34eaf06
bc6f217
 
 
 
5d863e9
 
 
 
bc6f217
5d863e9
 
 
bc6f217
 
 
 
d412f15
bc6f217
 
 
 
 
 
 
5d863e9
 
 
 
 
bc6f217
 
 
 
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
import openai 
import streamlit as st
import json

if 'exchanges' not in st.session_state:
    st.session_state.exchanges = []
    #st.session_state.exchanges = [{"role": "system", "content": "You are a chatbot."}]

def exchange_with_chatbot(prompt):
    st.session_state.exchanges.append({"role": "user", "content": prompt})
    # limit to 10 exchanges to save cost
    ex = st.session_state.exchanges if len(st.session_state.exchanges)<10 else st.session_state.exchanges[len(st.session_state.exchanges)-10:]    
    response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages= ex,
            max_tokens=1000,
            temperature=0.7
        )
    return response

def format_exchanges(exchanges):
    for i in range(len(exchanges)):
        if exchanges[i]["role"] == "user":
            icon, text, blank = st.columns([1,8,1])
        elif exchanges[i]["role"] == "assistant":
            blank, text, icon = st.columns([1,8,1])
        else:
            st.markdown("*" + exchanges[i]["role"] + ":* " + exchanges[i]["content"]) 
            continue
        
        with icon:
            st.image("icon_" + exchanges[i]["role"] + ".png", width=50)
        with text:
            st.markdown(exchanges[i]["content"])
        st.markdown("""---""")

openai.api_key = st.secrets["OPENAI_API_KEY"]

if openai.api_key:
    st.text_input("Prompt", placeholder="Ask me anything", key="prompt")
    
if st.session_state.prompt:
    try:
        response = exchange_with_chatbot(st.session_state.prompt)
    except Exception as e:
        st.error(e) 
        st.stop()
    json_object = json.loads(str(response))
    st.session_state.exchanges.append({"role": "assistant", "content": json_object['choices'][0]['message']['content']})
    format_exchanges(st.session_state.exchanges)