-
Notifications
You must be signed in to change notification settings - Fork 176
/
app.py
332 lines (277 loc) Β· 11.4 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
import os
import base64
import re
import json
import streamlit as st
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
load_dotenv()
def str_to_bool(str_input):
if not isinstance(str_input, str):
return False
return str_input.lower() == "true"
# Load environment variables
openai_api_key = os.environ.get("OPENAI_API_KEY")
instructions = os.environ.get("RUN_INSTRUCTIONS", "")
enabled_file_upload_message = os.environ.get(
"ENABLED_FILE_UPLOAD_MESSAGE", "Upload a file"
)
azure_openai_endpoint = os.environ.get("AZURE_OPENAI_ENDPOINT")
azure_openai_key = os.environ.get("AZURE_OPENAI_KEY")
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
if azure_openai_endpoint and azure_openai_key:
client = openai.AzureOpenAI(
api_key=azure_openai_key,
api_version="2024-05-01-preview",
azure_endpoint=azure_openai_endpoint,
)
else:
client = openai.OpenAI(api_key=openai_api_key)
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",
"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
)
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 multi_agents:
assistants_json = json.loads(multi_agents)
assistants_object = {f'{obj["title"]}': obj for obj in assistants_json}
selected_assistant = st.sidebar.selectbox(
"Select an assistant profile?",
list(assistants_object.keys()),
index=None,
placeholder="Select an assistant profile...",
on_change=reset_chat, # Call the reset function on change
)
if selected_assistant:
load_chat_screen(
assistants_object[selected_assistant]["id"],
assistants_object[selected_assistant]["title"],
)
elif single_agent_id:
load_chat_screen(single_agent_id, single_agent_title)
else:
st.error("No assistant configurations defined in environment variables.")
if __name__ == "__main__":
main()