Spaces:
Sleeping
Sleeping
Creating utils
Browse files
utils.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def display_msg(msg, author):
|
| 2 |
+
"""Method to display message on the UI
|
| 3 |
+
Args:
|
| 4 |
+
msg (str): message to display
|
| 5 |
+
author (str): author of the message -user/assistant
|
| 6 |
+
"""
|
| 7 |
+
st.session_state.messages.append({"role": author, "content": msg})
|
| 8 |
+
st.chat_message(author).write(msg)
|
| 9 |
+
|
| 10 |
+
def configure_openai():
|
| 11 |
+
openai_api_key = st.sidebar.text_input(
|
| 12 |
+
label="OpenAI API Key",
|
| 13 |
+
type="password",
|
| 14 |
+
value=st.session_state['OPENAI_API_KEY'] if 'OPENAI_API_KEY' in st.session_state else '',
|
| 15 |
+
placeholder="sk-..."
|
| 16 |
+
)
|
| 17 |
+
if openai_api_key:
|
| 18 |
+
st.session_state['OPENAI_API_KEY'] = openai_api_key
|
| 19 |
+
os.environ['OPENAI_API_KEY'] = openai_api_key
|
| 20 |
+
else:
|
| 21 |
+
st.error("Please add your OpenAI API key to continue.")
|
| 22 |
+
st.info("Obtain your key from this link: https://platform.openai.com/account/api-keys")
|
| 23 |
+
st.stop()
|
| 24 |
+
|
| 25 |
+
model = "gpt-3.5-turbo"
|
| 26 |
+
try:
|
| 27 |
+
client = openai.OpenAI()
|
| 28 |
+
available_models = [{"id": i.id, "created":datetime.fromtimestamp(i.created)} for i in client.models.list() if str(i.id).startswith("gpt")]
|
| 29 |
+
available_models = sorted(available_models, key=lambda x: x["created"])
|
| 30 |
+
available_models = [i["id"] for i in available_models]
|
| 31 |
+
|
| 32 |
+
model = st.sidebar.selectbox(
|
| 33 |
+
label="Model",
|
| 34 |
+
options=available_models,
|
| 35 |
+
index=available_models.index(st.session_state['OPENAI_MODEL']) if 'OPENAI_MODEL' in st.session_state else 0
|
| 36 |
+
)
|
| 37 |
+
st.session_state['OPENAI_MODEL'] = model
|
| 38 |
+
except openai.AuthenticationError as e:
|
| 39 |
+
st.error(e.body["message"])
|
| 40 |
+
st.stop()
|
| 41 |
+
except Exception as e:
|
| 42 |
+
print(e)
|
| 43 |
+
st.error("Something went wrong. Please try again later.")
|
| 44 |
+
st.stop()
|
| 45 |
+
return model
|