-
Notifications
You must be signed in to change notification settings - Fork 19
/
app.py
152 lines (125 loc) · 4.89 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
import streamlit as st
from streamlit_chat import message
import dotenv
import os
import openai
import datetime
import json
# region ENV + SDK SETUP
# Load environment variables
ENV = dotenv.dotenv_values(".env")
with st.sidebar.expander("Environment Variables"):
st.write(ENV)
# Set up the Open AI Client
openai.api_type = "azure"
openai.api_base = ENV["AZURE_OPENAI_ENDPOINT"]
openai.api_version = ENV["AZURE_OPENAI_API_VERSION"]
openai.api_key = ENV["AZURE_OPENAI_KEY"]
# endregion
# region PROMPT SETUP
default_prompt = """
You are an AI assistant that helps users write concise\
reports on sources provided according to a user query.\
You will provide reasoning for your summaries and deductions by\
describing your thought process. You will highlight any conflicting\
information between or within sources. Greet the user by asking\
what they'd like to investigate.
"""
system_prompt = st.sidebar.text_area("System Prompt", default_prompt, height=200)
seed_message = {"role": "system", "content": system_prompt}
# endregion
# region SESSION MANAGEMENT
# Initialise session state variables
if "generated" not in st.session_state:
st.session_state["generated"] = []
if "past" not in st.session_state:
st.session_state["past"] = []
if "messages" not in st.session_state:
st.session_state["messages"] = [seed_message]
if "model_name" not in st.session_state:
st.session_state["model_name"] = []
if "cost" not in st.session_state:
st.session_state["cost"] = []
if "total_tokens" not in st.session_state:
st.session_state["total_tokens"] = []
if "total_cost" not in st.session_state:
st.session_state["total_cost"] = 0.0
# endregion
# region SIDEBAR SETUP
counter_placeholder = st.sidebar.empty()
counter_placeholder.write(
f"Total cost of this conversation: ${st.session_state['total_cost']:.5f}"
)
clear_button = st.sidebar.button("Clear Conversation", key="clear")
if clear_button:
st.session_state["generated"] = []
st.session_state["past"] = []
st.session_state["messages"] = [seed_message]
st.session_state["number_tokens"] = []
st.session_state["model_name"] = []
st.session_state["cost"] = []
st.session_state["total_cost"] = 0.0
st.session_state["total_tokens"] = []
counter_placeholder.write(
f"Total cost of this conversation: £{st.session_state['total_cost']:.5f}"
)
download_conversation_button = st.sidebar.download_button(
"Download Conversation",
data=json.dumps(st.session_state["messages"]),
file_name=f"conversation.json",
mime="text/json",
)
# endregion
def generate_response(prompt):
st.session_state["messages"].append({"role": "user", "content": prompt})
try:
completion = openai.ChatCompletion.create(
engine=ENV["AZURE_OPENAI_CHATGPT_DEPLOYMENT"],
messages=st.session_state["messages"],
)
response = completion.choices[0].message.content
except openai.error.APIError as e:
st.write(response)
response = f"The API could not handle this content: {str(e)}"
st.session_state["messages"].append({"role": "assistant", "content": response})
# print(st.session_state['messages'])
total_tokens = completion.usage.total_tokens
prompt_tokens = completion.usage.prompt_tokens
completion_tokens = completion.usage.completion_tokens
return response, total_tokens, prompt_tokens, completion_tokens
st.title("Streamlit ChatGPT Demo")
# container for chat history
response_container = st.container()
# container for text box
container = st.container()
with container:
with st.form(key="my_form", clear_on_submit=True):
user_input = st.text_area("You:", key="input", height=100)
submit_button = st.form_submit_button(label="Send")
if submit_button and user_input:
output, total_tokens, prompt_tokens, completion_tokens = generate_response(
user_input
)
st.session_state["past"].append(user_input)
st.session_state["generated"].append(output)
st.session_state["model_name"].append(ENV["AZURE_OPENAI_CHATGPT_DEPLOYMENT"])
st.session_state["total_tokens"].append(total_tokens)
# from https://azure.microsoft.com/en-us/pricing/details/cognitive-services/openai-service/#pricing
cost = total_tokens * 0.001625 / 1000
st.session_state["cost"].append(cost)
st.session_state["total_cost"] += cost
if st.session_state["generated"]:
with response_container:
for i in range(len(st.session_state["generated"])):
message(
st.session_state["past"][i],
is_user=True,
key=str(i) + "_user",
avatar_style="shapes",
)
message(
st.session_state["generated"][i], key=str(i), avatar_style="identicon"
)
counter_placeholder.write(
f"Total cost of this conversation: ${st.session_state['total_cost']:.5f}"
)