MVPilgrim commited on
Commit
4dd686a
·
verified ·
1 Parent(s): f9df2bb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +652 -651
app.py CHANGED
@@ -1,651 +1,652 @@
1
- import weaviate
2
- from weaviate.connect import ConnectionParams
3
- from weaviate.classes.init import AdditionalConfig, Timeout
4
-
5
- from sentence_transformers import SentenceTransformer
6
- from langchain_community.document_loaders import BSHTMLLoader
7
- from pathlib import Path
8
- from lxml import html
9
- import logging
10
- from semantic_text_splitter import HuggingFaceTextSplitter
11
- from tokenizers import Tokenizer
12
- import json
13
- import os
14
- import re
15
-
16
- import llama_cpp
17
- from llama_cpp import Llama
18
-
19
- import streamlit as st
20
- import subprocess
21
- import time
22
- import pprint
23
- import io
24
- import torch
25
-
26
-
27
- try:
28
- #############################################
29
- # Logging setup including weaviate logging. #
30
- #############################################
31
- if 'logging' not in st.session_state:
32
- weaviate_logger = logging.getLogger("httpx")
33
- weaviate_logger.setLevel(logging.WARNING)
34
- logger = logging.getLogger(__name__)
35
- logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s',level=logging.INFO)
36
- st.session_state.weaviate_logger = weaviate_logger
37
- st.session_state.logger = logger
38
- else:
39
- weaviate_logger = st.session_state.weaviate_logger
40
- logger = st.session_state.logger
41
-
42
-
43
- logger.info("###################### Program Entry ############################")
44
-
45
- logger.info(f"CUDA available: {torch.cuda.is_available()}")
46
- logger.info(f"CUDA device count: {torch.cuda.device_count()}")
47
- if torch.cuda.is_available():
48
- logger.info(f"CUDA device name: {torch.cuda.get_device_name(0)}")
49
-
50
- ##########################################################################
51
- # Asynchonously run startup.sh which run text2vec-transformers #
52
- # asynchronously and the Weaviate Vector Database server asynchronously. #
53
- ##########################################################################
54
- def runStartup():
55
- logger.info("### Running startup.sh")
56
- try:
57
- subprocess.Popen(["/app/startup.sh"])
58
- # Wait for text2vec-transformers and Weaviate DB to initialize.
59
- time.sleep(120)
60
- #subprocess.run(["/app/cmd.sh 'ps -ef'"])
61
- displayStartupshLog()
62
- except Exception as e:
63
- emsg = str(e)
64
- logger.error(f"### subprocess.run or displayStartup.shLog EXCEPTION. e: {emsg}")
65
- logger.info("### Running startup.sh complete")
66
-
67
- def displayStartupshLog():
68
- logger.info("### Displaying /app/startup.log")
69
- with open("/app/startup.log", "r") as file:
70
- line = file.readline().rstrip()
71
- while line:
72
- logger.info(line)
73
- line = file.readline().rstrip()
74
- logger.info("### End of /app/startup.log display.")
75
-
76
- if 'runStartup' not in st.session_state:
77
- st.session_state.runStartup = False
78
- if 'runStartup' not in st.session_state:
79
- logger.info("### runStartup still not in st.session_state after setting variable.")
80
- with st.spinner('Restarting...'):
81
- runStartup()
82
- try:
83
- displayStartupshLog()
84
- except Exception as e2:
85
- emsg = str(e2)
86
- logger.error(f"#### Displaying startup.log EXCEPTION. e2: {emsg}")
87
-
88
-
89
- #########################################
90
- # Function to load the CSS syling file. #
91
- #########################################
92
- def load_css(file_name):
93
- logger.info("#### load_css entered.")
94
- with open(file_name) as f:
95
- st.markdown(f'<style>{f.read()}</style>', unsafe_allow_html=True)
96
- logger.info("#### load_css exited.")
97
- if 'load_css' not in st.session_state:
98
- load_css(".streamlit/main.css")
99
- st.session_state.load_css = True
100
-
101
- # Display UI heading.
102
- st.markdown("<h1 style='text-align: center; color: #666666;'>LLM with RAG Prompting <br style='page-break-after: always;'>Proof of Concept</h1>",
103
- unsafe_allow_html=True)
104
-
105
- pathString = "/app/inputDocs"
106
- chunks = []
107
- webpageDocNames = []
108
- page_contentArray = []
109
- webpageChunks = []
110
- webpageTitles = []
111
- webpageChunksDocNames = []
112
-
113
-
114
- ############################################
115
- # Connect to the Weaviate vector database. #
116
- ############################################
117
- if 'client' not in st.session_state:
118
- logger.info("#### Create Weaviate db client connection.")
119
- client = weaviate.WeaviateClient(
120
- connection_params=ConnectionParams.from_params(
121
- http_host="localhost",
122
- http_port="8080",
123
- http_secure=False,
124
- grpc_host="localhost",
125
- grpc_port="50051",
126
- grpc_secure=False
127
- ),
128
- additional_config=AdditionalConfig(
129
- timeout=Timeout(init=60, query=1800, insert=1800), # Values in seconds
130
- )
131
- )
132
- for i in range(3):
133
- try:
134
- client.connect()
135
- st.session_state.client = client
136
- logger.info("#### Create Weaviate db client connection exited.")
137
- break
138
- except Exception as e:
139
- emsg = str(e)
140
- logger.error(f"### client.connect() EXCEPTION. e2: {emsg}")
141
- time.sleep(45)
142
- if i >= 3:
143
- raise Exception("client.connect retries exhausted.")
144
- else:
145
- client = st.session_state.client
146
-
147
-
148
- ########################################################
149
- # Read each text input file, parse it into a document, #
150
- # chunk it, collect chunks and document names. #
151
- ########################################################
152
- if not client.collections.exists("Documents") or not client.collections.exists("Chunks") :
153
- logger.info("#### Read and chunk input RAG document files.")
154
- for filename in os.listdir(pathString):
155
- logger.debug(filename)
156
- path = Path(pathString + "/" + filename)
157
- filename = filename.rstrip(".html")
158
- webpageDocNames.append(filename)
159
- htmlLoader = BSHTMLLoader(path,"utf-8")
160
- htmlData = htmlLoader.load()
161
-
162
- title = htmlData[0].metadata['title']
163
- page_content = htmlData[0].page_content
164
-
165
- # Clean data. Remove multiple newlines, etc.
166
- page_content = re.sub(r'\n+', '\n',page_content)
167
-
168
- page_contentArray.append(page_content)
169
- webpageTitles.append(title)
170
- max_tokens = 1000
171
- tokenizer = Tokenizer.from_pretrained("bert-base-uncased")
172
- logger.info(f"### tokenizer: {tokenizer}")
173
- splitter = HuggingFaceTextSplitter(tokenizer, trim_chunks=True)
174
- chunksOnePage = splitter.chunks(page_content, chunk_capacity=50)
175
-
176
- chunks = []
177
- for chnk in chunksOnePage:
178
- logger.debug(f"#### chnk in file: {chnk}")
179
- chunks.append(chnk)
180
- logger.debug(f"chunks: {chunks}")
181
- webpageChunks.append(chunks)
182
- webpageChunksDocNames.append(filename + "Chunks")
183
-
184
- logger.info(f"### filename, title: {filename}, {title}")
185
- logger.info(f"### webpageDocNames: {webpageDocNames}")
186
- logger.info("#### Read and chunk input RAG document files.")
187
-
188
-
189
- #############################################################
190
- # Create database documents and chunks schemas/collections. #
191
- # Each chunk schema points to its corresponding document. #
192
- #############################################################
193
- if not client.collections.exists("Documents"):
194
- logger.info("#### Create documents schema/collection started.")
195
- class_obj = {
196
- "class": "Documents",
197
- "description": "For first attempt at loading a Weviate database.",
198
- "vectorizer": "text2vec-transformers",
199
- "moduleConfig": {
200
- "text2vec-transformers": {
201
- "vectorizeClassName": False
202
- }
203
- },
204
- "vectorIndexType": "hnsw",
205
- "vectorIndexConfig": {
206
- "distance": "cosine",
207
- },
208
- "properties": [
209
- {
210
- "name": "title",
211
- "dataType": ["text"],
212
- "description": "HTML doc title.",
213
- "vectorizer": "text2vec-transformers",
214
- "moduleConfig": {
215
- "text2vec-transformers": {
216
- "vectorizePropertyName": True,
217
- "skip": False,
218
- "tokenization": "lowercase"
219
- }
220
- },
221
- "invertedIndexConfig": {
222
- "bm25": {
223
- "b": 0.75,
224
- "k1": 1.2
225
- },
226
- }
227
- },
228
- {
229
- "name": "content",
230
- "dataType": ["text"],
231
- "description": "HTML page content.",
232
- "moduleConfig": {
233
- "text2vec-transformers": {
234
- "vectorizePropertyName": True,
235
- "tokenization": "whitespace"
236
- }
237
- }
238
- }
239
- ]
240
- }
241
- wpCollection = client.collections.create_from_dict(class_obj)
242
- st.session_state.wpCollection = wpCollection
243
- logger.info("#### Create documents schema/collection ended.")
244
- else:
245
- wpCollection = client.collections.get("Documents")
246
- st.session_state.wpCollection = wpCollection
247
-
248
- # Create chunks in db.
249
- if not client.collections.exists("Chunks"):
250
- logger.info("#### create document chunks schema/collection started.")
251
- #client.collections.delete("Chunks")
252
- class_obj = {
253
- "class": "Chunks",
254
- "description": "Collection for document chunks.",
255
- "vectorizer": "text2vec-transformers",
256
- "moduleConfig": {
257
- "text2vec-transformers": {
258
- "vectorizeClassName": True
259
- }
260
- },
261
- "vectorIndexType": "hnsw",
262
- "vectorIndexConfig": {
263
- "distance": "cosine"
264
- },
265
- "properties": [
266
- {
267
- "name": "chunk",
268
- "dataType": ["text"],
269
- "description": "Single webpage chunk.",
270
- "vectorizer": "text2vec-transformers",
271
- "moduleConfig": {
272
- "text2vec-transformers": {
273
- "vectorizePropertyName": False,
274
- "skip": False,
275
- "tokenization": "lowercase"
276
- }
277
- }
278
- },
279
- {
280
- "name": "chunk_index",
281
- "dataType": ["int"]
282
- },
283
- {
284
- "name": "webpage",
285
- "dataType": ["Documents"],
286
- "description": "Webpage content chunks.",
287
-
288
- "invertedIndexConfig": {
289
- "bm25": {
290
- "b": 0.75,
291
- "k1": 1.2
292
- }
293
- }
294
- }
295
- ]
296
- }
297
- wpChunksCollection = client.collections.create_from_dict(class_obj)
298
- st.session_state.wpChunksCollection = wpChunksCollection
299
- logger.info("#### create document chunks schedma/collection ended.")
300
- else:
301
- wpChunksCollection = client.collections.get("Chunks")
302
- st.session_state.wpChunksCollection = wpChunksCollection
303
-
304
-
305
- ##################################################################
306
- # Create the actual document and chunks objects in the database. #
307
- ##################################################################
308
- if 'dbObjsCreated' not in st.session_state:
309
- logger.info("#### Create db document and chunk objects started.")
310
- st.session_state.dbObjsCreated = True
311
- for i, className in enumerate(webpageDocNames):
312
- logger.info("#### Creating document object.")
313
- title = webpageTitles[i]
314
- logger.debug(f"## className, title: {className}, {title}")
315
- # Create Webpage Object
316
- page_content = page_contentArray[i]
317
- # Insert the document.
318
- wpCollectionObj_uuid = wpCollection.data.insert(
319
- {
320
- "name": className,
321
- "title": title,
322
- "content": page_content
323
- }
324
- )
325
- logger.info("#### Document object created.")
326
-
327
- logger.info("#### Create chunk db objects.")
328
- st.session_state.wpChunksCollection = wpChunksCollection
329
- # Insert the chunks for the document.
330
- for i2, chunk in enumerate(webpageChunks[i]):
331
- chunk_uuid = wpChunksCollection.data.insert(
332
- {
333
- "title": title,
334
- "chunk": chunk,
335
- "chunk_index": i2,
336
- "references":
337
- {
338
- "webpage": wpCollectionObj_uuid
339
- }
340
- }
341
- )
342
- logger.info("#### Create chunk db objects created.")
343
- logger.info("#### Create db document and chunk objects ended.")
344
-
345
-
346
- #######################
347
- # Initialize the LLM. #
348
- #######################
349
- model_path = "/app/llama-2-7b-chat.Q4_0.gguf"
350
- if 'llm' not in st.session_state:
351
- logger.info("### Initializing LLM.")
352
- llm = Llama(model_path,
353
- #*,
354
- n_gpu_layers=-1,
355
- split_mode=llama_cpp.LLAMA_SPLIT_MODE_LAYER,
356
- main_gpu=0,
357
- tensor_split=None,
358
- vocab_only=False,
359
- use_mmap=True,
360
- use_mlock=False,
361
- kv_overrides=None,
362
- seed=llama_cpp.LLAMA_DEFAULT_SEED,
363
- n_ctx=2048,
364
- n_batch=512,
365
- n_threads=8,
366
- n_threads_batch=16,
367
- rope_scaling_type=llama_cpp.LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
368
- pooling_type=llama_cpp.LLAMA_POOLING_TYPE_UNSPECIFIED,
369
- rope_freq_base=0.0,
370
- rope_freq_scale=0.0,
371
- yarn_ext_factor=-1.0,
372
- yarn_attn_factor=1.0,
373
- yarn_beta_fast=32.0,
374
- yarn_beta_slow=1.0,
375
- yarn_orig_ctx=0,
376
- logits_all=False,
377
- embedding=False,
378
- offload_kqv=True,
379
- last_n_tokens_size=64,
380
- lora_base=None,
381
- lora_scale=1.0,
382
- lora_path=None,
383
- numa=False,
384
- chat_format="llama-2",
385
- chat_handler=None,
386
- draft_model=None,
387
- tokenizer=None,
388
- type_k=None,
389
- type_v=None,
390
- verbose=True
391
- )
392
- st.session_state.llm = llm
393
- logger.info("### Initializing LLM completed.")
394
- else:
395
- llm = st.session_state.llm
396
-
397
-
398
- #####################################################
399
- # Get RAG data from vector db based on user prompt. #
400
- #####################################################
401
- def getRagData(promptText):
402
- logger.info("#### getRagData() entered.")
403
- ###############################################################################
404
- # Initial the the sentence transformer and encode the query prompt.
405
- logger.debug(f"#### Encode text query prompt to create vectors. {promptText}")
406
- model = SentenceTransformer('/app/multi-qa-MiniLM-L6-cos-v1')
407
- vector = model.encode(promptText)
408
-
409
- logLevel = logger.getEffectiveLevel()
410
- if logLevel >= logging.DEBUG:
411
- wrks = str(vector)
412
- logger.debug(f"### vector: {wrks}")
413
-
414
- vectorList = []
415
- for vec in vector:
416
- vectorList.append(vec)
417
-
418
- if logLevel >= logging.DEBUG:
419
- logger.debug("#### Print vectors.")
420
- wrks = str(vectorList)
421
- logger.debug(f"vectorList: {wrks}")
422
-
423
- # Fetch chunks and print chunks.
424
- logger.debug("#### Retrieve semchunks from db using vectors from prompt.")
425
- wpChunksCollection = st.session_state.wpChunksCollection
426
- semChunks = wpChunksCollection.query.near_vector(
427
- near_vector=vectorList,
428
- distance=0.7,
429
- limit=3
430
- )
431
-
432
- if logLevel >= logging.DEBUG:
433
- wrks = str(semChunks)
434
- logger.debug(f"### semChunks[0]: {wrks}")
435
-
436
- # Print chunks, corresponding document and document title.
437
- ragData = ""
438
- logger.debug("#### Print individual retrieved chunks.")
439
- wpCollection = st.session_state.wpCollection
440
- for chunk in enumerate(semChunks.objects):
441
- logger.debug(f"#### chunk: {chunk}")
442
- ragData = ragData + chunk[1].properties['chunk'] + "\n"
443
- webpage_uuid = chunk[1].properties['references']['webpage']
444
- logger.debug(f"webpage_uuid: {webpage_uuid}")
445
- wpFromChunk = wpCollection.query.fetch_object_by_id(webpage_uuid)
446
- logger.debug(f"### wpFromChunk title: {wpFromChunk.properties['title']}")
447
- #collection = client.collections.get("Chunks")
448
- logger.debug("#### ragData: {ragData}")
449
- if ragData == "" or ragData == None:
450
- ragData = "None found."
451
- logger.info("#### getRagData() exited.")
452
- return ragData
453
-
454
-
455
- #################################################
456
- # Retrieve all RAG data for the user to review. #
457
- #################################################
458
- def getAllRagData():
459
- logger.info("#### getAllRagData() entered.")
460
-
461
- chunksCollection = client.collections.get("Chunks")
462
- response = chunksCollection.query.fetch_objects()
463
- wstrObjs = str(response.objects)
464
- logger.debug(f"### response.objects: {wstrObjs}")
465
- for o in response.objects:
466
- wstr = o.properties
467
- logger.debug(f"### o.properties: {wstr}")
468
- logger.info("#### getAllRagData() exited.")
469
- return wstrObjs
470
-
471
-
472
- ####################################################################
473
- # Prompt the LLM with the user's input and return the completion. #
474
- ####################################################################
475
- def runLLM(prompt):
476
- logger = st.session_state.logger
477
- logger.info("### runLLM entered.")
478
-
479
- max_tokens = 1000
480
- temperature = 0.3
481
- top_p = 0.1
482
- echoVal = True
483
- stop = ["Q", "\n"]
484
-
485
- modelOutput = ""
486
- #with st.spinner('Generating Completion (but slowly. 40+ seconds.)...'):
487
- #with st.markdown("<h1 style='text-align: center; color: #666666;'>LLM with RAG Prompting <br style='page-break-after: always;'>Proof of Concept</h1>",
488
- # unsafe_allow_html=True):
489
- st.session_state.spinGenMsg = True
490
- modelOutput = llm.create_chat_completion(
491
- prompt
492
- #max_tokens=max_tokens,
493
- #temperature=temperature,
494
- #top_p=top_p,
495
- #echo=echoVal,
496
- #stop=stop,
497
- )
498
- st.session_state.spinGenMsg = False
499
- if modelOutput != "":
500
- result = modelOutput["choices"][0]["message"]["content"]
501
- else:
502
- result = "No result returned."
503
- #result = str(modelOutput)
504
- logger.debug(f"### llmResult: {result}")
505
- logger.info("### runLLM exited.")
506
- return result
507
-
508
-
509
- ##########################################################################
510
- # Build a llama-2 prompt from the user prompt and RAG input if selected. #
511
- ##########################################################################
512
- def setPrompt(pprompt,ragFlag):
513
- logger = st.session_state.logger
514
- logger.info(f"### setPrompt() entered. ragFlag: {ragFlag}")
515
- if ragFlag:
516
- ragPrompt = getRagData(pprompt)
517
- st.session_state.ragpTA = ragPrompt
518
- if ragFlag != "None found.":
519
- userPrompt = pprompt + " " \
520
- + "Also, combine the following information with information in the LLM itself. " \
521
- + "Use the combined information to generate the response. " \
522
- + ragPrompt + " "
523
- else:
524
- userPrompt = pprompt
525
- else:
526
- userPrompt = pprompt
527
-
528
- fullPrompt = [
529
- {"role": "system", "content": st.session_state.sysTA},
530
- {"role": "user", "content": userPrompt}
531
- ]
532
-
533
- logger.debug(f"### userPrompt: {userPrompt}")
534
- logger.info("setPrompt exited.")
535
- return fullPrompt
536
-
537
- ##########################
538
- # Display UI text areas. #
539
- ##########################
540
- col1, col2 = st.columns(2)
541
- with col1:
542
- if 'spinGenMsg' not in st.session_state or st.session_state.spinGenMsg == False:
543
- placeHolder = st.empty()
544
- else:
545
- st.session_state.spinGenMsg = False;
546
- with st.spinner('Generating Completion...'):
547
- st.session_state.sysTAtext = st.session_state.sysTA
548
- logger.debug(f"sysTAtext: {st.session_state.sysTAtext}")
549
- wrklist = setPrompt(st.session_state.userpTA,st.selectRag)
550
- st.session_state.userpTA = wrklist[1]["content"]
551
- logger.debug(f"userpTAtext: {st.session_state.userpTA}")
552
- rsp = runLLM(wrklist)
553
- st.session_state.rspTA = rsp
554
- logger.debug(f"rspTAtext: {st.session_state.rspTA}")
555
- #if "sysTA" not in st.session_state:
556
- # st.session_state.sysTA = st.text_area(label="System Prompt",placeholder="You are a helpful AI assistant", help="Instruct the LLM about how to handle the user prompt.")
557
- #elif "sysTAtext" in st.session_state:
558
- # st.session_state.sysTA = st.text_area(label="System Prompt",value=st.session_state.sysTAtext,placeholder="You are a helpful AI assistant", help="Instruct the LLM about how to handle the user prompt.")
559
- #else:
560
- # st.session_state.sysTA = st.text_area(label="System Prompt",value=st.session_state.sysTA,placeholder="You are a helpful AI assistant", help="Instruct the LLM about how to handle the user prompt.")
561
-
562
- if "sysTA" not in st.session_state:
563
- st.session_state.sysTA = st.text_area(label="System Prompt",placeholder="You are a helpful AI assistant", help="Instruct the LLM about how to handle the user prompt.")
564
- elif "sysTAtext" in st.session_state:
565
- st.session_state.sysTA = st.text_area(label="System Prompt",value=st.session_state.sysTAtext,placeholder="You are a helpful AI assistant", help="Instruct the LLM about how to handle the user prompt.")
566
- else:
567
- st.session_state.sysTA = st.text_area(label="System Prompt",value=st.session_state.sysTA,placeholder="You are a helpful AI assistant", help="Instruct the LLM about how to handle the user prompt.")
568
-
569
- if "userpTA" not in st.session_state:
570
- st.session_state.userpTA = st.text_area(label="User Prompt",placeholder="Prompt the LLM with a question or instruction.", \
571
- help="Enter a prompt for the LLM. No special characters needed.")
572
- elif "userpTAtext" in st.session_state:
573
- st.session_state.userpTA = st.text_area (label="User Prompt",value=st.session_state.userpTAtext,placeholder="Prompt the LLM with a question or instruction.", \
574
- help="Enter a prompt for the LLM. No special characters needed.")
575
- else:
576
- st.session_state.userpTA = st.text_area(label="User Prompt",value=st.session_state.userpTA,placeholder="Prompt the LLM with a question or instruction.", \
577
- help="Enter a prompt for the LLM. No special characters needed.")
578
-
579
- with col2:
580
- if "ragpTA" not in st.session_state:
581
- st.session_state.ragpTA = st.text_area(label="RAG Response",placeholder="Output if RAG selected.",help="RAG output if enabled.")
582
- elif "ragpTAtext" in st.session_state:
583
- st.session_state.ragpTA = st.text_area(label="RAG Response",value=st.session_state.ragpTAtext,placeholder="Output if RAG selected.",help="RAG output if enabled.")
584
- else:
585
- st.session_state.ragpTA = st.text_area(label="RAG Response",value=st.session_state.ragpTA,placeholder="Output if RAG selected.",help="RAG output if enabled.")
586
-
587
- if "rspTA" not in st.session_state:
588
- st.session_state.rspTA = st.text_area(label="LLM Completion",placeholder="LLM completion.",help="Output area for LLM completion (response).")
589
- elif "rspTAtext" in st.session_state:
590
- st.session_state.rspTA = st.text_area(label="LLM Completion",value=st.session_state.rspTAtext,placeholder="LLM completion.",help="Output area for LLM completion (response).")
591
- else:
592
- st.session_state.rspTA = st.text_area(label="LLM Completion",value=st.session_state.rspTA,placeholder="LLM completion.",help="Output area for LLM completion (response).")
593
-
594
-
595
- #####################################
596
- # Run the LLM with the user prompt. #
597
- #####################################
598
- def on_runLLMButton_Clicked():
599
- logger = st.session_state.logger
600
- logger.info("### on_runLLMButton_Clicked entered.")
601
-
602
- st.session_state.spinGenMsg = True
603
-
604
- logger.info("### on_runLLMButton_Clicked exited.")
605
-
606
-
607
- #########################################
608
- # Get all the RAG data for user review. #
609
- #########################################
610
- def on_getAllRagDataButton_Clicked():
611
- logger = st.session_state.logger
612
- logger.info("### on_getAllRagButton_Clicked entered.")
613
- st.session_state.ragpTA = getAllRagData();
614
- logger.info("### on_getAllRagButton_Clicked exited.")
615
-
616
-
617
- #######################################
618
- # Reset all the input, output fields. #
619
- #######################################
620
- def on_resetButton_Clicked():
621
- logger = st.session_state.logger
622
- logger.info("### on_resetButton_Clicked entered.")
623
- st.session_state.sysTA = ""
624
- st.session_state.userpTA = ""
625
- st.session_state.ragpTA = ""
626
- st.session_state.rspTA = ""
627
- logger.info("### on_resetButton_Clicked exited.")
628
-
629
-
630
- ###########################################
631
- # Display the sidebar with a checkbox and #
632
- # text areas. #
633
- ###########################################
634
- with st.sidebar:
635
- st.selectRag = st.checkbox("Enable RAG",value=False,key="selectRag",help=None,on_change=None,args=None,kwargs=None,disabled=False,label_visibility="visible")
636
- st.runLLMButton = st.button("Run LLM Prompt",key=None,help=None,on_click=on_runLLMButton_Clicked,args=None,kwargs=None,type="secondary",disabled=False,use_container_width=False)
637
- st.getAllRagDataButton = st.button("Get All Rag Data",key=None,help=None,on_click=on_getAllRagDataButton_Clicked,args=None,kwargs=None,type="secondary",disabled=False,use_container_width=False)
638
- st.resetButton = st.button("Reset",key=None,help=None,on_click=on_resetButton_Clicked,args=None,kwargs=None,type="secondary",disabled=False,use_container_width=False)
639
-
640
- logger.info("#### Program End Execution.")
641
-
642
- except Exception as e:
643
- try:
644
- emsg = str(e)
645
- logger.error(f"Program-wide EXCEPTION. e: {emsg}")
646
- with open("/app/startup.log", "r") as file:
647
- content = file.read()
648
- logger.debug(content)
649
- except Exception as e2:
650
- emsg = str(e2)
651
- logger.error(f"#### Displaying startup.log EXCEPTION. e2: {emsg}")
 
 
1
+ import weaviate
2
+ from weaviate.connect import ConnectionParams
3
+ from weaviate.classes.init import AdditionalConfig, Timeout
4
+
5
+ from sentence_transformers import SentenceTransformer
6
+ from langchain_community.document_loaders import BSHTMLLoader
7
+ from pathlib import Path
8
+ from lxml import html
9
+ import logging
10
+ from semantic_text_splitter import HuggingFaceTextSplitter
11
+ from tokenizers import Tokenizer
12
+ import json
13
+ import os
14
+ import re
15
+
16
+ import llama_cpp
17
+ from llama_cpp import Llama
18
+
19
+ import streamlit as st
20
+ import subprocess
21
+ import time
22
+ import pprint
23
+ import io
24
+ import torch
25
+
26
+
27
+ try:
28
+ #############################################
29
+ # Logging setup including weaviate logging. #
30
+ #############################################
31
+ if 'logging' not in st.session_state:
32
+ weaviate_logger = logging.getLogger("httpx")
33
+ weaviate_logger.setLevel(logging.WARNING)
34
+ logger = logging.getLogger(__name__)
35
+ logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s',level=logging.INFO)
36
+ st.session_state.weaviate_logger = weaviate_logger
37
+ st.session_state.logger = logger
38
+ else:
39
+ weaviate_logger = st.session_state.weaviate_logger
40
+ logger = st.session_state.logger
41
+
42
+
43
+ logger.info("###################### Program Entry ############################")
44
+
45
+ logger.info(f"CUDA available: {torch.cuda.is_available()}")
46
+ logger.info(f"CUDA device count: {torch.cuda.device_count()}")
47
+ if torch.cuda.is_available():
48
+ logger.info(f"CUDA device name: {torch.cuda.get_device_name(0)}")
49
+
50
+ ##########################################################################
51
+ # Asynchonously run startup.sh which run text2vec-transformers #
52
+ # asynchronously and the Weaviate Vector Database server asynchronously. #
53
+ ##########################################################################
54
+ def runStartup():
55
+ logger.info("### Running startup.sh")
56
+ try:
57
+ subprocess.Popen(["/app/startup.sh"])
58
+ # Wait for text2vec-transformers and Weaviate DB to initialize.
59
+ time.sleep(120)
60
+ #subprocess.run(["/app/cmd.sh 'ps -ef'"])
61
+ displayStartupshLog()
62
+ except Exception as e:
63
+ emsg = str(e)
64
+ logger.error(f"### subprocess.run or displayStartup.shLog EXCEPTION. e: {emsg}")
65
+ logger.info("### Running startup.sh complete")
66
+
67
+ def displayStartupshLog():
68
+ logger.info("### Displaying /app/startup.log")
69
+ with open("/app/startup.log", "r") as file:
70
+ line = file.readline().rstrip()
71
+ while line:
72
+ logger.info(line)
73
+ line = file.readline().rstrip()
74
+ logger.info("### End of /app/startup.log display.")
75
+
76
+ if 'runStartup' not in st.session_state:
77
+ st.session_state.runStartup = False
78
+ if 'runStartup' not in st.session_state:
79
+ logger.info("### runStartup still not in st.session_state after setting variable.")
80
+ with st.spinner('Restarting...'):
81
+ runStartup()
82
+ try:
83
+ displayStartupshLog()
84
+ except Exception as e2:
85
+ emsg = str(e2)
86
+ logger.error(f"#### Displaying startup.log EXCEPTION. e2: {emsg}")
87
+
88
+
89
+ #########################################
90
+ # Function to load the CSS syling file. #
91
+ #########################################
92
+ def load_css(file_name):
93
+ logger.info("#### load_css entered.")
94
+ with open(file_name) as f:
95
+ st.markdown(f'<style>{f.read()}</style>', unsafe_allow_html=True)
96
+ logger.info("#### load_css exited.")
97
+ if 'load_css' not in st.session_state:
98
+ load_css(".streamlit/main.css")
99
+ st.session_state.load_css = True
100
+
101
+ # Display UI heading.
102
+ st.markdown("<h1 style='text-align: center; color: #666666;'>LLM with RAG Prompting <br style='page-break-after: always;'>Proof of Concept</h1>",
103
+ unsafe_allow_html=True)
104
+
105
+ pathString = "/app/inputDocs"
106
+ chunks = []
107
+ webpageDocNames = []
108
+ page_contentArray = []
109
+ webpageChunks = []
110
+ webpageTitles = []
111
+ webpageChunksDocNames = []
112
+
113
+
114
+ ############################################
115
+ # Connect to the Weaviate vector database. #
116
+ ############################################
117
+ if 'client' not in st.session_state:
118
+ logger.info("#### Create Weaviate db client connection.")
119
+ client = weaviate.WeaviateClient(
120
+ connection_params=ConnectionParams.from_params(
121
+ http_host="localhost",
122
+ http_port="8080",
123
+ http_secure=False,
124
+ grpc_host="localhost",
125
+ grpc_port="50051",
126
+ grpc_secure=False
127
+ ),
128
+ additional_config=AdditionalConfig(
129
+ timeout=Timeout(init=60, query=1800, insert=1800), # Values in seconds
130
+ )
131
+ )
132
+ for i in range(3):
133
+ try:
134
+ client.connect()
135
+ st.session_state.client = client
136
+ logger.info("#### Create Weaviate db client connection exited.")
137
+ break
138
+ except Exception as e:
139
+ emsg = str(e)
140
+ logger.error(f"### client.connect() EXCEPTION. e2: {emsg}")
141
+ time.sleep(45)
142
+ if i >= 3:
143
+ raise Exception("client.connect retries exhausted.")
144
+ else:
145
+ client = st.session_state.client
146
+
147
+
148
+ ########################################################
149
+ # Read each text input file, parse it into a document, #
150
+ # chunk it, collect chunks and document names. #
151
+ ########################################################
152
+ if not client.collections.exists("Documents") or not client.collections.exists("Chunks") :
153
+ logger.info("#### Read and chunk input RAG document files.")
154
+ for filename in os.listdir(pathString):
155
+ logger.debug(filename)
156
+ path = Path(pathString + "/" + filename)
157
+ filename = filename.rstrip(".html")
158
+ webpageDocNames.append(filename)
159
+ htmlLoader = BSHTMLLoader(path,"utf-8")
160
+ htmlData = htmlLoader.load()
161
+
162
+ title = htmlData[0].metadata['title']
163
+ page_content = htmlData[0].page_content
164
+
165
+ # Clean data. Remove multiple newlines, etc.
166
+ page_content = re.sub(r'\n+', '\n',page_content)
167
+
168
+ page_contentArray.append(page_content)
169
+ webpageTitles.append(title)
170
+ max_tokens = 1000
171
+ tokenizer = Tokenizer.from_pretrained("bert-base-uncased")
172
+ logger.info(f"### tokenizer: {tokenizer}")
173
+ splitter = HuggingFaceTextSplitter(tokenizer, trim_chunks=True)
174
+ chunksOnePage = splitter.chunks(page_content, chunk_capacity=50)
175
+
176
+ chunks = []
177
+ for chnk in chunksOnePage:
178
+ logger.debug(f"#### chnk in file: {chnk}")
179
+ chunks.append(chnk)
180
+ logger.debug(f"chunks: {chunks}")
181
+ webpageChunks.append(chunks)
182
+ webpageChunksDocNames.append(filename + "Chunks")
183
+
184
+ logger.info(f"### filename, title: {filename}, {title}")
185
+ logger.info(f"### webpageDocNames: {webpageDocNames}")
186
+ logger.info("#### Read and chunk input RAG document files.")
187
+
188
+
189
+ #############################################################
190
+ # Create database documents and chunks schemas/collections. #
191
+ # Each chunk schema points to its corresponding document. #
192
+ #############################################################
193
+ if not client.collections.exists("Documents"):
194
+ logger.info("#### Create documents schema/collection started.")
195
+ class_obj = {
196
+ "class": "Documents",
197
+ "description": "For first attempt at loading a Weviate database.",
198
+ "vectorizer": "text2vec-transformers",
199
+ "moduleConfig": {
200
+ "text2vec-transformers": {
201
+ "vectorizeClassName": False
202
+ }
203
+ },
204
+ "vectorIndexType": "hnsw",
205
+ "vectorIndexConfig": {
206
+ "distance": "cosine",
207
+ },
208
+ "properties": [
209
+ {
210
+ "name": "title",
211
+ "dataType": ["text"],
212
+ "description": "HTML doc title.",
213
+ "vectorizer": "text2vec-transformers",
214
+ "moduleConfig": {
215
+ "text2vec-transformers": {
216
+ "vectorizePropertyName": True,
217
+ "skip": False,
218
+ "tokenization": "lowercase"
219
+ }
220
+ },
221
+ "invertedIndexConfig": {
222
+ "bm25": {
223
+ "b": 0.75,
224
+ "k1": 1.2
225
+ },
226
+ }
227
+ },
228
+ {
229
+ "name": "content",
230
+ "dataType": ["text"],
231
+ "description": "HTML page content.",
232
+ "moduleConfig": {
233
+ "text2vec-transformers": {
234
+ "vectorizePropertyName": True,
235
+ "tokenization": "whitespace"
236
+ }
237
+ }
238
+ }
239
+ ]
240
+ }
241
+ wpCollection = client.collections.create_from_dict(class_obj)
242
+ st.session_state.wpCollection = wpCollection
243
+ logger.info("#### Create documents schema/collection ended.")
244
+ else:
245
+ wpCollection = client.collections.get("Documents")
246
+ st.session_state.wpCollection = wpCollection
247
+
248
+ # Create chunks in db.
249
+ if not client.collections.exists("Chunks"):
250
+ logger.info("#### create document chunks schema/collection started.")
251
+ #client.collections.delete("Chunks")
252
+ class_obj = {
253
+ "class": "Chunks",
254
+ "description": "Collection for document chunks.",
255
+ "vectorizer": "text2vec-transformers",
256
+ "moduleConfig": {
257
+ "text2vec-transformers": {
258
+ "vectorizeClassName": True
259
+ }
260
+ },
261
+ "vectorIndexType": "hnsw",
262
+ "vectorIndexConfig": {
263
+ "distance": "cosine"
264
+ },
265
+ "properties": [
266
+ {
267
+ "name": "chunk",
268
+ "dataType": ["text"],
269
+ "description": "Single webpage chunk.",
270
+ "vectorizer": "text2vec-transformers",
271
+ "moduleConfig": {
272
+ "text2vec-transformers": {
273
+ "vectorizePropertyName": False,
274
+ "skip": False,
275
+ "tokenization": "lowercase"
276
+ }
277
+ }
278
+ },
279
+ {
280
+ "name": "chunk_index",
281
+ "dataType": ["int"]
282
+ },
283
+ {
284
+ "name": "webpage",
285
+ "dataType": ["Documents"],
286
+ "description": "Webpage content chunks.",
287
+
288
+ "invertedIndexConfig": {
289
+ "bm25": {
290
+ "b": 0.75,
291
+ "k1": 1.2
292
+ }
293
+ }
294
+ }
295
+ ]
296
+ }
297
+ wpChunksCollection = client.collections.create_from_dict(class_obj)
298
+ st.session_state.wpChunksCollection = wpChunksCollection
299
+ logger.info("#### create document chunks schedma/collection ended.")
300
+ else:
301
+ wpChunksCollection = client.collections.get("Chunks")
302
+ st.session_state.wpChunksCollection = wpChunksCollection
303
+
304
+
305
+ ##################################################################
306
+ # Create the actual document and chunks objects in the database. #
307
+ ##################################################################
308
+ if 'dbObjsCreated' not in st.session_state:
309
+ logger.info("#### Create db document and chunk objects started.")
310
+ st.session_state.dbObjsCreated = True
311
+ for i, className in enumerate(webpageDocNames):
312
+ logger.info("#### Creating document object.")
313
+ title = webpageTitles[i]
314
+ logger.debug(f"## className, title: {className}, {title}")
315
+ # Create Webpage Object
316
+ page_content = page_contentArray[i]
317
+ # Insert the document.
318
+ wpCollectionObj_uuid = wpCollection.data.insert(
319
+ {
320
+ "name": className,
321
+ "title": title,
322
+ "content": page_content
323
+ }
324
+ )
325
+ logger.info("#### Document object created.")
326
+
327
+ logger.info("#### Create chunk db objects.")
328
+ st.session_state.wpChunksCollection = wpChunksCollection
329
+ # Insert the chunks for the document.
330
+ for i2, chunk in enumerate(webpageChunks[i]):
331
+ chunk_uuid = wpChunksCollection.data.insert(
332
+ {
333
+ "title": title,
334
+ "chunk": chunk,
335
+ "chunk_index": i2,
336
+ "references":
337
+ {
338
+ "webpage": wpCollectionObj_uuid
339
+ }
340
+ }
341
+ )
342
+ logger.info("#### Create chunk db objects created.")
343
+ logger.info("#### Create db document and chunk objects ended.")
344
+
345
+
346
+ #######################
347
+ # Initialize the LLM. #
348
+ #######################
349
+ #model_path = "/app/llama-2-7b-chat.Q4_0.gguf"
350
+ model_path = "Llama-3.2-3B-Instruct-Q4_K_M.gguf"
351
+ if 'llm' not in st.session_state:
352
+ logger.info("### Initializing LLM.")
353
+ llm = Llama(model_path,
354
+ #*,
355
+ n_gpu_layers=-1,
356
+ split_mode=llama_cpp.LLAMA_SPLIT_MODE_LAYER,
357
+ main_gpu=0,
358
+ tensor_split=None,
359
+ vocab_only=False,
360
+ use_mmap=True,
361
+ use_mlock=False,
362
+ kv_overrides=None,
363
+ seed=llama_cpp.LLAMA_DEFAULT_SEED,
364
+ n_ctx=2048,
365
+ n_batch=512,
366
+ n_threads=8,
367
+ n_threads_batch=16,
368
+ rope_scaling_type=llama_cpp.LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
369
+ pooling_type=llama_cpp.LLAMA_POOLING_TYPE_UNSPECIFIED,
370
+ rope_freq_base=0.0,
371
+ rope_freq_scale=0.0,
372
+ yarn_ext_factor=-1.0,
373
+ yarn_attn_factor=1.0,
374
+ yarn_beta_fast=32.0,
375
+ yarn_beta_slow=1.0,
376
+ yarn_orig_ctx=0,
377
+ logits_all=False,
378
+ embedding=False,
379
+ offload_kqv=True,
380
+ last_n_tokens_size=64,
381
+ lora_base=None,
382
+ lora_scale=1.0,
383
+ lora_path=None,
384
+ numa=False,
385
+ chat_format="llama-2",
386
+ chat_handler=None,
387
+ draft_model=None,
388
+ tokenizer=None,
389
+ type_k=None,
390
+ type_v=None,
391
+ verbose=True
392
+ )
393
+ st.session_state.llm = llm
394
+ logger.info("### Initializing LLM completed.")
395
+ else:
396
+ llm = st.session_state.llm
397
+
398
+
399
+ #####################################################
400
+ # Get RAG data from vector db based on user prompt. #
401
+ #####################################################
402
+ def getRagData(promptText):
403
+ logger.info("#### getRagData() entered.")
404
+ ###############################################################################
405
+ # Initial the the sentence transformer and encode the query prompt.
406
+ logger.debug(f"#### Encode text query prompt to create vectors. {promptText}")
407
+ model = SentenceTransformer('/app/multi-qa-MiniLM-L6-cos-v1')
408
+ vector = model.encode(promptText)
409
+
410
+ logLevel = logger.getEffectiveLevel()
411
+ if logLevel >= logging.DEBUG:
412
+ wrks = str(vector)
413
+ logger.debug(f"### vector: {wrks}")
414
+
415
+ vectorList = []
416
+ for vec in vector:
417
+ vectorList.append(vec)
418
+
419
+ if logLevel >= logging.DEBUG:
420
+ logger.debug("#### Print vectors.")
421
+ wrks = str(vectorList)
422
+ logger.debug(f"vectorList: {wrks}")
423
+
424
+ # Fetch chunks and print chunks.
425
+ logger.debug("#### Retrieve semchunks from db using vectors from prompt.")
426
+ wpChunksCollection = st.session_state.wpChunksCollection
427
+ semChunks = wpChunksCollection.query.near_vector(
428
+ near_vector=vectorList,
429
+ distance=0.7,
430
+ limit=3
431
+ )
432
+
433
+ if logLevel >= logging.DEBUG:
434
+ wrks = str(semChunks)
435
+ logger.debug(f"### semChunks[0]: {wrks}")
436
+
437
+ # Print chunks, corresponding document and document title.
438
+ ragData = ""
439
+ logger.debug("#### Print individual retrieved chunks.")
440
+ wpCollection = st.session_state.wpCollection
441
+ for chunk in enumerate(semChunks.objects):
442
+ logger.debug(f"#### chunk: {chunk}")
443
+ ragData = ragData + chunk[1].properties['chunk'] + "\n"
444
+ webpage_uuid = chunk[1].properties['references']['webpage']
445
+ logger.debug(f"webpage_uuid: {webpage_uuid}")
446
+ wpFromChunk = wpCollection.query.fetch_object_by_id(webpage_uuid)
447
+ logger.debug(f"### wpFromChunk title: {wpFromChunk.properties['title']}")
448
+ #collection = client.collections.get("Chunks")
449
+ logger.debug("#### ragData: {ragData}")
450
+ if ragData == "" or ragData == None:
451
+ ragData = "None found."
452
+ logger.info("#### getRagData() exited.")
453
+ return ragData
454
+
455
+
456
+ #################################################
457
+ # Retrieve all RAG data for the user to review. #
458
+ #################################################
459
+ def getAllRagData():
460
+ logger.info("#### getAllRagData() entered.")
461
+
462
+ chunksCollection = client.collections.get("Chunks")
463
+ response = chunksCollection.query.fetch_objects()
464
+ wstrObjs = str(response.objects)
465
+ logger.debug(f"### response.objects: {wstrObjs}")
466
+ for o in response.objects:
467
+ wstr = o.properties
468
+ logger.debug(f"### o.properties: {wstr}")
469
+ logger.info("#### getAllRagData() exited.")
470
+ return wstrObjs
471
+
472
+
473
+ ####################################################################
474
+ # Prompt the LLM with the user's input and return the completion. #
475
+ ####################################################################
476
+ def runLLM(prompt):
477
+ logger = st.session_state.logger
478
+ logger.info("### runLLM entered.")
479
+
480
+ max_tokens = 1000
481
+ temperature = 0.3
482
+ top_p = 0.1
483
+ echoVal = True
484
+ stop = ["Q", "\n"]
485
+
486
+ modelOutput = ""
487
+ #with st.spinner('Generating Completion (but slowly. 40+ seconds.)...'):
488
+ #with st.markdown("<h1 style='text-align: center; color: #666666;'>LLM with RAG Prompting <br style='page-break-after: always;'>Proof of Concept</h1>",
489
+ # unsafe_allow_html=True):
490
+ st.session_state.spinGenMsg = True
491
+ modelOutput = llm.create_chat_completion(
492
+ prompt
493
+ #max_tokens=max_tokens,
494
+ #temperature=temperature,
495
+ #top_p=top_p,
496
+ #echo=echoVal,
497
+ #stop=stop,
498
+ )
499
+ st.session_state.spinGenMsg = False
500
+ if modelOutput != "":
501
+ result = modelOutput["choices"][0]["message"]["content"]
502
+ else:
503
+ result = "No result returned."
504
+ #result = str(modelOutput)
505
+ logger.debug(f"### llmResult: {result}")
506
+ logger.info("### runLLM exited.")
507
+ return result
508
+
509
+
510
+ ##########################################################################
511
+ # Build a llama-2 prompt from the user prompt and RAG input if selected. #
512
+ ##########################################################################
513
+ def setPrompt(pprompt,ragFlag):
514
+ logger = st.session_state.logger
515
+ logger.info(f"### setPrompt() entered. ragFlag: {ragFlag}")
516
+ if ragFlag:
517
+ ragPrompt = getRagData(pprompt)
518
+ st.session_state.ragpTA = ragPrompt
519
+ if ragFlag != "None found.":
520
+ userPrompt = pprompt + " " \
521
+ + "Also, combine the following information with information in the LLM itself. " \
522
+ + "Use the combined information to generate the response. " \
523
+ + ragPrompt + " "
524
+ else:
525
+ userPrompt = pprompt
526
+ else:
527
+ userPrompt = pprompt
528
+
529
+ fullPrompt = [
530
+ {"role": "system", "content": st.session_state.sysTA},
531
+ {"role": "user", "content": userPrompt}
532
+ ]
533
+
534
+ logger.debug(f"### userPrompt: {userPrompt}")
535
+ logger.info("setPrompt exited.")
536
+ return fullPrompt
537
+
538
+ ##########################
539
+ # Display UI text areas. #
540
+ ##########################
541
+ col1, col2 = st.columns(2)
542
+ with col1:
543
+ if 'spinGenMsg' not in st.session_state or st.session_state.spinGenMsg == False:
544
+ placeHolder = st.empty()
545
+ else:
546
+ st.session_state.spinGenMsg = False;
547
+ with st.spinner('Generating Completion...'):
548
+ st.session_state.sysTAtext = st.session_state.sysTA
549
+ logger.debug(f"sysTAtext: {st.session_state.sysTAtext}")
550
+ wrklist = setPrompt(st.session_state.userpTA,st.selectRag)
551
+ st.session_state.userpTA = wrklist[1]["content"]
552
+ logger.debug(f"userpTAtext: {st.session_state.userpTA}")
553
+ rsp = runLLM(wrklist)
554
+ st.session_state.rspTA = rsp
555
+ logger.debug(f"rspTAtext: {st.session_state.rspTA}")
556
+ #if "sysTA" not in st.session_state:
557
+ # st.session_state.sysTA = st.text_area(label="System Prompt",placeholder="You are a helpful AI assistant", help="Instruct the LLM about how to handle the user prompt.")
558
+ #elif "sysTAtext" in st.session_state:
559
+ # st.session_state.sysTA = st.text_area(label="System Prompt",value=st.session_state.sysTAtext,placeholder="You are a helpful AI assistant", help="Instruct the LLM about how to handle the user prompt.")
560
+ #else:
561
+ # st.session_state.sysTA = st.text_area(label="System Prompt",value=st.session_state.sysTA,placeholder="You are a helpful AI assistant", help="Instruct the LLM about how to handle the user prompt.")
562
+
563
+ if "sysTA" not in st.session_state:
564
+ st.session_state.sysTA = st.text_area(label="System Prompt",placeholder="You are a helpful AI assistant", help="Instruct the LLM about how to handle the user prompt.")
565
+ elif "sysTAtext" in st.session_state:
566
+ st.session_state.sysTA = st.text_area(label="System Prompt",value=st.session_state.sysTAtext,placeholder="You are a helpful AI assistant", help="Instruct the LLM about how to handle the user prompt.")
567
+ else:
568
+ st.session_state.sysTA = st.text_area(label="System Prompt",value=st.session_state.sysTA,placeholder="You are a helpful AI assistant", help="Instruct the LLM about how to handle the user prompt.")
569
+
570
+ if "userpTA" not in st.session_state:
571
+ st.session_state.userpTA = st.text_area(label="User Prompt",placeholder="Prompt the LLM with a question or instruction.", \
572
+ help="Enter a prompt for the LLM. No special characters needed.")
573
+ elif "userpTAtext" in st.session_state:
574
+ st.session_state.userpTA = st.text_area (label="User Prompt",value=st.session_state.userpTAtext,placeholder="Prompt the LLM with a question or instruction.", \
575
+ help="Enter a prompt for the LLM. No special characters needed.")
576
+ else:
577
+ st.session_state.userpTA = st.text_area(label="User Prompt",value=st.session_state.userpTA,placeholder="Prompt the LLM with a question or instruction.", \
578
+ help="Enter a prompt for the LLM. No special characters needed.")
579
+
580
+ with col2:
581
+ if "ragpTA" not in st.session_state:
582
+ st.session_state.ragpTA = st.text_area(label="RAG Response",placeholder="Output if RAG selected.",help="RAG output if enabled.")
583
+ elif "ragpTAtext" in st.session_state:
584
+ st.session_state.ragpTA = st.text_area(label="RAG Response",value=st.session_state.ragpTAtext,placeholder="Output if RAG selected.",help="RAG output if enabled.")
585
+ else:
586
+ st.session_state.ragpTA = st.text_area(label="RAG Response",value=st.session_state.ragpTA,placeholder="Output if RAG selected.",help="RAG output if enabled.")
587
+
588
+ if "rspTA" not in st.session_state:
589
+ st.session_state.rspTA = st.text_area(label="LLM Completion",placeholder="LLM completion.",help="Output area for LLM completion (response).")
590
+ elif "rspTAtext" in st.session_state:
591
+ st.session_state.rspTA = st.text_area(label="LLM Completion",value=st.session_state.rspTAtext,placeholder="LLM completion.",help="Output area for LLM completion (response).")
592
+ else:
593
+ st.session_state.rspTA = st.text_area(label="LLM Completion",value=st.session_state.rspTA,placeholder="LLM completion.",help="Output area for LLM completion (response).")
594
+
595
+
596
+ #####################################
597
+ # Run the LLM with the user prompt. #
598
+ #####################################
599
+ def on_runLLMButton_Clicked():
600
+ logger = st.session_state.logger
601
+ logger.info("### on_runLLMButton_Clicked entered.")
602
+
603
+ st.session_state.spinGenMsg = True
604
+
605
+ logger.info("### on_runLLMButton_Clicked exited.")
606
+
607
+
608
+ #########################################
609
+ # Get all the RAG data for user review. #
610
+ #########################################
611
+ def on_getAllRagDataButton_Clicked():
612
+ logger = st.session_state.logger
613
+ logger.info("### on_getAllRagButton_Clicked entered.")
614
+ st.session_state.ragpTA = getAllRagData();
615
+ logger.info("### on_getAllRagButton_Clicked exited.")
616
+
617
+
618
+ #######################################
619
+ # Reset all the input, output fields. #
620
+ #######################################
621
+ def on_resetButton_Clicked():
622
+ logger = st.session_state.logger
623
+ logger.info("### on_resetButton_Clicked entered.")
624
+ st.session_state.sysTA = ""
625
+ st.session_state.userpTA = ""
626
+ st.session_state.ragpTA = ""
627
+ st.session_state.rspTA = ""
628
+ logger.info("### on_resetButton_Clicked exited.")
629
+
630
+
631
+ ###########################################
632
+ # Display the sidebar with a checkbox and #
633
+ # text areas. #
634
+ ###########################################
635
+ with st.sidebar:
636
+ st.selectRag = st.checkbox("Enable RAG",value=False,key="selectRag",help=None,on_change=None,args=None,kwargs=None,disabled=False,label_visibility="visible")
637
+ st.runLLMButton = st.button("Run LLM Prompt",key=None,help=None,on_click=on_runLLMButton_Clicked,args=None,kwargs=None,type="secondary",disabled=False,use_container_width=False)
638
+ st.getAllRagDataButton = st.button("Get All Rag Data",key=None,help=None,on_click=on_getAllRagDataButton_Clicked,args=None,kwargs=None,type="secondary",disabled=False,use_container_width=False)
639
+ st.resetButton = st.button("Reset",key=None,help=None,on_click=on_resetButton_Clicked,args=None,kwargs=None,type="secondary",disabled=False,use_container_width=False)
640
+
641
+ logger.info("#### Program End Execution.")
642
+
643
+ except Exception as e:
644
+ try:
645
+ emsg = str(e)
646
+ logger.error(f"Program-wide EXCEPTION. e: {emsg}")
647
+ with open("/app/startup.log", "r") as file:
648
+ content = file.read()
649
+ logger.debug(content)
650
+ except Exception as e2:
651
+ emsg = str(e2)
652
+ logger.error(f"#### Displaying startup.log EXCEPTION. e2: {emsg}")