AIfenaike commited on
Commit
f6f9615
·
verified ·
1 Parent(s): aa2ec1f

Create utils.py

Browse files
Files changed (1) hide show
  1. utils.py +78 -0
utils.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import openai
3
+ import random
4
+ import streamlit as st
5
+ from datetime import datetime
6
+
7
+ #decorator
8
+ def enable_chat_history(func):
9
+ if os.environ.get("OPENAI_API_KEY"):
10
+
11
+ # to clear chat history after swtching chatbot
12
+ current_page = func.__qualname__
13
+ if "current_page" not in st.session_state:
14
+ st.session_state["current_page"] = current_page
15
+ if st.session_state["current_page"] != current_page:
16
+ try:
17
+ st.cache_resource.clear()
18
+ del st.session_state["current_page"]
19
+ del st.session_state["messages"]
20
+ except:
21
+ pass
22
+
23
+ # to show chat history on ui
24
+ if "messages" not in st.session_state:
25
+ st.session_state["messages"] = [{"role": "assistant", "content": "How can I help you?"}]
26
+ for msg in st.session_state["messages"]:
27
+ st.chat_message(msg["role"]).write(msg["content"])
28
+
29
+ def execute(*args, **kwargs):
30
+ func(*args, **kwargs)
31
+ return execute
32
+
33
+ def display_msg(msg, author):
34
+ """Method to display message on the UI
35
+
36
+ Args:
37
+ msg (str): message to display
38
+ author (str): author of the message -user/assistant
39
+ """
40
+ st.session_state.messages.append({"role": author, "content": msg})
41
+ st.chat_message(author).write(msg)
42
+
43
+ def configure_openai():
44
+ openai_api_key = st.sidebar.text_input(
45
+ label="OpenAI API Key",
46
+ type="password",
47
+ value=st.session_state['OPENAI_API_KEY'] if 'OPENAI_API_KEY' in st.session_state else '',
48
+ placeholder="sk-..."
49
+ )
50
+ if openai_api_key:
51
+ st.session_state['OPENAI_API_KEY'] = openai_api_key
52
+ os.environ['OPENAI_API_KEY'] = openai_api_key
53
+ else:
54
+ st.error("Please add your OpenAI API key to continue.")
55
+ st.info("Obtain your key from this link: https://platform.openai.com/account/api-keys")
56
+ st.stop()
57
+
58
+ model = "gpt-3.5-turbo"
59
+ try:
60
+ client = openai.OpenAI()
61
+ available_models = [{"id": i.id, "created":datetime.fromtimestamp(i.created)} for i in client.models.list() if str(i.id).startswith("gpt")]
62
+ available_models = sorted(available_models, key=lambda x: x["created"])
63
+ available_models = [i["id"] for i in available_models]
64
+
65
+ model = st.sidebar.selectbox(
66
+ label="Model",
67
+ options=available_models,
68
+ index=available_models.index(st.session_state['OPENAI_MODEL']) if 'OPENAI_MODEL' in st.session_state else 0
69
+ )
70
+ st.session_state['OPENAI_MODEL'] = model
71
+ except openai.AuthenticationError as e:
72
+ st.error(e.body["message"])
73
+ st.stop()
74
+ except Exception as e:
75
+ print(e)
76
+ st.error("Something went wrong. Please try again later.")
77
+ st.stop()
78
+ return model