MilanM commited on
Commit
be554ae
·
verified ·
1 Parent(s): d78905b

Create neo_sages4.py

Browse files
Files changed (1) hide show
  1. neo_sages4.py +543 -0
neo_sages4.py ADDED
@@ -0,0 +1,543 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from io import BytesIO
3
+ import ibm_watsonx_ai
4
+ import secretsload
5
+ import genparam
6
+ import requests
7
+ import time
8
+ import re
9
+ import json
10
+
11
+ from ibm_watsonx_ai.foundation_models import ModelInference
12
+ from ibm_watsonx_ai import Credentials, APIClient
13
+ from ibm_watsonx_ai.metanames import GenTextParamsMetaNames as GenParams
14
+ from ibm_watsonx_ai.metanames import GenTextReturnOptMetaNames as RetParams
15
+ from knowledge_bases import KNOWLEDGE_BASE_OPTIONS, SYSTEM_PROMPTS, VECTOR_INDEXES
16
+ from ibm_watsonx_ai.foundation_models import Embeddings
17
+ from ibm_watsonx_ai.foundation_models.utils.enums import EmbeddingTypes
18
+ from pymilvus import MilvusClient
19
+
20
+ from secretsload import load_stsecrets
21
+
22
+ credentials = load_stsecrets()
23
+
24
+ st.set_page_config(
25
+ page_title="The Solutioning Sages",
26
+ page_icon="🪄",
27
+ initial_sidebar_state="collapsed",
28
+ layout="wide"
29
+ )
30
+
31
+ # Password protection
32
+ def check_password():
33
+ def password_entered():
34
+ if st.session_state["password"] == st.secrets["app_password"]:
35
+ st.session_state["password_correct"] = True
36
+ del st.session_state["password"]
37
+ else:
38
+ st.session_state["password_correct"] = False
39
+
40
+ if "password_correct" not in st.session_state:
41
+ st.markdown("\n\n")
42
+ st.text_input("Enter the password", type="password", on_change=password_entered, key="password")
43
+ st.divider()
44
+ st.info("Designed and developed by Milan Mrdenovic © IBM Norway 2024")
45
+ return False
46
+ elif not st.session_state["password_correct"]:
47
+ st.markdown("\n\n")
48
+ st.text_input("Enter the password", type="password", on_change=password_entered, key="password")
49
+ st.divider()
50
+ st.error("😕 Incorrect password")
51
+ st.info("Designed and developed by Milan Mrdenovic © IBM Norway 2024")
52
+ return False
53
+ else:
54
+ return True
55
+
56
+ def initialize_session_state():
57
+ if 'chat_history_1' not in st.session_state:
58
+ st.session_state.chat_history_1 = []
59
+ if 'chat_history_2' not in st.session_state:
60
+ st.session_state.chat_history_2 = []
61
+ if 'chat_history_3' not in st.session_state:
62
+ st.session_state.chat_history_3 = []
63
+ if 'first_question' not in st.session_state:
64
+ st.session_state.first_question = False
65
+ if "counter" not in st.session_state:
66
+ st.session_state["counter"] = 0
67
+ if 'token_statistics' not in st.session_state:
68
+ st.session_state.token_statistics = []
69
+ if 'selected_kb' not in st.session_state:
70
+ st.session_state.selected_kb = KNOWLEDGE_BASE_OPTIONS[0]
71
+ if 'current_system_prompts' not in st.session_state:
72
+ st.session_state.current_system_prompts = SYSTEM_PROMPTS[st.session_state.selected_kb]
73
+
74
+ # three_column_style = """
75
+ # <style>
76
+ # .stColumn {
77
+ # padding: 0.5rem;
78
+ # border-right: 1px solid #dedede;
79
+ # }
80
+ # .stColumn:last-child {
81
+ # border-right: none;
82
+ # }
83
+ # .chat-container {
84
+ # height: calc(100vh - 200px);
85
+ # overflow-y: auto;
86
+ # }
87
+ # </style>
88
+ # """
89
+
90
+ three_column_style = """
91
+ <style>
92
+ .stColumn {
93
+ padding: 0.5rem;
94
+ border-right: 1px solid #dedede;
95
+ }
96
+ .stColumn:last-child {
97
+ border-right: none;
98
+ }
99
+ .chat-container {
100
+ height: calc(100vh - 200px);
101
+ overflow-y: auto;
102
+ display: flex;
103
+ flex-direction: column;
104
+ }
105
+ .chat-messages {
106
+ display: flex;
107
+ flex-direction: column;
108
+ gap: 1rem;
109
+ }
110
+ </style>
111
+ """ # Alt Style
112
+
113
+ #-----
114
+ def get_active_model():
115
+ return genparam.SELECTED_MODEL_1 if genparam.ACTIVE_MODEL == 0 else genparam.SELECTED_MODEL_2
116
+
117
+ def get_active_prompt_template():
118
+ return genparam.PROMPT_TEMPLATE_1 if genparam.ACTIVE_MODEL == 0 else genparam.PROMPT_TEMPLATE_2
119
+
120
+ def get_active_vector_index():
121
+ selected_kb = st.session_state.selected_kb
122
+ if genparam.ACTIVE_INDEX == 0:
123
+ return VECTOR_INDEXES[selected_kb]["index_1"]
124
+ else:
125
+ return VECTOR_INDEXES[selected_kb]["index_2"]
126
+ #-----
127
+
128
+ def setup_client(project_id=None):
129
+ credentials = Credentials(
130
+ url=st.secrets["url"],
131
+ api_key=st.secrets["api_key"]
132
+ )
133
+ # Use the passed project_id if provided, otherwise fallback to secrets
134
+ project_id = project_id or st.secrets["project_id"]
135
+ client = APIClient(credentials, project_id=project_id)
136
+ return credentials, client
137
+
138
+ wml_credentials, client = setup_client(st.secrets["project_id"])
139
+
140
+ def setup_vector_index(client, wml_credentials, vector_index_id):
141
+ vector_index_details = client.data_assets.get_details(vector_index_id)
142
+ vector_index_properties = vector_index_details["entity"]["vector_index"]
143
+
144
+ emb = Embeddings(
145
+ model_id=vector_index_properties["settings"]["embedding_model_id"],
146
+ #model_id="sentence-transformers/all-minilm-l12-v2",
147
+ credentials=wml_credentials,
148
+ project_id=st.secrets["project_id"],
149
+ params={
150
+ "truncate_input_tokens": 512
151
+ }
152
+ )
153
+
154
+ vector_store_schema = vector_index_properties["settings"]["schema_fields"]
155
+ connection_details = client.connections.get_details(vector_index_details["entity"]["vector_index"]["store"]["connection_id"])
156
+ connection_properties = connection_details["entity"]["properties"]
157
+
158
+ milvus_client = MilvusClient(
159
+ uri=f'https://{connection_properties.get("host")}:{connection_properties.get("port")}',
160
+ user=connection_properties.get("username"),
161
+ password=connection_properties.get("password"),
162
+ db_name=vector_index_properties["store"]["database"]
163
+ )
164
+
165
+ return milvus_client, emb, vector_index_properties, vector_store_schema
166
+
167
+ def proximity_search(question, milvus_client, emb, vector_index_properties, vector_store_schema):
168
+ query_vectors = emb.embed_query(question)
169
+ milvus_response = milvus_client.search(
170
+ collection_name=vector_index_properties["store"]["index"],
171
+ data=[query_vectors],
172
+ limit=vector_index_properties["settings"]["top_k"],
173
+ metric_type="L2",
174
+ output_fields=[
175
+ vector_store_schema.get("text"),
176
+ vector_store_schema.get("document_name"),
177
+ vector_store_schema.get("page_number")
178
+ ]
179
+ )
180
+
181
+ documents = []
182
+
183
+ for hit in milvus_response[0]:
184
+ text = hit["entity"].get(vector_store_schema.get("text"), "")
185
+ doc_name = hit["entity"].get(vector_store_schema.get("document_name"), "Unknown Document")
186
+ page_num = hit["entity"].get(vector_store_schema.get("page_number"), "N/A")
187
+
188
+ formatted_result = f"Document: {doc_name}\nContent: {text}\nPage: {page_num}\n"
189
+ documents.append(formatted_result)
190
+
191
+ joined = "\n".join(documents)
192
+ retrieved = f"""Number of Retrieved Documents: {len(documents)}\n\n{joined}"""
193
+
194
+ return retrieved
195
+
196
+ def prepare_prompt(prompt, chat_history):
197
+ if genparam.TYPE == "chat" and chat_history:
198
+ chats = "\n".join([f"{message['role']}: \"{message['content']}\"" for message in chat_history])
199
+ prompt = f"""Retrieved Contextual Information:\n__grounding__\n\nConversation History:\n{chats}\n\nNew User Input: {prompt}"""
200
+ return prompt
201
+ else:
202
+ prompt = f"""Retrieved Contextual Information:\n__grounding__\n\nUser Input: {prompt}"""
203
+ return prompt
204
+
205
+ def apply_prompt_syntax(prompt, system_prompt, prompt_template, bake_in_prompt_syntax):
206
+ model_family_syntax = {
207
+ "llama3-instruct (llama-3, 3.1 & 3.2) - system": """<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n\n{system_prompt}<|eot_id|><|start_header_id|>user<|end_header_id|>\n\n{prompt}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n""",
208
+ "llama3-instruct (llama-3, 3.1 & 3.2) - user": """<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n{prompt}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n""",
209
+ "granite-13b-chat & instruct - system": """<|system|>\n{system_prompt}\n<|user|>\n{prompt}\n<|assistant|>\n\n""",
210
+ "granite-13b-chat & instruct - user": """<|user|>\n{prompt}\n<|assistant|>\n\n""",
211
+ "mistral & mixtral v2 tokenizer - system": """<s>[INST] System Prompt: {system_prompt} [/INST][INST] {prompt} [/INST]\n\n""",
212
+ "mistral & mixtral v2 tokenizer - user": """<s>[INST] {prompt} [/INST]\n\n""",
213
+ "no syntax - system": """{system_prompt}\n\n{prompt}""",
214
+ "no syntax - user": """{prompt}"""
215
+ }
216
+
217
+ if bake_in_prompt_syntax:
218
+ template = model_family_syntax[prompt_template]
219
+ if system_prompt:
220
+ return template.format(system_prompt=system_prompt, prompt=prompt)
221
+ return prompt
222
+
223
+ def generate_response(watsonx_llm, prompt_data, params):
224
+ generated_response = watsonx_llm.generate_text_stream(prompt=prompt_data, params=params)
225
+ for chunk in generated_response:
226
+ yield chunk
227
+
228
+ def fetch_response(user_input, milvus_client, emb, vector_index_properties, vector_store_schema, system_prompt, chat_history):
229
+ # Get grounding documents
230
+ grounding = proximity_search(
231
+ question=user_input,
232
+ milvus_client=milvus_client,
233
+ emb=emb,
234
+ vector_index_properties=vector_index_properties,
235
+ vector_store_schema=vector_store_schema
236
+ )
237
+
238
+ # Special handling for PATH-er B. (first column)
239
+ if chat_history == st.session_state.chat_history_1:
240
+ # Display user question first
241
+ with st.chat_message("user", avatar=genparam.USER_AVATAR):
242
+ st.markdown(user_input)
243
+
244
+ # Parse and display each document from the grounding
245
+ documents = grounding.split("\n\n")[2:] # Skip the count line and first newline
246
+ for doc in documents:
247
+ if doc.strip(): # Only process non-empty strings
248
+ parts = doc.split("\n")
249
+ doc_name = parts[0].replace("Document: ", "")
250
+ content = parts[1].replace("Content: ", "")
251
+
252
+ # Display document with delay
253
+ time.sleep(0.5)
254
+ st.markdown(f"**{doc_name}**")
255
+ st.code(content)
256
+
257
+ # Store in chat history
258
+ return grounding
259
+
260
+ # For MOD-ther S. (second column) and SYS-ter V. (third column)
261
+ else:
262
+ prompt = prepare_prompt(user_input, chat_history)
263
+ prompt_data = apply_prompt_syntax(
264
+ prompt,
265
+ system_prompt, # Using the system_prompt passed to the function
266
+ get_active_prompt_template(),
267
+ genparam.BAKE_IN_PROMPT_SYNTAX
268
+ )
269
+ prompt_data = prompt_data.replace("__grounding__", grounding)
270
+
271
+ # Add debug information to column 1 if enabled
272
+ if genparam.INPUT_DEBUG_VIEW == 1:
273
+ with col1: # Access first column
274
+ bot_name = genparam.BOT_2_NAME if chat_history == st.session_state.chat_history_2 else genparam.BOT_3_NAME
275
+ bot_avatar = genparam.BOT_2_AVATAR if chat_history == st.session_state.chat_history_2 else genparam.BOT_3_AVATAR
276
+ st.markdown(f"**{bot_avatar} {bot_name} Prompt Data:**")
277
+ st.code(prompt_data, language="text")
278
+
279
+ # Continue with normal processing for columns 2 and 3
280
+ watsonx_llm = ModelInference(
281
+ api_client=client,
282
+ model_id=get_active_model(),
283
+ verify=genparam.VERIFY
284
+ )
285
+
286
+ params = {
287
+ GenParams.DECODING_METHOD: genparam.DECODING_METHOD,
288
+ GenParams.MAX_NEW_TOKENS: genparam.MAX_NEW_TOKENS,
289
+ GenParams.MIN_NEW_TOKENS: genparam.MIN_NEW_TOKENS,
290
+ GenParams.REPETITION_PENALTY: genparam.REPETITION_PENALTY,
291
+ GenParams.STOP_SEQUENCES: genparam.STOP_SEQUENCES
292
+ }
293
+
294
+ bot_name = None
295
+ bot_avatar = None
296
+ if chat_history == st.session_state.chat_history_1:
297
+ bot_name = genparam.BOT_1_NAME
298
+ bot_avatar = genparam.BOT_1_AVATAR
299
+ elif chat_history == st.session_state.chat_history_2:
300
+ bot_name = genparam.BOT_2_NAME
301
+ bot_avatar = genparam.BOT_2_AVATAR
302
+ else:
303
+ bot_name = genparam.BOT_3_NAME
304
+ bot_avatar = genparam.BOT_3_AVATAR
305
+
306
+ with st.chat_message(bot_name, avatar=bot_avatar):
307
+ if chat_history != st.session_state.chat_history_1: # Only generate responses for columns 2 and 3
308
+ stream = generate_response(watsonx_llm, prompt_data, params)
309
+ response = st.write_stream(stream)
310
+
311
+ # Only capture tokens for MOD-ther S. and SYS-ter V.
312
+ if genparam.TOKEN_CAPTURE_ENABLED and chat_history != st.session_state.chat_history_1:
313
+ token_stats = capture_tokens(prompt_data, response, bot_name)
314
+ if token_stats:
315
+ st.session_state.token_statistics.append(token_stats)
316
+ else:
317
+ response = grounding # For column 1, we already displayed the content
318
+
319
+ return response
320
+
321
+ def capture_tokens(prompt_data, response, chat_number):
322
+ if not genparam.TOKEN_CAPTURE_ENABLED:
323
+ return
324
+
325
+ watsonx_llm = ModelInference(
326
+ api_client=client,
327
+ model_id=genparam.SELECTED_MODEL,
328
+ verify=genparam.VERIFY
329
+ )
330
+
331
+ input_tokens = watsonx_llm.tokenize(prompt=prompt_data)["result"]["token_count"]
332
+ output_tokens = watsonx_llm.tokenize(prompt=response)["result"]["token_count"]
333
+ total_tokens = input_tokens + output_tokens
334
+
335
+ return {
336
+ "bot_name": bot_name,
337
+ "input_tokens": input_tokens,
338
+ "output_tokens": output_tokens,
339
+ "total_tokens": total_tokens,
340
+ "timestamp": time.strftime("%H:%M:%S")
341
+ }
342
+
343
+ def main():
344
+ initialize_session_state()
345
+
346
+ # Apply custom styles
347
+ st.markdown(three_column_style, unsafe_allow_html=True)
348
+
349
+ # Sidebar configuration
350
+ st.sidebar.header('The Solutioning Sages')
351
+ st.sidebar.divider()
352
+
353
+ # Knowledge Base Selection
354
+ selected_kb = st.sidebar.selectbox(
355
+ "Select Knowledge Base",
356
+ KNOWLEDGE_BASE_OPTIONS,
357
+ index=KNOWLEDGE_BASE_OPTIONS.index(st.session_state.selected_kb)
358
+ )
359
+
360
+ # Update knowledge base related values if selection changes
361
+ if selected_kb != st.session_state.selected_kb:
362
+ st.session_state.selected_kb = selected_kb
363
+
364
+ # Display current knowledge base contents
365
+ with st.sidebar.expander("Knowledge Base Contents"):
366
+ for doc in VECTOR_INDEXES[selected_kb]["contents"]:
367
+ st.write(f"📄 {doc}")
368
+
369
+ # Display active model information
370
+ st.sidebar.divider()
371
+ active_model = genparam.SELECTED_MODEL_1 if genparam.ACTIVE_MODEL == 0 else genparam.SELECTED_MODEL_2
372
+ st.sidebar.markdown("**Active Model:**")
373
+ st.sidebar.code(active_model)
374
+
375
+ st.sidebar.divider()
376
+
377
+ # Display token statistics in sidebar
378
+ st.sidebar.subheader("Token Usage Statistics")
379
+
380
+ # Group token statistics by interaction (for MOD-ther S. and SYS-ter V. only)
381
+ if st.session_state.token_statistics:
382
+ current_timestamp = None
383
+ interaction_count = 0
384
+ stats_by_time = {}
385
+
386
+ # Group stats by timestamp
387
+ for stat in st.session_state.token_statistics:
388
+ if stat["timestamp"] not in stats_by_time:
389
+ stats_by_time[stat["timestamp"]] = []
390
+ stats_by_time[stat["timestamp"]].append(stat)
391
+
392
+ # Display grouped stats
393
+ for timestamp, stats in stats_by_time.items():
394
+ interaction_count += 1
395
+ st.sidebar.markdown(f"**Interaction {interaction_count}** ({timestamp})")
396
+
397
+ # Calculate total tokens for this interaction
398
+ total_input = sum(stat['input_tokens'] for stat in stats)
399
+ total_output = sum(stat['output_tokens'] for stat in stats)
400
+ total = total_input + total_output
401
+
402
+ # Display individual bot statistics
403
+ for stat in stats:
404
+ st.sidebar.markdown(
405
+ f"_{stat['bot_name']}_ \n"
406
+ f"Input: {stat['input_tokens']} tokens \n"
407
+ f"Output: {stat['output_tokens']} tokens \n"
408
+ f"Total: {stat['total_tokens']} tokens"
409
+ )
410
+
411
+ # Display interaction totals
412
+ st.sidebar.markdown("**Interaction Totals:**")
413
+ st.sidebar.markdown(
414
+ f"Total Input: {total_input} tokens \n"
415
+ f"Total Output: {total_output} tokens \n"
416
+ f"Total Usage: {total} tokens"
417
+ )
418
+ st.sidebar.markdown("---")
419
+
420
+ st.sidebar.markdown("")
421
+
422
+ if not check_password():
423
+ st.stop()
424
+
425
+ # Get user input before column creation
426
+ user_input = st.chat_input("Ask your question here", key="user_input")
427
+
428
+ if user_input:
429
+ # Create three columns
430
+ col1, col2, col3 = st.columns(3)
431
+
432
+ # First column - PATH-er B. (Document Display)
433
+ with col1:
434
+ st.markdown("<div class='chat-container'>", unsafe_allow_html=True)
435
+ st.subheader(f"{genparam.BOT_1_AVATAR} {genparam.BOT_1_NAME}")
436
+ st.markdown("<div class='chat-messages'>", unsafe_allow_html=True)
437
+
438
+ # Display previous messages
439
+ for message in st.session_state.chat_history_1:
440
+ if message["role"] == "user":
441
+ with st.chat_message(message["role"], avatar=genparam.USER_AVATAR):
442
+ st.markdown(message['content'])
443
+ else:
444
+ # Parse and display stored documents
445
+ documents = message['content'].split("\n\n")[2:] # Skip count line
446
+ for doc in documents:
447
+ if doc.strip():
448
+ parts = doc.split("\n")
449
+ doc_name = parts[0].replace("Document: ", "")
450
+ content = parts[1].replace("Content: ", "")
451
+ st.markdown(f"**{doc_name}**")
452
+ st.code(content)
453
+
454
+ # Add user message and get new response
455
+ st.session_state.chat_history_1.append({"role": "user", "content": user_input, "avatar": genparam.USER_AVATAR})
456
+ milvus_client, emb, vector_index_properties, vector_store_schema = setup_vector_index(
457
+ client,
458
+ wml_credentials,
459
+ VECTOR_INDEXES[st.session_state.selected_kb]["index_1"]
460
+ )
461
+ system_prompt = genparam.BOT_1_PROMPT
462
+
463
+ response = fetch_response(
464
+ user_input,
465
+ milvus_client,
466
+ emb,
467
+ vector_index_properties,
468
+ vector_store_schema,
469
+ system_prompt,
470
+ st.session_state.chat_history_1
471
+ )
472
+ st.session_state.chat_history_1.append({"role": genparam.BOT_1_NAME, "content": response, "avatar": genparam.BOT_1_AVATAR})
473
+ st.markdown("</div></div>", unsafe_allow_html=True)
474
+
475
+ # Second column - MOD-ther S. (Uses documents from first vector index)
476
+ with col2:
477
+ st.markdown("<div class='chat-container'>", unsafe_allow_html=True)
478
+ st.subheader(f"{genparam.BOT_2_AVATAR} {genparam.BOT_2_NAME}")
479
+ st.markdown("<div class='chat-messages'>", unsafe_allow_html=True)
480
+
481
+ for message in st.session_state.chat_history_2:
482
+ if message["role"] != "user":
483
+ with st.chat_message(message["role"], avatar=genparam.BOT_2_AVATAR):
484
+ st.markdown(message['content'])
485
+
486
+ st.session_state.chat_history_2.append({"role": "user", "content": user_input, "avatar": genparam.USER_AVATAR})
487
+ milvus_client, emb, vector_index_properties, vector_store_schema = setup_vector_index(
488
+ client,
489
+ wml_credentials,
490
+ VECTOR_INDEXES[st.session_state.selected_kb]["index_1"]
491
+ )
492
+ system_prompt = SYSTEM_PROMPTS[st.session_state.selected_kb]["bot_2"]
493
+
494
+ response = fetch_response(
495
+ user_input,
496
+ milvus_client,
497
+ emb,
498
+ vector_index_properties,
499
+ vector_store_schema,
500
+ system_prompt,
501
+ st.session_state.chat_history_2
502
+ )
503
+ st.session_state.chat_history_2.append({"role": genparam.BOT_2_NAME, "content": response, "avatar": genparam.BOT_2_AVATAR})
504
+ st.markdown("</div></div>", unsafe_allow_html=True)
505
+
506
+ # Third column - SYS-ter V. (Uses second vector index and chat history from second column)
507
+ with col3:
508
+ st.markdown("<div class='chat-container'>", unsafe_allow_html=True)
509
+ st.subheader(f"{genparam.BOT_3_AVATAR} {genparam.BOT_3_NAME}")
510
+ st.markdown("<div class='chat-messages'>", unsafe_allow_html=True)
511
+
512
+ for message in st.session_state.chat_history_3:
513
+ if message["role"] != "user":
514
+ with st.chat_message(message["role"], avatar=genparam.BOT_3_AVATAR):
515
+ st.markdown(message['content'])
516
+
517
+ st.session_state.chat_history_3.append({"role": "user", "content": user_input, "avatar": genparam.USER_AVATAR})
518
+ milvus_client, emb, vector_index_properties, vector_store_schema = setup_vector_index(
519
+ client,
520
+ wml_credentials,
521
+ VECTOR_INDEXES[st.session_state.selected_kb]["index_2"]
522
+ )
523
+ system_prompt = SYSTEM_PROMPTS[st.session_state.selected_kb]["bot_3"]
524
+
525
+ response = fetch_response(
526
+ user_input,
527
+ milvus_client,
528
+ emb,
529
+ vector_index_properties,
530
+ vector_store_schema,
531
+ system_prompt,
532
+ st.session_state.chat_history_3
533
+ )
534
+ st.session_state.chat_history_3.append({"role": genparam.BOT_3_NAME, "content": response, "avatar": genparam.BOT_3_AVATAR})
535
+ st.markdown("</div></div>", unsafe_allow_html=True)
536
+
537
+ # Update sidebar with new question
538
+ st.sidebar.markdown("---")
539
+ st.sidebar.markdown("**Latest Question:**")
540
+ st.sidebar.markdown(f"_{user_input}_")
541
+
542
+ if __name__ == "__main__":
543
+ main()