forked from ryo-ma/gpt-assistants-api-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
363 lines (299 loc) Β· 12.2 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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
import os
import base64
import re
import json
import streamlit as st
from urllib.parse import urlparse, parse_qs
import openai
from openai import AssistantEventHandler
from tools import TOOL_MAP
from typing_extensions import override
from dotenv import load_dotenv
import streamlit_authenticator as stauth
import requests
load_dotenv()
hide_streamlit_style = """
<style>
header {visibility: hidden;}
.streamlit-footer {display: none;}
.st-emotion-cache-h4xjwg {display: none;}
</style>
"""
st.markdown(hide_streamlit_style, unsafe_allow_html=True)
def str_to_bool(str_input):
if not isinstance(str_input, str):
return False
return str_input.lower() == "true"
if 'id' not in st.query_params:
st.error("Missing url parameter: id")
st.stop()
unique_id = st.query_params["id"]
if 'initial_greeting' in st.query_params:
initial_greeting = st.query_params["initial_greeting"]
if initial_greeting == '':
initial_greeting = False
else:
initial_greeting = False
if 'openai_api_key' not in st.session_state:
# Send a GET request to the API
#url = "https://assistembedd.bubbleapps.io/version-test/api/1.1/wf/get-embed?id="+unique_id
url = "https://assistor.online/api/1.1/wf/get-embed?id="+unique_id
response = requests.get(url, timeout=10)
# Check if the request was successful
if response.status_code == 200:
# Parse the JSON response if it's available
response = response.json()
#st.write(response)
st.session_state["openai_api_key"] = response["response"]["openai_key"]["openai_text"]
st.session_state["chatGPT_assistant_id"] = response["response"]["openai_key"]["assistant_id_text"]
else:
st.error("Request failed with "+{response.status_code})
st.stop()
if 'greeted' not in st.session_state:
st.session_state['greeted'] = True
if initial_greeting:
with st.chat_message("assistant"):
st.write(initial_greeting)
# Load environment variables
instructions = os.environ.get("RUN_INSTRUCTIONS", "Instructions")
enabled_file_upload_message = os.environ.get(
"ENABLED_FILE_UPLOAD_MESSAGE", ""
)
authentication_required = str_to_bool(os.environ.get("AUTHENTICATION_REQUIRED", False))
# Load authentication configuration
if authentication_required:
if "credentials" in st.secrets:
authenticator = stauth.Authenticate(
st.secrets["credentials"].to_dict(),
st.secrets["cookie"]["name"],
st.secrets["cookie"]["key"],
st.secrets["cookie"]["expiry_days"],
)
else:
authenticator = None # No authentication should be performed
client = None
client = openai.OpenAI(api_key=st.session_state["openai_api_key"])
assistant_id = st.session_state["chatGPT_assistant_id"]
class EventHandler(AssistantEventHandler):
@override
def on_event(self, event):
pass
@override
def on_text_created(self, text):
st.session_state.current_message = ""
with st.chat_message("Assistant"):
st.session_state.current_markdown = st.empty()
@override
def on_text_delta(self, delta, snapshot):
if snapshot.value:
text_value = re.sub(
r"\[(.*?)\]\s*\(\s*(.*?)\s*\)", "Download Link", snapshot.value
)
st.session_state.current_message = text_value
st.session_state.current_markdown.markdown(
st.session_state.current_message, True
)
@override
def on_text_done(self, text):
format_text = format_annotation(text)
st.session_state.current_markdown.markdown(format_text, True)
st.session_state.chat_log.append({"name": "assistant", "msg": format_text})
@override
def on_tool_call_created(self, tool_call):
if tool_call.type == "code_interpreter":
st.session_state.current_tool_input = ""
with st.chat_message("Assistant"):
st.session_state.current_tool_input_markdown = st.empty()
@override
def on_tool_call_delta(self, delta, snapshot):
if 'current_tool_input_markdown' not in st.session_state:
with st.chat_message("Assistant"):
st.session_state.current_tool_input_markdown = st.empty()
if delta.type == "code_interpreter":
if delta.code_interpreter.input:
st.session_state.current_tool_input += delta.code_interpreter.input
input_code = f"### code interpreter\ninput:\n```python\n{st.session_state.current_tool_input}\n```"
st.session_state.current_tool_input_markdown.markdown(input_code, True)
if delta.code_interpreter.outputs:
for output in delta.code_interpreter.outputs:
if output.type == "logs":
pass
@override
def on_tool_call_done(self, tool_call):
st.session_state.tool_calls.append(tool_call)
if tool_call.type == "code_interpreter":
if tool_call.id in [x.id for x in st.session_state.tool_calls]:
return
input_code = f"### code interpreter\ninput:\n```python\n{tool_call.code_interpreter.input}\n```"
st.session_state.current_tool_input_markdown.markdown(input_code, True)
st.session_state.chat_log.append({"name": "assistant", "msg": input_code})
st.session_state.current_tool_input_markdown = None
for output in tool_call.code_interpreter.outputs:
if output.type == "logs":
output = f"### code interpreter\noutput:\n```\n{output.logs}\n```"
with st.chat_message("Assistant"):
st.markdown(output, True)
st.session_state.chat_log.append(
{"name": "assistant", "msg": output}
)
elif (
tool_call.type == "function"
and self.current_run.status == "requires_action"
):
with st.chat_message("Assistant"):
msg = f"### Function Calling: {tool_call.function.name}"
st.markdown(msg, True)
st.session_state.chat_log.append({"name": "assistant", "msg": msg})
tool_calls = self.current_run.required_action.submit_tool_outputs.tool_calls
tool_outputs = []
for submit_tool_call in tool_calls:
tool_function_name = submit_tool_call.function.name
tool_function_arguments = json.loads(
submit_tool_call.function.arguments
)
tool_function_output = TOOL_MAP[tool_function_name](
**tool_function_arguments
)
tool_outputs.append(
{
"tool_call_id": submit_tool_call.id,
"output": tool_function_output,
}
)
with client.beta.threads.runs.submit_tool_outputs_stream(
thread_id=st.session_state.thread.id,
run_id=self.current_run.id,
tool_outputs=tool_outputs,
event_handler=EventHandler(),
) as stream:
stream.until_done()
def create_thread(content, file):
return client.beta.threads.create()
def create_message(thread, content, file):
attachments = []
if file is not None:
attachments.append(
{"file_id": file.id, "tools": [{"type": "code_interpreter"}, {"type": "file_search"}]}
)
client.beta.threads.messages.create(
thread_id=thread.id, role="user", content=content, attachments=attachments
)
def create_file_link(file_name, file_id):
content = client.files.content(file_id)
content_type = content.response.headers["content-type"]
b64 = base64.b64encode(content.text.encode(content.encoding)).decode()
link_tag = f'<a href="data:{content_type};base64,{b64}" download="{file_name}">Download Link</a>'
return link_tag
def format_annotation(text):
citations = []
text_value = text.value
for index, annotation in enumerate(text.annotations):
text_value = text_value.replace(annotation.text, f" [{index}]")
if file_citation := getattr(annotation, "file_citation", None):
cited_file = client.files.retrieve(file_citation.file_id)
citations.append(
f"[{index}] {file_citation.quote} from {cited_file.filename}"
)
elif file_path := getattr(annotation, "file_path", None):
link_tag = create_file_link(
annotation.text.split("/")[-1],
file_path.file_id,
)
text_value = re.sub(r"\[(.*?)\]\s*\(\s*(.*?)\s*\)", link_tag, text_value)
text_value += "\n\n" + "\n".join(citations)
return text_value
def run_stream(user_input, file, selected_assistant_id):
if "thread" not in st.session_state:
st.session_state.thread = create_thread(user_input, file)
create_message(st.session_state.thread, user_input, file)
with client.beta.threads.runs.stream(
thread_id=st.session_state.thread.id,
assistant_id=selected_assistant_id,
event_handler=EventHandler(),
) as stream:
stream.until_done()
def handle_uploaded_file(uploaded_file):
file = client.files.create(file=uploaded_file, purpose="assistants")
return file
def render_chat():
for chat in st.session_state.chat_log:
with st.chat_message(chat["name"]):
st.markdown(chat["msg"], True)
if "tool_call" not in st.session_state:
st.session_state.tool_calls = []
if "chat_log" not in st.session_state:
st.session_state.chat_log = []
if "in_progress" not in st.session_state:
st.session_state.in_progress = False
def disable_form():
st.session_state.in_progress = True
def login():
if st.session_state["authentication_status"] is False:
st.error("Username/password is incorrect")
elif st.session_state["authentication_status"] is None:
st.warning("Please enter your username and password")
def reset_chat():
st.session_state.chat_log = []
st.session_state.in_progress = False
def load_chat_screen(assistant_id, assistant_title):
if enabled_file_upload_message:
uploaded_file = st.sidebar.file_uploader(
enabled_file_upload_message,
type=[
"txt",
"pdf",
"png",
"jpg",
"jpeg",
"csv",
"json",
"geojson",
"xlsx",
"xls",
],
disabled=st.session_state.in_progress,
)
else:
uploaded_file = None
#st.title(assistant_title if assistant_title else "")
user_msg = st.chat_input(
"Message",
on_submit=disable_form,
disabled=st.session_state.in_progress,
max_chars=1024,
)
if user_msg:
render_chat()
with st.chat_message("user"):
st.markdown(user_msg, True)
st.session_state.chat_log.append({"name": "user", "msg": user_msg})
file = None
if uploaded_file is not None:
file = handle_uploaded_file(uploaded_file)
run_stream(user_msg, file, assistant_id)
st.session_state.in_progress = False
st.session_state.tool_call = None
st.rerun()
render_chat()
def main():
# Check if multi-agent settings are defined
multi_agents = os.environ.get("OPENAI_ASSISTANTS", None)
single_agent_id = os.environ.get("ASSISTANT_ID", None)
single_agent_title = os.environ.get("ASSISTANT_TITLE", "Assistants API UI")
if (
authentication_required
and "credentials" in st.secrets
and authenticator is not None
):
authenticator.login()
if not st.session_state["authentication_status"]:
login()
return
else:
authenticator.logout(location="sidebar")
if assistant_id:
load_chat_screen(assistant_id, single_agent_title)
else:
st.error("No assistant configurations defined in environment variables.")
if __name__ == "__main__":
main()