MilanM commited on
Commit
370ab8d
·
verified ·
1 Parent(s): 4761be0

Create tribunal_3.py

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