keefereuther commited on
Commit
ad6d2ba
·
verified ·
1 Parent(s): 268f47d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +148 -0
app.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ############################################################################################################
2
+ # Importing Libraries
3
+
4
+ import streamlit as st
5
+ import hmac
6
+ import config
7
+ from openai import OpenAI
8
+
9
+ ############################################################################################################
10
+ # Password protection
11
+
12
+ def check_password():
13
+ """Returns `True` if the user had the correct password."""
14
+
15
+ def password_entered():
16
+ """Checks whether a password entered by the user is correct."""
17
+ if hmac.compare_digest(st.session_state["password"], st.secrets["password"]):
18
+ st.session_state["password_correct"] = True
19
+ del st.session_state["password"] # Don't store the password.
20
+ else:
21
+ st.session_state["password_correct"] = False
22
+
23
+ # Return True if the password is validated.
24
+ if st.session_state.get("password_correct", False):
25
+ return True
26
+
27
+ # Show input for password.
28
+ st.text_input(
29
+ "Password", type="password", on_change=password_entered, key="password"
30
+ )
31
+ if "password_correct" in st.session_state:
32
+ st.error("😕 Password incorrect")
33
+ return False
34
+
35
+ if not check_password():
36
+ st.stop() # Do not continue if check_password is not True.
37
+
38
+ ############################################################################################################
39
+ # Streamlit app layout
40
+
41
+ # Set the page to wide or centered mode
42
+ st.set_page_config(layout="wide",
43
+ page_title="Modular Chatbot",
44
+ page_icon=":lightbulb:",
45
+ initial_sidebar_state="collapsed"
46
+ )
47
+
48
+ # Streamlit app layout
49
+ # st.title(config.app_title)
50
+ # with st.expander("INSTRUCTIONS FOR STUDENTS:"):
51
+ # st.markdown(config.instructions)
52
+
53
+ ############################################################################################################
54
+
55
+
56
+ # Define a basic initial context at the beginning of your script
57
+ initial_context = {
58
+ "role": "system",
59
+ "content": config.prompt
60
+ }
61
+
62
+ # Initialize the OpenAI client
63
+ client = OpenAI(api_key=st.secrets["OPENAI_API_KEY"])
64
+
65
+ # Initialize the session state variables if they don't exist
66
+ if "openai_model" not in st.session_state:
67
+ st.session_state["openai_model"] = config.ai_model
68
+
69
+ # Corrected initialization of display_messages:
70
+ if "display_messages" not in st.session_state:
71
+ st.session_state["display_messages"] = [initial_context]
72
+
73
+ # Get user input
74
+ prompt = st.chat_input("Type your message here...")
75
+
76
+ # Input for new messages
77
+ if prompt:
78
+ # Ensure initial context is in the session state and then append user messages
79
+ if not st.session_state["display_messages"]:
80
+ st.session_state["display_messages"] = [initial_context]
81
+ st.session_state["display_messages"].append({"role": "user", "content": prompt})
82
+
83
+ # Function to reset all chat-related session state
84
+ def reset_chat_history():
85
+ st.session_state["display_messages"] = [initial_context]
86
+ st.rerun()
87
+
88
+ # Main chat container
89
+ with st.container(border=False):
90
+ # Display chat history in reverse order including new messages
91
+ for message in st.session_state["display_messages"][1:]:
92
+ if message["role"] == "user":
93
+ with st.chat_message("user"):
94
+ st.markdown(message["content"])
95
+ else:
96
+ with st.chat_message("assistant"):
97
+ st.markdown(message["content"])
98
+
99
+ # Generate assistant's response and add it to the messages
100
+ if prompt:
101
+ with st.chat_message("assistant"):
102
+ try:
103
+ stream = client.chat.completions.create(
104
+ model=st.session_state["openai_model"],
105
+ messages=[
106
+ {"role": m["role"], "content": m["content"]}
107
+ for m in st.session_state["display_messages"]
108
+ ],
109
+ stream=True,
110
+ temperature=config.temperature,
111
+ max_tokens=config.max_tokens,
112
+ frequency_penalty=config.frequency_penalty,
113
+ presence_penalty=config.presence_penalty,
114
+ )
115
+
116
+ # Initialize an empty string to store the full response
117
+ full_response = ""
118
+ message_placeholder = st.empty()
119
+
120
+ # Iterate through the stream to get each chunk
121
+ for chunk in stream:
122
+ if chunk.choices[0].delta.content is not None:
123
+ full_response += chunk.choices[0].delta.content
124
+ message_placeholder.markdown(full_response + "▌")
125
+
126
+ # Replace the placeholder with the complete message
127
+ message_placeholder.markdown(full_response)
128
+
129
+ # Append the full response to the session state for display
130
+ st.session_state["display_messages"].append(
131
+ {"role": "assistant", "content": full_response}
132
+ )
133
+ except Exception as e:
134
+ st.error(f"An error occurred: {str(e)}")
135
+
136
+ # Create a sidebar
137
+ with st.sidebar:
138
+ st.markdown(config.warning_message, unsafe_allow_html=True)
139
+
140
+ # Add Clear Chat History button to sidebar
141
+ if st.button("Clear Chat History"):
142
+ reset_chat_history()
143
+
144
+ # Add license link with markdown
145
+ st.markdown("---") # Separator line
146
+ st.markdown("""
147
+ <small>Licensed under [GNU GPL v3.0](https://www.gnu.org/licenses/gpl-3.0.en.html)</small>
148
+ """, unsafe_allow_html=True)