Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -2,41 +2,68 @@ import streamlit as st
|
|
2 |
import openai
|
3 |
import os
|
4 |
|
5 |
-
#
|
6 |
-
|
|
|
|
|
|
|
|
|
|
|
7 |
|
8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
|
10 |
-
#
|
11 |
-
|
12 |
-
st.
|
13 |
|
14 |
-
#
|
15 |
-
|
16 |
-
|
17 |
|
18 |
-
#
|
19 |
-
|
|
|
|
|
20 |
|
21 |
-
|
22 |
-
|
23 |
-
st.session_state.messages.append({"role": "user", "content": user_input})
|
24 |
|
25 |
-
|
26 |
-
|
|
|
|
|
|
|
27 |
|
28 |
-
|
29 |
-
|
30 |
-
model="gpt-3.5-turbo",
|
31 |
-
messages=messages
|
32 |
-
)
|
33 |
|
34 |
-
|
35 |
-
|
|
|
|
|
36 |
|
37 |
-
|
38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
|
40 |
-
|
41 |
-
|
42 |
-
|
|
|
2 |
import openai
|
3 |
import os
|
4 |
|
5 |
+
# Function to get the API key from Streamlit secrets
|
6 |
+
def get_api_key():
|
7 |
+
try:
|
8 |
+
return st.secrets["API_KEY"]
|
9 |
+
except KeyError:
|
10 |
+
st.error("API_KEY not found in Streamlit secrets. Please add it.")
|
11 |
+
return None
|
12 |
|
13 |
+
# Function to interact with the OpenAI API
|
14 |
+
def generate_response(prompt, model_name, api_key):
|
15 |
+
openai.api_key = api_key
|
16 |
+
try:
|
17 |
+
completion = openai.ChatCompletion.create(
|
18 |
+
model=model_name,
|
19 |
+
messages=[{"role": "user", "content": prompt}]
|
20 |
+
)
|
21 |
+
return completion.choices[0].message.content
|
22 |
+
except openai.error.OpenAIError as e:
|
23 |
+
st.error(f"Error with {model_name}: {e}")
|
24 |
+
return None
|
25 |
|
26 |
+
# Main Streamlit app
|
27 |
+
def main():
|
28 |
+
st.title("Chatbot with Model Switching")
|
29 |
|
30 |
+
# Initialize conversation history in session state
|
31 |
+
if "messages" not in st.session_state:
|
32 |
+
st.session_state.messages = []
|
33 |
|
34 |
+
# Display previous messages
|
35 |
+
for message in st.session_state.messages:
|
36 |
+
with st.chat_message(message["role"]):
|
37 |
+
st.markdown(message["content"])
|
38 |
|
39 |
+
# Get user input
|
40 |
+
prompt = st.chat_input("Say something")
|
|
|
41 |
|
42 |
+
if prompt:
|
43 |
+
# Add user message to the state
|
44 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
45 |
+
with st.chat_message("user"):
|
46 |
+
st.markdown(prompt)
|
47 |
|
48 |
+
# Define model priority
|
49 |
+
models = ["gpt-4", "gpt-3.5-turbo"] # Add more models as needed
|
|
|
|
|
|
|
50 |
|
51 |
+
# Get API key
|
52 |
+
api_key = get_api_key()
|
53 |
+
if not api_key:
|
54 |
+
return
|
55 |
|
56 |
+
response = None
|
57 |
+
for model in models:
|
58 |
+
response = generate_response(prompt, model, api_key)
|
59 |
+
if response:
|
60 |
+
break # If a response is generated, break out of loop.
|
61 |
+
|
62 |
+
if response:
|
63 |
+
# Add bot message to state
|
64 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|
65 |
+
with st.chat_message("assistant"):
|
66 |
+
st.markdown(response)
|
67 |
|
68 |
+
if __name__ == "__main__":
|
69 |
+
main()
|
|