-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.py
380 lines (327 loc) Β· 11.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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
import streamlit as st
from api.client import Client
from constants import Constants
from utils import generate_conversation
client = Client()
# ~~~ Page Configuration ~~~ π¨
st.set_page_config(
page_title="Amazon Bedrock Chatbot Demo",
initial_sidebar_state="expanded",
)
st.header("Unlock the Power of Generative AI with Divio and Amazon Bedrock")
st.text("How to Build and Deploy Your Own Chatbot")
col1, col2, col3 = st.columns([1, 1, 1])
with col1:
st.link_button(
"Source Code (GitHub) π",
"https://github.com/divio/amazon-bedrock-chatbot-demo",
use_container_width=True,
)
with col2:
st.link_button(
"Blog Post (Divio) π",
"https://www.divio.com/blog/unlock-the-power-of-generative-ai-with-divio-and-amazon-bedrock/",
use_container_width=True,
)
with col3:
st.link_button(
"Website (Divio) π",
"https://amazon-bedrock-chatbot-demo.eu.aldryn.io/",
use_container_width=True,
)
st.divider()
# ~~~ AWS Credentials ~~~ π
with st.sidebar:
st.text("Sign in with your AWS credentials")
with st.form("aws_credentials_form"):
st.text(
"π AWS Access Key",
help=Constants.AWS_ACCESS_KEY_FORM_HELP_TEXT.value,
)
aws_access_key_id = st.text_input(
"Access Key ID", type="password", key="aws_access_key_id"
)
aws_secret_access_key = st.text_input("Secret Access Key", type="password")
aws_credentials_form_submitted = st.form_submit_button("Sign In")
user_id = st.session_state.get("user_id", None)
auth_message = st.session_state.get(
"auth_message", Constants.AWS_AUTH_NO_CREDENTIALS_MESSAGE.value
)
if aws_credentials_form_submitted:
user_id, auth_message = client.check_aws_credentials(
aws_access_key_id, aws_secret_access_key
)
st.session_state.user_id = user_id
st.session_state.auth_message = auth_message
if user_id:
client.aws_access_key_id = aws_access_key_id
client.aws_secret_access_key = aws_secret_access_key
if not st.session_state.get("valid_aws_credentials_toast_shown", False):
st.session_state.valid_aws_credentials_toast_shown = True
st.toast(auth_message, icon="π")
else:
st.session_state.valid_aws_credentials_toast_shown = False
st.info(auth_message, icon="π¨")
# ~~~ AWS Region Selection ~~~ π
with st.sidebar:
# Listing available AWS regions does not require credentials.
amazon_bedrock_regions_response = client.list_amazon_bedrock_regions()
st.divider()
region = st.selectbox(
"π AWS Region",
placeholder="Select an AWS Region",
options=amazon_bedrock_regions_response if user_id else [],
help=Constants.AWS_REGION_SELECTBOX_HELP_TEXT.value,
index=None,
disabled=user_id is None,
)
if user_id and not region:
st.info("Please select an AWS region to view the available models.", icon="π")
# ~~~ Chat Messages ~~~ π¬
messages = st.session_state.get("messages", [])
# ~~~ Foundation Model Selection ~~~ π§
with st.sidebar:
models = {}
if region:
foundation_models_response = client.list_foundation_models(
region_name=region,
byOutputModality="TEXT",
)
# NOTE: boto3 does not supports filtering by responseStreamingSupported.
models = {
m["modelId"]: {
"name": m["modelName"],
"model_arn": m["modelArn"],
}
for m in foundation_models_response.get("modelSummaries", [])
if m.get("responseStreamingSupported", False)
}
st.divider()
model_id = st.selectbox(
"π§ Model",
placeholder="Select a Model",
options=models,
# Enable the following 2 lines (captions, format_func) if you go for
# a radio button instead. (Optional)
# captions = models,
# format_func = lambda x: models[x]["name"],
help=Constants.AWS_FOUNDATION_MODEL_SELECTBOX_HELP_TEXT.value,
index=None,
disabled=not all([user_id, region]),
)
if not model_id and region:
st.info(
(
"Please select a model to "
f"{'continue' if messages else 'start'} the conversation."
),
icon="π§ ",
)
with st.sidebar:
with st.form("model_configuration_form"):
max_tokens = st.slider(
"Max Tokens",
min_value=20,
max_value=1000,
value=500,
step=20,
disabled=not model_id,
help=Constants.AWS_FOUNDATION_MODEL_CONFIGURATION_MAX_TOKENS_HELP_TEXT.value,
)
temperature = st.slider(
"Temperature",
min_value=0.0,
max_value=1.0,
value=0.5,
step=0.1,
disabled=not model_id,
help=Constants.AWS_FOUNDATION_MODEL_CONFIGURATION_TEMPERATURE_HELP_TEXT.value,
)
top_p = st.slider(
"topP",
min_value=0.0,
max_value=1.0,
value=0.9,
step=0.1,
disabled=not model_id,
help=Constants.AWS_FOUNDATION_MODEL_CONFIGURATION_TOP_P_HELP_TEXT.value,
)
system_prompt = st.text_input(
"System Prompt",
placeholder="Enter a system prompt",
disabled=not model_id,
help=Constants.AWS_FOUNDATION_MODEL_CONFIGURATION_SYSTEM_PROMPT_HELP_TEXT.value,
value=None,
)
system_config = []
if system_prompt:
system_config = [{"text": system_prompt}]
inference_config = {
"maxTokens": max_tokens,
"temperature": temperature,
"topP": top_p,
}
st.form_submit_button(
"Apply",
disabled=not model_id,
)
# ~~~ Knowledge Base ~~~ ποΈ
with st.sidebar:
knowledge_base_id = None
# ~~~ Knowledge Base ~~~ ποΈ
knowledge_bases = {}
if region and model_id:
knowledge_bases_response = client.list_knowledge_bases(
region_name=region,
)
knowledge_bases_summaries = knowledge_bases_response.get(
"knowledgeBaseSummaries", []
)
knowledge_bases = {
kb["knowledgeBaseId"]: kb["name"] for kb in knowledge_bases_summaries
}
st.divider()
knowledge_base_id = st.selectbox(
"π Knowledge Base",
placeholder="Select a Knowledge Base",
options=knowledge_bases,
format_func=lambda x: knowledge_bases[x],
help=Constants.KNOWLEDGE_BASE_SELECTBOX_HELP_TEXT.value,
index=None,
disabled=not all([user_id, region]),
)
if knowledge_base_id:
st.text(
"π Knowledge Base search mode enabled.",
help=Constants.KNOWLEDGE_BASE_SEARCH_MODE_ENABLED_HELP_TEXT.value,
)
with st.sidebar:
# ~~~ Data Source ~~~ ποΈ
knowledge_base_data_sources = {}
if knowledge_base_id:
response = client.list_data_sources(
region_name=region,
knowledge_base_id=knowledge_base_id,
)
knowledge_base_data_sources = {
ds["dataSourceId"]: ds["name"]
for ds in response.get("dataSourceSummaries", [])
}
data_source = st.selectbox(
"π€ Upload file to Data Source",
placeholder="Select a Data Source",
options=knowledge_base_data_sources,
format_func=lambda x: knowledge_base_data_sources[x],
index=None,
disabled=not knowledge_base_id,
help=Constants.DATA_SOURCE_SELECTBOX_HELP_TEXT.value,
)
data_source_bucket_name = None
if data_source:
data_source_details = client.get_data_source(
region_name=region,
data_source_id=data_source,
knowledge_base_id=knowledge_base_id,
)
data_source_bucket_arn = data_source_details["dataSource"][
"dataSourceConfiguration"
]["s3Configuration"]["bucketArn"]
data_source_bucket_name = data_source_bucket_arn.split(":::")[-1]
# ~~~ Document Upload ~~~ π
uploaded_file = None
upload_file_to_s3_bucket_form_submitted = False
if data_source_bucket_name:
with st.form("upload_file_to_s3_bucket_form", border=False):
uploaded_file = st.file_uploader(
"π Upload file",
type=["txt", "csv", "md", "pdf"],
disabled=not data_source_bucket_name,
label_visibility="collapsed",
)
upload_file_to_s3_bucket_form_submitted = st.form_submit_button(
"Upload & Sync",
disabled=not data_source_bucket_name,
)
if all(
[
upload_file_to_s3_bucket_form_submitted,
uploaded_file,
data_source_bucket_name,
]
):
upload_to_s3_bucket_response = client.upload_to_s3_bucket(
region_name=region,
bucket_name=data_source_bucket_name,
file_name=uploaded_file.name,
file_body=uploaded_file.getvalue(),
)
sync_knowledge_base_response = client.sync_knowledge_base(
region_name=region,
data_source_id=data_source,
knowledge_base_id=knowledge_base_id,
)
# ~~~ Build Chat ~~~ π¬
prompt = st.chat_input(
f"Message {models[model_id]["name"]}"
if model_id
else (
"Please select a model to "
f"{'continue' if messages else 'start'} the conversation."
),
disabled=not model_id,
max_chars=1000,
)
if prompt:
user_message = {
"role": "user",
"content": [{"text": prompt}],
}
messages.append(user_message)
st.session_state.messages = messages
if knowledge_base_id:
assistant_response = client.get_assistant_response_using_knowledge_base(
region_name=region,
modelArn=models[model_id]["model_arn"],
knowledge_base_id=knowledge_base_id,
user_query=prompt,
inference_config=inference_config,
)
else:
assistant_response = client.get_assistant_response(
region_name=region,
model_id=model_id,
system_config=system_config,
messages=messages,
inference_config=inference_config,
)
if assistant_response:
if knowledge_base_id:
stream = assistant_response["output"]["text"]
else:
stream = (
chunk["contentBlockDelta"]["delta"]["text"]
for chunk in assistant_response["stream"]
if "contentBlockDelta" in chunk
)
assistant_message = {
"role": "assistant",
"content": [{"text": stream}],
}
messages.append(assistant_message)
st.session_state.messages = messages
else:
messages.pop()
st.session_state.messages = messages
# ~~~ Chat Display ~~~ π¬
if messages:
st.button(
"Clear Chat",
on_click=lambda: st.session_state.pop("messages"),
)
else:
if model_id:
st.info(
"All set! You're ready to start a conversation.",
icon="π",
)
generate_conversation(st.session_state.get("messages", []))