MilanM commited on
Commit
9956728
·
verified ·
1 Parent(s): a8dd21f

Create neo_sages3.py

Browse files
Files changed (1) hide show
  1. neo_sages3.py +542 -0
neo_sages3.py ADDED
@@ -0,0 +1,542 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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):
129
+ credentials = Credentials(
130
+ url=st.secrets["url"],
131
+ api_key=st.secrets["api_key"]
132
+ )
133
+ apo = st.secrets["api_key"]
134
+ client = APIClient(credentials, project_id=project_id)
135
+ return credentials, client
136
+
137
+ wml_credentials, client = setup_client(st.secrets["project_id"])
138
+
139
+ def setup_vector_index(client, wml_credentials, vector_index_id):
140
+ vector_index_details = client.data_assets.get_details(vector_index_id)
141
+ vector_index_properties = vector_index_details["entity"]["vector_index"]
142
+
143
+ emb = Embeddings(
144
+ model_id=vector_index_properties["settings"]["embedding_model_id"],
145
+ #model_id="sentence-transformers/all-minilm-l12-v2",
146
+ credentials=wml_credentials,
147
+ project_id=st.secrets["project_id"],
148
+ params={
149
+ "truncate_input_tokens": 512
150
+ }
151
+ )
152
+
153
+ vector_store_schema = vector_index_properties["settings"]["schema_fields"]
154
+ connection_details = client.connections.get_details(vector_index_details["entity"]["vector_index"]["store"]["connection_id"])
155
+ connection_properties = connection_details["entity"]["properties"]
156
+
157
+ milvus_client = MilvusClient(
158
+ uri=f'https://{connection_properties.get("host")}:{connection_properties.get("port")}',
159
+ user=connection_properties.get("username"),
160
+ password=connection_properties.get("password"),
161
+ db_name=vector_index_properties["store"]["database"]
162
+ )
163
+
164
+ return milvus_client, emb, vector_index_properties, vector_store_schema
165
+
166
+ def proximity_search(question, milvus_client, emb, vector_index_properties, vector_store_schema):
167
+ query_vectors = emb.embed_query(question)
168
+ milvus_response = milvus_client.search(
169
+ collection_name=vector_index_properties["store"]["index"],
170
+ data=[query_vectors],
171
+ limit=vector_index_properties["settings"]["top_k"],
172
+ metric_type="L2",
173
+ output_fields=[
174
+ vector_store_schema.get("text"),
175
+ vector_store_schema.get("document_name"),
176
+ vector_store_schema.get("page_number")
177
+ ]
178
+ )
179
+
180
+ documents = []
181
+
182
+ for hit in milvus_response[0]:
183
+ text = hit["entity"].get(vector_store_schema.get("text"), "")
184
+ doc_name = hit["entity"].get(vector_store_schema.get("document_name"), "Unknown Document")
185
+ page_num = hit["entity"].get(vector_store_schema.get("page_number"), "N/A")
186
+
187
+ formatted_result = f"Document: {doc_name}\nContent: {text}\nPage: {page_num}\n"
188
+ documents.append(formatted_result)
189
+
190
+ joined = "\n".join(documents)
191
+ retrieved = f"""Number of Retrieved Documents: {len(documents)}\n\n{joined}"""
192
+
193
+ return retrieved
194
+
195
+ def prepare_prompt(prompt, chat_history):
196
+ if genparam.TYPE == "chat" and chat_history:
197
+ chats = "\n".join([f"{message['role']}: \"{message['content']}\"" for message in chat_history])
198
+ prompt = f"""Retrieved Contextual Information:\n__grounding__\n\nConversation History:\n{chats}\n\nNew User Input: {prompt}"""
199
+ return prompt
200
+ else:
201
+ prompt = f"""Retrieved Contextual Information:\n__grounding__\n\nUser Input: {prompt}"""
202
+ return prompt
203
+
204
+ def apply_prompt_syntax(prompt, system_prompt, prompt_template, bake_in_prompt_syntax):
205
+ model_family_syntax = {
206
+ "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""",
207
+ "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""",
208
+ "granite-13b-chat & instruct - system": """<|system|>\n{system_prompt}\n<|user|>\n{prompt}\n<|assistant|>\n\n""",
209
+ "granite-13b-chat & instruct - user": """<|user|>\n{prompt}\n<|assistant|>\n\n""",
210
+ "mistral & mixtral v2 tokenizer - system": """<s>[INST] System Prompt: {system_prompt} [/INST][INST] {prompt} [/INST]\n\n""",
211
+ "mistral & mixtral v2 tokenizer - user": """<s>[INST] {prompt} [/INST]\n\n""",
212
+ "no syntax - system": """{system_prompt}\n\n{prompt}""",
213
+ "no syntax - user": """{prompt}"""
214
+ }
215
+
216
+ if bake_in_prompt_syntax:
217
+ template = model_family_syntax[prompt_template]
218
+ if system_prompt:
219
+ return template.format(system_prompt=system_prompt, prompt=prompt)
220
+ return prompt
221
+
222
+ def generate_response(watsonx_llm, prompt_data, params):
223
+ generated_response = watsonx_llm.generate_text_stream(prompt=prompt_data, params=params)
224
+ for chunk in generated_response:
225
+ yield chunk
226
+
227
+ def fetch_response(user_input, milvus_client, emb, vector_index_properties, vector_store_schema, system_prompt, chat_history):
228
+ # Get grounding documents
229
+ grounding = proximity_search(
230
+ question=user_input,
231
+ milvus_client=milvus_client,
232
+ emb=emb,
233
+ vector_index_properties=vector_index_properties,
234
+ vector_store_schema=vector_store_schema
235
+ )
236
+
237
+ # Special handling for PATH-er B. (first column)
238
+ if chat_history == st.session_state.chat_history_1:
239
+ # Display user question first
240
+ with st.chat_message("user", avatar=genparam.USER_AVATAR):
241
+ st.markdown(user_input)
242
+
243
+ # Parse and display each document from the grounding
244
+ documents = grounding.split("\n\n")[2:] # Skip the count line and first newline
245
+ for doc in documents:
246
+ if doc.strip(): # Only process non-empty strings
247
+ parts = doc.split("\n")
248
+ doc_name = parts[0].replace("Document: ", "")
249
+ content = parts[1].replace("Content: ", "")
250
+
251
+ # Display document with delay
252
+ time.sleep(0.5)
253
+ st.markdown(f"**{doc_name}**")
254
+ st.code(content)
255
+
256
+ # Store in chat history
257
+ return grounding
258
+
259
+ # For MOD-ther S. (second column) and SYS-ter V. (third column)
260
+ else:
261
+ prompt = prepare_prompt(user_input, chat_history)
262
+ prompt_data = apply_prompt_syntax(
263
+ prompt,
264
+ system_prompt, # Using the system_prompt passed to the function
265
+ get_active_prompt_template(),
266
+ genparam.BAKE_IN_PROMPT_SYNTAX
267
+ )
268
+ prompt_data = prompt_data.replace("__grounding__", grounding)
269
+
270
+ # Add debug information to column 1 if enabled
271
+ if genparam.INPUT_DEBUG_VIEW == 1:
272
+ with st.columns(3)[0]: # Access first column
273
+ bot_name = genparam.BOT_2_NAME if chat_history == st.session_state.chat_history_2 else genparam.BOT_3_NAME
274
+ bot_avatar = genparam.BOT_2_AVATAR if chat_history == st.session_state.chat_history_2 else genparam.BOT_3_AVATAR
275
+ st.markdown(f"**{bot_avatar} {bot_name} Prompt Data:**")
276
+ st.code(prompt_data, language="text")
277
+
278
+ # Continue with normal processing for columns 2 and 3
279
+ watsonx_llm = ModelInference(
280
+ api_client=client,
281
+ model_id=get_active_model(),
282
+ verify=genparam.VERIFY
283
+ )
284
+
285
+ params = {
286
+ GenParams.DECODING_METHOD: genparam.DECODING_METHOD,
287
+ GenParams.MAX_NEW_TOKENS: genparam.MAX_NEW_TOKENS,
288
+ GenParams.MIN_NEW_TOKENS: genparam.MIN_NEW_TOKENS,
289
+ GenParams.REPETITION_PENALTY: genparam.REPETITION_PENALTY,
290
+ GenParams.STOP_SEQUENCES: genparam.STOP_SEQUENCES
291
+ }
292
+
293
+ bot_name = None
294
+ bot_avatar = None
295
+ if chat_history == st.session_state.chat_history_1:
296
+ bot_name = genparam.BOT_1_NAME
297
+ bot_avatar = genparam.BOT_1_AVATAR
298
+ elif chat_history == st.session_state.chat_history_2:
299
+ bot_name = genparam.BOT_2_NAME
300
+ bot_avatar = genparam.BOT_2_AVATAR
301
+ else:
302
+ bot_name = genparam.BOT_3_NAME
303
+ bot_avatar = genparam.BOT_3_AVATAR
304
+
305
+ with st.chat_message(bot_name, avatar=bot_avatar):
306
+ if chat_history != st.session_state.chat_history_1: # Only generate responses for columns 2 and 3
307
+ stream = generate_response(watsonx_llm, prompt_data, params)
308
+ response = st.write_stream(stream)
309
+
310
+ # Only capture tokens for MOD-ther S. and SYS-ter V.
311
+ if genparam.TOKEN_CAPTURE_ENABLED and chat_history != st.session_state.chat_history_1:
312
+ token_stats = capture_tokens(prompt_data, response, bot_name)
313
+ if token_stats:
314
+ st.session_state.token_statistics.append(token_stats)
315
+ else:
316
+ response = grounding # For column 1, we already displayed the content
317
+
318
+ return response
319
+
320
+ def capture_tokens(prompt_data, response, chat_number):
321
+ if not genparam.TOKEN_CAPTURE_ENABLED:
322
+ return
323
+
324
+ watsonx_llm = ModelInference(
325
+ api_client=client,
326
+ model_id=genparam.SELECTED_MODEL,
327
+ verify=genparam.VERIFY
328
+ )
329
+
330
+ input_tokens = watsonx_llm.tokenize(prompt=prompt_data)["result"]["token_count"]
331
+ output_tokens = watsonx_llm.tokenize(prompt=response)["result"]["token_count"]
332
+ total_tokens = input_tokens + output_tokens
333
+
334
+ return {
335
+ "bot_name": bot_name,
336
+ "input_tokens": input_tokens,
337
+ "output_tokens": output_tokens,
338
+ "total_tokens": total_tokens,
339
+ "timestamp": time.strftime("%H:%M:%S")
340
+ }
341
+
342
+ def main():
343
+ initialize_session_state()
344
+
345
+ # Apply custom styles
346
+ st.markdown(three_column_style, unsafe_allow_html=True)
347
+
348
+ # Sidebar configuration
349
+ st.sidebar.header('The Solutioning Sages')
350
+ st.sidebar.divider()
351
+
352
+ # Knowledge Base Selection
353
+ selected_kb = st.sidebar.selectbox(
354
+ "Select Knowledge Base",
355
+ KNOWLEDGE_BASE_OPTIONS,
356
+ index=KNOWLEDGE_BASE_OPTIONS.index(st.session_state.selected_kb)
357
+ )
358
+
359
+ # Update knowledge base related values if selection changes
360
+ if selected_kb != st.session_state.selected_kb:
361
+ st.session_state.selected_kb = selected_kb
362
+
363
+ # Display current knowledge base contents
364
+ with st.sidebar.expander("Knowledge Base Contents"):
365
+ for doc in VECTOR_INDEXES[selected_kb]["contents"]:
366
+ st.write(f"📄 {doc}")
367
+
368
+ # Display active model information
369
+ st.sidebar.divider()
370
+ active_model = genparam.SELECTED_MODEL_1 if genparam.ACTIVE_MODEL == 0 else genparam.SELECTED_MODEL_2
371
+ st.sidebar.markdown("**Active Model:**")
372
+ st.sidebar.code(active_model)
373
+
374
+ st.sidebar.divider()
375
+
376
+ # Display token statistics in sidebar
377
+ st.sidebar.subheader("Token Usage Statistics")
378
+
379
+ # Group token statistics by interaction (for MOD-ther S. and SYS-ter V. only)
380
+ if st.session_state.token_statistics:
381
+ current_timestamp = None
382
+ interaction_count = 0
383
+ stats_by_time = {}
384
+
385
+ # Group stats by timestamp
386
+ for stat in st.session_state.token_statistics:
387
+ if stat["timestamp"] not in stats_by_time:
388
+ stats_by_time[stat["timestamp"]] = []
389
+ stats_by_time[stat["timestamp"]].append(stat)
390
+
391
+ # Display grouped stats
392
+ for timestamp, stats in stats_by_time.items():
393
+ interaction_count += 1
394
+ st.sidebar.markdown(f"**Interaction {interaction_count}** ({timestamp})")
395
+
396
+ # Calculate total tokens for this interaction
397
+ total_input = sum(stat['input_tokens'] for stat in stats)
398
+ total_output = sum(stat['output_tokens'] for stat in stats)
399
+ total = total_input + total_output
400
+
401
+ # Display individual bot statistics
402
+ for stat in stats:
403
+ st.sidebar.markdown(
404
+ f"_{stat['bot_name']}_ \n"
405
+ f"Input: {stat['input_tokens']} tokens \n"
406
+ f"Output: {stat['output_tokens']} tokens \n"
407
+ f"Total: {stat['total_tokens']} tokens"
408
+ )
409
+
410
+ # Display interaction totals
411
+ st.sidebar.markdown("**Interaction Totals:**")
412
+ st.sidebar.markdown(
413
+ f"Total Input: {total_input} tokens \n"
414
+ f"Total Output: {total_output} tokens \n"
415
+ f"Total Usage: {total} tokens"
416
+ )
417
+ st.sidebar.markdown("---")
418
+
419
+ st.sidebar.markdown("")
420
+
421
+ if not check_password():
422
+ st.stop()
423
+
424
+ # Get user input before column creation
425
+ user_input = st.chat_input("Ask your question here", key="user_input")
426
+
427
+ if user_input:
428
+ # Create three columns
429
+ col1, col2, col3 = st.columns(3)
430
+
431
+ # First column - PATH-er B. (Document Display)
432
+ with col1:
433
+ st.markdown("<div class='chat-container'>", unsafe_allow_html=True)
434
+ st.subheader(f"{genparam.BOT_1_AVATAR} {genparam.BOT_1_NAME}")
435
+ st.markdown("<div class='chat-messages'>", unsafe_allow_html=True)
436
+
437
+ # Display previous messages
438
+ for message in st.session_state.chat_history_1:
439
+ if message["role"] == "user":
440
+ with st.chat_message(message["role"], avatar=genparam.USER_AVATAR):
441
+ st.markdown(message['content'])
442
+ else:
443
+ # Parse and display stored documents
444
+ documents = message['content'].split("\n\n")[2:] # Skip count line
445
+ for doc in documents:
446
+ if doc.strip():
447
+ parts = doc.split("\n")
448
+ doc_name = parts[0].replace("Document: ", "")
449
+ content = parts[1].replace("Content: ", "")
450
+ st.markdown(f"**{doc_name}**")
451
+ st.code(content)
452
+
453
+ # Add user message and get new response
454
+ st.session_state.chat_history_1.append({"role": "user", "content": user_input, "avatar": genparam.USER_AVATAR})
455
+ milvus_client, emb, vector_index_properties, vector_store_schema = setup_vector_index(
456
+ client,
457
+ wml_credentials,
458
+ VECTOR_INDEXES[st.session_state.selected_kb]["index_1"]
459
+ )
460
+ system_prompt = genparam.BOT_1_PROMPT
461
+
462
+ response = fetch_response(
463
+ user_input,
464
+ milvus_client,
465
+ emb,
466
+ vector_index_properties,
467
+ vector_store_schema,
468
+ system_prompt,
469
+ st.session_state.chat_history_1
470
+ )
471
+ st.session_state.chat_history_1.append({"role": genparam.BOT_1_NAME, "content": response, "avatar": genparam.BOT_1_AVATAR})
472
+ st.markdown("</div></div>", unsafe_allow_html=True)
473
+
474
+ # Second column - MOD-ther S. (Uses documents from first vector index)
475
+ with col2:
476
+ st.markdown("<div class='chat-container'>", unsafe_allow_html=True)
477
+ st.subheader(f"{genparam.BOT_2_AVATAR} {genparam.BOT_2_NAME}")
478
+ st.markdown("<div class='chat-messages'>", unsafe_allow_html=True)
479
+
480
+ for message in st.session_state.chat_history_2:
481
+ if message["role"] != "user":
482
+ with st.chat_message(message["role"], avatar=genparam.BOT_2_AVATAR):
483
+ st.markdown(message['content'])
484
+
485
+ st.session_state.chat_history_2.append({"role": "user", "content": user_input, "avatar": genparam.USER_AVATAR})
486
+ milvus_client, emb, vector_index_properties, vector_store_schema = setup_vector_index(
487
+ client,
488
+ wml_credentials,
489
+ VECTOR_INDEXES[st.session_state.selected_kb]["index_1"]
490
+ )
491
+ system_prompt = SYSTEM_PROMPTS[st.session_state.selected_kb]["bot_2"]
492
+
493
+ response = fetch_response(
494
+ user_input,
495
+ milvus_client,
496
+ emb,
497
+ vector_index_properties,
498
+ vector_store_schema,
499
+ system_prompt,
500
+ st.session_state.chat_history_2
501
+ )
502
+ st.session_state.chat_history_2.append({"role": genparam.BOT_2_NAME, "content": response, "avatar": genparam.BOT_2_AVATAR})
503
+ st.markdown("</div></div>", unsafe_allow_html=True)
504
+
505
+ # Third column - SYS-ter V. (Uses second vector index and chat history from second column)
506
+ with col3:
507
+ st.markdown("<div class='chat-container'>", unsafe_allow_html=True)
508
+ st.subheader(f"{genparam.BOT_3_AVATAR} {genparam.BOT_3_NAME}")
509
+ st.markdown("<div class='chat-messages'>", unsafe_allow_html=True)
510
+
511
+ for message in st.session_state.chat_history_3:
512
+ if message["role"] != "user":
513
+ with st.chat_message(message["role"], avatar=genparam.BOT_3_AVATAR):
514
+ st.markdown(message['content'])
515
+
516
+ st.session_state.chat_history_3.append({"role": "user", "content": user_input, "avatar": genparam.USER_AVATAR})
517
+ milvus_client, emb, vector_index_properties, vector_store_schema = setup_vector_index(
518
+ client,
519
+ wml_credentials,
520
+ VECTOR_INDEXES[st.session_state.selected_kb]["index_2"]
521
+ )
522
+ system_prompt = SYSTEM_PROMPTS[st.session_state.selected_kb]["bot_3"]
523
+
524
+ response = fetch_response(
525
+ user_input,
526
+ milvus_client,
527
+ emb,
528
+ vector_index_properties,
529
+ vector_store_schema,
530
+ system_prompt,
531
+ st.session_state.chat_history_3
532
+ )
533
+ st.session_state.chat_history_3.append({"role": genparam.BOT_3_NAME, "content": response, "avatar": genparam.BOT_3_AVATAR})
534
+ st.markdown("</div></div>", unsafe_allow_html=True)
535
+
536
+ # Update sidebar with new question
537
+ st.sidebar.markdown("---")
538
+ st.sidebar.markdown("**Latest Question:**")
539
+ st.sidebar.markdown(f"_{user_input}_")
540
+
541
+ if __name__ == "__main__":
542
+ main()