MilanM commited on
Commit
eb66c4f
·
verified ·
1 Parent(s): 1b66d76

Create tribunal_4.py

Browse files
Files changed (1) hide show
  1. tribunal_4.py +421 -0
tribunal_4.py ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
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_capture' not in st.session_state:
68
+ st.session_state.token_capture = []
69
+
70
+ # three_column_style = """
71
+ # <style>
72
+ # .stColumn {
73
+ # padding: 0.5rem;
74
+ # border-right: 1px solid #dedede;
75
+ # }
76
+ # .stColumn:last-child {
77
+ # border-right: none;
78
+ # }
79
+ # .chat-container {
80
+ # height: calc(100vh - 200px);
81
+ # overflow-y: auto;
82
+ # }
83
+ # </style>
84
+ # """
85
+
86
+ three_column_style = """
87
+ <style>
88
+ .stColumn {
89
+ padding: 0.5rem;
90
+ border-right: 1px solid #dedede;
91
+ }
92
+ .stColumn:last-child {
93
+ border-right: none;
94
+ }
95
+ .chat-container {
96
+ height: calc(100vh - 200px);
97
+ overflow-y: auto;
98
+ display: flex;
99
+ flex-direction: column;
100
+ }
101
+ .chat-messages {
102
+ display: flex;
103
+ flex-direction: column;
104
+ gap: 1rem;
105
+ }
106
+ </style>
107
+ """ # Alt Style
108
+
109
+ #-----
110
+ def get_active_model():
111
+ return genparam.SELECTED_MODEL_1 if genparam.ACTIVE_MODEL == 0 else genparam.SELECTED_MODEL_2
112
+
113
+ def get_active_prompt_template():
114
+ return genparam.PROMPT_TEMPLATE_1 if genparam.ACTIVE_MODEL == 0 else genparam.PROMPT_TEMPLATE_2
115
+
116
+ def get_active_vector_index():
117
+ return st.secrets["vector_index_id_1"] if genparam.ACTIVE_INDEX == 0 else st.secrets["vector_index_id_2"]
118
+ #-----
119
+
120
+ def setup_client(project_id):
121
+ credentials = Credentials(
122
+ url=st.secrets["url"],
123
+ api_key=st.secrets["api_key"]
124
+ )
125
+ apo = st.secrets["api_key"]
126
+ client = APIClient(credentials, project_id=project_id)
127
+ return credentials, client
128
+
129
+ wml_credentials, client = setup_client(st.secrets["project_id"])
130
+
131
+ def setup_vector_index(client, wml_credentials, vector_index_id):
132
+ vector_index_details = client.data_assets.get_details(vector_index_id)
133
+ vector_index_properties = vector_index_details["entity"]["vector_index"]
134
+
135
+ emb = Embeddings(
136
+ model_id=vector_index_properties["settings"]["embedding_model_id"],
137
+ #model_id="sentence-transformers/all-minilm-l12-v2",
138
+ credentials=wml_credentials,
139
+ project_id=st.secrets["project_id"],
140
+ params={
141
+ "truncate_input_tokens": 512
142
+ }
143
+ )
144
+
145
+ vector_store_schema = vector_index_properties["settings"]["schema_fields"]
146
+ connection_details = client.connections.get_details(vector_index_details["entity"]["vector_index"]["store"]["connection_id"])
147
+ connection_properties = connection_details["entity"]["properties"]
148
+
149
+ milvus_client = MilvusClient(
150
+ uri=f'https://{connection_properties.get("host")}:{connection_properties.get("port")}',
151
+ user=connection_properties.get("username"),
152
+ password=connection_properties.get("password"),
153
+ db_name=vector_index_properties["store"]["database"]
154
+ )
155
+
156
+ return milvus_client, emb, vector_index_properties, vector_store_schema
157
+
158
+ def proximity_search(question, milvus_client, emb, vector_index_properties, vector_store_schema):
159
+ query_vectors = emb.embed_query(question)
160
+ milvus_response = milvus_client.search(
161
+ collection_name=vector_index_properties["store"]["index"],
162
+ data=[query_vectors],
163
+ limit=vector_index_properties["settings"]["top_k"],
164
+ metric_type="L2",
165
+ output_fields=[
166
+ vector_store_schema.get("text"),
167
+ vector_store_schema.get("document_name"),
168
+ vector_store_schema.get("page_number")
169
+ ]
170
+ )
171
+
172
+ documents = []
173
+
174
+ for hit in milvus_response[0]:
175
+ text = hit["entity"].get(vector_store_schema.get("text"), "")
176
+ doc_name = hit["entity"].get(vector_store_schema.get("document_name"), "Unknown Document")
177
+ page_num = hit["entity"].get(vector_store_schema.get("page_number"), "N/A")
178
+
179
+ formatted_result = f"Document: {doc_name}\nContent: {text}\nPage: {page_num}\n"
180
+ documents.append(formatted_result)
181
+
182
+ joined = "\n".join(documents)
183
+ retrieved = f"""Number of Retrieved Documents: {len(documents)}\n\n{joined}"""
184
+
185
+ return retrieved
186
+
187
+ def prepare_prompt(prompt, chat_history):
188
+ if genparam.TYPE == "chat" and chat_history:
189
+ chats = "\n".join([f"{message['role']}: \"{message['content']}\"" for message in chat_history])
190
+ prompt = f"""Retrieved Contextual Information:\n__grounding__\n\nConversation History:\n{chats}\n\nNew User Input: {prompt}"""
191
+ return prompt
192
+ else:
193
+ prompt = f"""Retrieved Contextual Information:\n__grounding__\n\nUser Input: {prompt}"""
194
+ return prompt
195
+
196
+ def apply_prompt_syntax(prompt, system_prompt, prompt_template, bake_in_prompt_syntax):
197
+ model_family_syntax = {
198
+ "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""",
199
+ "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""",
200
+ "granite-13b-chat & instruct - system": """<|system|>\n{system_prompt}\n<|user|>\n{prompt}\n<|assistant|>\n\n""",
201
+ "granite-13b-chat & instruct - user": """<|user|>\n{prompt}\n<|assistant|>\n\n""",
202
+ "mistral & mixtral v2 tokenizer - system": """<s>[INST] System Prompt: {system_prompt} [/INST][INST] {prompt} [/INST]\n\n""",
203
+ "mistral & mixtral v2 tokenizer - user": """<s>[INST] {prompt} [/INST]\n\n""",
204
+ "no syntax - system": """{system_prompt}\n\n{prompt}""",
205
+ "no syntax - user": """{prompt}"""
206
+ }
207
+
208
+ if bake_in_prompt_syntax:
209
+ template = model_family_syntax[prompt_template]
210
+ if system_prompt:
211
+ return template.format(system_prompt=system_prompt, prompt=prompt)
212
+ return prompt
213
+
214
+ def generate_response(watsonx_llm, prompt_data, params):
215
+ generated_response = watsonx_llm.generate_text_stream(prompt=prompt_data, params=params)
216
+ for chunk in generated_response:
217
+ yield chunk
218
+
219
+ def fetch_response(user_input, milvus_client, emb, vector_index_properties, vector_store_schema, system_prompt, chat_history):
220
+ grounding = proximity_search(
221
+ question=user_input,
222
+ milvus_client=milvus_client,
223
+ emb=emb,
224
+ vector_index_properties=vector_index_properties,
225
+ vector_store_schema=vector_store_schema
226
+ )
227
+ prompt = prepare_prompt(user_input, chat_history)
228
+
229
+ prompt_data = apply_prompt_syntax(
230
+ prompt,
231
+ system_prompt,
232
+ get_active_prompt_template(),
233
+ genparam.BAKE_IN_PROMPT_SYNTAX
234
+ )
235
+
236
+ prompt_data = prompt_data.replace("__grounding__", grounding)
237
+
238
+ watsonx_llm = ModelInference(
239
+ api_client=client,
240
+ model_id=get_active_model(),
241
+ verify=genparam.VERIFY
242
+ )
243
+
244
+ params = {
245
+ GenParams.DECODING_METHOD: genparam.DECODING_METHOD,
246
+ GenParams.MAX_NEW_TOKENS: genparam.MAX_NEW_TOKENS,
247
+ GenParams.MIN_NEW_TOKENS: genparam.MIN_NEW_TOKENS,
248
+ GenParams.REPETITION_PENALTY: genparam.REPETITION_PENALTY,
249
+ GenParams.STOP_SEQUENCES: genparam.STOP_SEQUENCES
250
+ }
251
+
252
+ bot_name = None
253
+ bot_avatar = None
254
+ if chat_history == st.session_state.chat_history_1:
255
+ bot_name = genparam.BOT_1_NAME
256
+ bot_avatar = genparam.BOT_1_AVATAR
257
+ elif chat_history == st.session_state.chat_history_2:
258
+ bot_name = genparam.BOT_2_NAME
259
+ bot_avatar = genparam.BOT_2_AVATAR
260
+ else:
261
+ bot_name = genparam.BOT_3_NAME
262
+ bot_avatar = genparam.BOT_3_AVATAR
263
+
264
+ with st.chat_message(bot_name, avatar=bot_avatar):
265
+ if genparam.TOKEN_CAPTURE_ENABLED:
266
+ st.code(prompt_data, line_numbers=True, wrap_lines=True)
267
+ stream = generate_response(watsonx_llm, prompt_data, params)
268
+ response = st.write_stream(stream)
269
+ # response = st.write_stream(stream, f"<span style='color: {color};'>", unsafe_allow_html=True)
270
+
271
+ if genparam.TOKEN_CAPTURE_ENABLED:
272
+ chat_number = len(chat_history) // 2
273
+ token_calculations = capture_tokens(prompt_data, response, chat_number)
274
+ if token_calculations:
275
+ st.sidebar.code(token_calculations)
276
+
277
+ return response
278
+
279
+ def capture_tokens(prompt_data, response, chat_number):
280
+ if not genparam.TOKEN_CAPTURE_ENABLED:
281
+ return
282
+
283
+ watsonx_llm = ModelInference(
284
+ api_client=client,
285
+ model_id=genparam.SELECTED_MODEL,
286
+ verify=genparam.VERIFY
287
+ )
288
+
289
+ input_tokens = watsonx_llm.tokenize(prompt=prompt_data)["result"]["token_count"]
290
+ output_tokens = watsonx_llm.tokenize(prompt=response)["result"]["token_count"]
291
+ total_tokens = input_tokens + output_tokens
292
+
293
+ st.session_state.token_capture.append(f"chat {chat_number}: {input_tokens} + {output_tokens} = {total_tokens}")
294
+
295
+ token_calculations = "\n".join(st.session_state.token_capture)
296
+ return token_calculations
297
+
298
+ def main():
299
+ initialize_session_state()
300
+
301
+ # Apply custom styles
302
+ st.markdown(three_column_style, unsafe_allow_html=True)
303
+
304
+ # Sidebar configuration
305
+ st.sidebar.header('The Solutioning Sages')
306
+ st.sidebar.write('')
307
+
308
+ # Display user chat history in sidebar
309
+ st.sidebar.subheader("Your Questions")
310
+ for i, message in enumerate(st.session_state.chat_history_1):
311
+ if message["role"] == "user":
312
+ st.sidebar.markdown(f"**Question {i//2 + 1}:** {message['content']}")
313
+
314
+ st.sidebar.write('')
315
+ st.sidebar.write('')
316
+
317
+ if not check_password():
318
+ st.stop()
319
+
320
+ # Get user input before column creation
321
+ user_input = st.chat_input("Ask your question here", key="user_input")
322
+
323
+ if user_input:
324
+ # Create three columns
325
+ col1, col2, col3 = st.columns(3)
326
+
327
+ with col1:
328
+ st.markdown("<div class='chat-container'>", unsafe_allow_html=True)
329
+ st.subheader(f"{genparam.BOT_1_AVATAR} {genparam.BOT_1_NAME}")
330
+ st.markdown("<div class='chat-messages'>", unsafe_allow_html=True)
331
+
332
+ # Display only bot responses
333
+ for message in st.session_state.chat_history_1:
334
+ if message["role"] != "user": # Only show bot messages
335
+ with st.chat_message(message["role"], avatar=genparam.BOT_1_AVATAR):
336
+ st.markdown(message['content'])
337
+
338
+ # Add user message to history but don't display
339
+ st.session_state.chat_history_1.append({"role": "user", "content": user_input, "avatar": genparam.USER_AVATAR})
340
+ milvus_client, emb, vector_index_properties, vector_store_schema = setup_vector_index(
341
+ client,
342
+ wml_credentials,
343
+ get_active_vector_index()
344
+ )
345
+ system_prompt = genparam.BOT_1_PROMPT
346
+
347
+ response = fetch_response(
348
+ user_input,
349
+ milvus_client,
350
+ emb,
351
+ vector_index_properties,
352
+ vector_store_schema,
353
+ system_prompt,
354
+ st.session_state.chat_history_1
355
+ )
356
+ st.session_state.chat_history_1.append({"role": genparam.BOT_1_NAME, "content": response, "avatar": genparam.BOT_1_AVATAR})
357
+ st.markdown("</div></div>", unsafe_allow_html=True)
358
+
359
+ with col2:
360
+ st.markdown("<div class='chat-container'>", unsafe_allow_html=True)
361
+ st.subheader(f"{genparam.BOT_2_AVATAR} {genparam.BOT_2_NAME}")
362
+ st.markdown("<div class='chat-messages'>", unsafe_allow_html=True)
363
+
364
+ # Display only bot responses
365
+ for message in st.session_state.chat_history_2:
366
+ if message["role"] != "user": # Only show bot messages
367
+ with st.chat_message(message["role"], avatar=genparam.BOT_2_AVATAR):
368
+ st.markdown(message['content'])
369
+
370
+ # Add user message to history but don't display
371
+ st.session_state.chat_history_2.append({"role": "user", "content": user_input, "avatar": genparam.USER_AVATAR})
372
+ milvus_client, emb, vector_index_properties, vector_store_schema = setup_vector_index(
373
+ client,
374
+ wml_credentials,
375
+ get_active_vector_index()
376
+ )
377
+ system_prompt = genparam.BOT_2_PROMPT
378
+
379
+ response = fetch_response(
380
+ user_input,
381
+ milvus_client,
382
+ emb,
383
+ vector_index_properties,
384
+ vector_store_schema,
385
+ system_prompt,
386
+ st.session_state.chat_history_2
387
+ )
388
+ st.session_state.chat_history_2.append({"role": genparam.BOT_2_NAME, "content": response, "avatar": genparam.BOT_2_AVATAR})
389
+ st.markdown("</div></div>", unsafe_allow_html=True)
390
+
391
+ with col3:
392
+ st.markdown("<div class='chat-container'>", unsafe_allow_html=True)
393
+ st.subheader(f"{genparam.BOT_3_AVATAR} {genparam.BOT_3_NAME}")
394
+ st.markdown("<div class='chat-messages'>", unsafe_allow_html=True)
395
+
396
+ # Display only bot responses
397
+ for message in st.session_state.chat_history_3:
398
+ if message["role"] != "user": # Only show bot messages
399
+ with st.chat_message(message["role"], avatar=genparam.BOT_3_AVATAR):
400
+ st.markdown(message['content'])
401
+
402
+ # Add user message to history but don't display
403
+ st.session_state.chat_history_3.append({"role": "user", "content": user_input, "avatar": genparam.USER_AVATAR})
404
+ milvus_client, emb, vector_index_properties, vector_store_schema = setup_vector_index(
405
+ client,
406
+ wml_credentials,
407
+ st.secrets["vector_index_id_2"]
408
+ )
409
+ system_prompt = genparam.BOT_3_PROMPT
410
+
411
+ response = fetch_response(
412
+ user_input,
413
+ milvus_client,
414
+ emb,
415
+ vector_index_properties,
416
+ vector_store_schema,
417
+ system_prompt,
418
+ st.session_state.chat_history_3
419
+ )
420
+ st.session_state.chat_history_3.append({"role": genparam.BOT_3_NAME, "content": response, "avatar": genparam.BOT_3_AVATAR})
421
+ st.markdown("</div></div>", unsafe_allow_html=True)