artintel235 commited on
Commit
cdabcae
·
verified ·
1 Parent(s): d72bbc5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -46
app.py CHANGED
@@ -1,56 +1,78 @@
1
  import streamlit as st
2
  import openai
 
3
 
4
- # Set up the OpenAI API key
5
- openai.api_key = st.secrets['API_KEY']
6
-
7
- # Define the models in order of preference
8
- MODELS = ["gpt-4", "gpt-3.5-turbo", "gpt-3.5-turbo-16k"]
9
-
10
- # Initialize session state to store conversation history
11
- if "conversation" not in st.session_state:
12
- st.session_state.conversation = []
13
 
14
- # Function to get a response from the OpenAI API
15
- def get_chat_response(prompt, model_index=0):
 
16
  try:
17
- response = openai.ChatCompletion.create(
18
- model=MODELS[model_index],
19
  messages=[{"role": "user", "content": prompt}]
20
  )
21
- return response.choices[0].message['content']
22
- except openai.error.RateLimitError:
23
- if model_index + 1 < len(MODELS):
24
- st.warning(f"Quota exceeded for {MODELS[model_index]}. Switching to {MODELS[model_index + 1]}.")
25
- return get_chat_response(prompt, model_index + 1)
26
- else:
27
- st.error("All models have exceeded their quota. Please try again later.")
28
- return None
29
- except Exception as e:
30
- st.error(f"An error occurred: {e}")
31
  return None
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
- # Streamlit UI
34
- st.title("ChatGPT with Model Fallback")
35
-
36
- # Display previous conversation
37
- st.write("### Conversation History")
38
- for message in st.session_state.conversation:
39
- st.write(f"**{message['role']}**: {message['content']}")
40
-
41
- # User input
42
- user_input = st.text_input("You: ", "")
43
-
44
- if user_input:
45
- # Add user input to conversation history
46
- st.session_state.conversation.append({"role": "User", "content": user_input})
47
-
48
- # Get response from the model
49
- response = get_chat_response(user_input)
50
-
51
- if response:
52
- # Add model response to conversation history
53
- st.session_state.conversation.append({"role": "Assistant", "content": response})
 
 
 
 
 
 
 
 
 
 
54
 
55
- # Display the response
56
- st.write(f"**Assistant**: {response}")
 
 
 
 
 
 
 
1
  import streamlit as st
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.APIError as e: # General API Error
23
+ st.error(f"OpenAI API Error with {model_name}: {e}")
 
 
 
 
 
 
 
24
  return None
25
+ except openai.RateLimitError as e: # Rate Limit Error
26
+ st.error(f"OpenAI Rate Limit Error with {model_name}: {e}")
27
+ return None
28
+ except openai.AuthenticationError as e: # Authentication Error
29
+ st.error(f"OpenAI Authentication Error with {model_name}: {e}")
30
+ return None
31
+ except Exception as e: # Catch any other exception
32
+ st.error(f"An unexpected error occurred with {model_name}: {e}")
33
+ return None
34
+
35
+ # Main Streamlit app
36
+ def main():
37
+ st.title("Chatbot with Model Switching")
38
 
39
+ # Initialize conversation history in session state
40
+ if "messages" not in st.session_state:
41
+ st.session_state.messages = []
42
+
43
+ # Display previous messages
44
+ for message in st.session_state.messages:
45
+ with st.chat_message(message["role"]):
46
+ st.markdown(message["content"])
47
+
48
+ # Get user input
49
+ prompt = st.chat_input("Say something")
50
+
51
+ if prompt:
52
+ # Add user message to the state
53
+ st.session_state.messages.append({"role": "user", "content": prompt})
54
+ with st.chat_message("user"):
55
+ st.markdown(prompt)
56
+
57
+ # Define model priority
58
+ models = ["gpt-4", "gpt-3.5-turbo"] # Add more models as needed
59
+
60
+ # Get API key
61
+ api_key = get_api_key()
62
+ if not api_key:
63
+ return
64
+
65
+ response = None
66
+ for model in models:
67
+ response = generate_response(prompt, model, api_key)
68
+ if response:
69
+ break # If a response is generated, break out of loop.
70
 
71
+ if response:
72
+ # Add bot message to state
73
+ st.session_state.messages.append({"role": "assistant", "content": response})
74
+ with st.chat_message("assistant"):
75
+ st.markdown(response)
76
+
77
+ if __name__ == "__main__":
78
+ main()