-
Notifications
You must be signed in to change notification settings - Fork 1
/
rag-advanced.py
1707 lines (1516 loc) · 73.7 KB
/
rag-advanced.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import time
import json
import boto3
import pandas as pd
import logging
import streamlit as st
from pathlib import Path
import time
from PIL import Image
from io import BytesIO
from PyPDF2 import PdfWriter, PdfReader
import requests
import tiktoken
from tqdm import tqdm
import yaml
from anthropic import Anthropic
import sentencepiece
import aspose.words as aw
import multiprocessing
import uuid
from streamlit_chat import message
import fitz
import io
import json
from tokenizers import Tokenizer
from transformers import AutoTokenizer
from opensearchpy import OpenSearch, RequestsHttpConnection
from requests_aws4auth import AWS4Auth
st.set_page_config(layout="wide")
logger = logging.getLogger('sagemaker')
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())
APP_MD = json.load(open('application_metadata_complete.json', 'r'))
MODELS_LLM = {d['name']: d['endpoint'] for d in APP_MD['models-llm']}
MODELS_EMB = {d['name']: d['endpoint'] for d in APP_MD['models-emb']}
REGION = APP_MD['region']
BUCKET = APP_MD['Kendra']['bucket']
PREFIX = APP_MD['Kendra']['prefix']
OS_ENDPOINT = APP_MD['opensearch']['domain_endpoint']
KENDRA_ID = APP_MD['Kendra']['index']
KENDRA_ROLE=APP_MD['Kendra']['role']
PARENT_TEMPLATE_PATH="prompt_template"
KENDRA_S3_DATA_SOURCE_NAME=APP_MD['Kendra']['s3_data_source_name']
try:
DYNAMODB_TABLE=APP_MD['dynamodb_table']
DYNAMODB_USER=APP_MD['dynamodb_user']
except:
DYNAMODB_TABLE=""
DYNAMODB = boto3.resource('dynamodb')
S3 = boto3.client('s3', region_name=REGION)
TEXTRACT = boto3.client('textract', region_name=REGION)
KENDRA = boto3.client('kendra', region_name=REGION)
SAGEMAKER = boto3.client('sagemaker-runtime', region_name=REGION)
BEDROCK = boto3.client(service_name='bedrock-runtime',region_name='us-east-1')
COMPREHEND=boto3.client("comprehend")
# Vector dimension mappings of each embedding model
EMB_MODEL_DICT={"titan":1536,
"minilmv2":384,
"bgelarge":1024,
"gtelarge":1024,
"e5largev2":1024,
"e5largemultilingual":1024,
"gptj6b":4096,
"cohere":1024}
# Creating unique domain names for each embedding model using the domain name prefix set in the config json file
# and a corresponding suffix of the embedding model name
EMB_MODEL_DOMAIN_NAME={"titan":f"{APP_MD['opensearch']['domain_name']}_titan",
"minilmv2":f"{APP_MD['opensearch']['domain_name']}_minilm",
"bgelarge":f"{APP_MD['opensearch']['domain_name']}_bgelarge",
"gtelarge":f"{APP_MD['opensearch']['domain_name']}_gtelarge",
"e5largev2":f"{APP_MD['opensearch']['domain_name']}_e5large",
"e5largemultilingual":f"{APP_MD['opensearch']['domain_name']}_e5largeml",
"gptj6b":f"{APP_MD['opensearch']['domain_name']}_gptj6b",
"cohere":f"{APP_MD['opensearch']['domain_name']}_cohere"}
# Session state keys
if 'generate' not in st.session_state:
st.session_state['generate'] = []
if 'generated' not in st.session_state:
st.session_state['generated'] = []
if 'past' not in st.session_state:
st.session_state['past'] = []
if 'messages' not in st.session_state:
st.session_state['messages'] = []
if 'domain' not in st.session_state:
st.session_state['domain'] = ""
if 'file_name' not in st.session_state:
st.session_state['file_name'] = ''
if 'token' not in st.session_state:
st.session_state['token'] = 0
if 'text' not in st.session_state:
st.session_state['text'] = ''
if 'summary' not in st.session_state:
st.session_state['summary']=''
if 'message' not in st.session_state:
st.session_state['message'] = []
if 'current_page' not in st.session_state:
st.session_state['current_page'] = 0
if 'bytes' not in st.session_state:
st.session_state['bytes'] = None
if 'rtv' not in st.session_state:
st.session_state['rtv'] = ''
if 'page_summ' not in st.session_state:
st.session_state['page_summ'] = ''
if 'action_name' not in st.session_state:
st.session_state['action_name'] = ""
if 'chat_memory' not in st.session_state:
if DYNAMODB_TABLE:
chat_histories = DYNAMODB.Table(DYNAMODB_TABLE).get_item(Key={"UserId": DYNAMODB_USER})
if "Item" in chat_histories:
st.session_state['chat_memory']=chat_histories['Item']['messages']
else:
st.session_state['chat_memory']=[]
else:
st.session_state['chat_memory'] = []
def query_index(query):
response = KENDRA.retrieve(
IndexId=KENDRA_ID,
QueryText=query,
)
return response
@st.cache_resource
def token_counter(path):
tokenizer = AutoTokenizer.from_pretrained(path, token=APP_MD['hugginfacekey'])
return tokenizer
@st.cache_resource
def token_cohere(path):
tokenizer = Tokenizer.from_pretrained(path)
return tokenizer
def create_os_index(param, chunks):
""" Create an Opensearch Index
It uses four mappings:
- embedding: chunk vector embedding
- passage_id: document page number of chunk
- passage: chunk
- doc_id: name of document
An opensearch undex is created per embedding model selected every subsequest indexing using that model, goes to the same opensearch index.
To use a new index, change teh opensearch domain name in the configuration json file.
"""
st.write("Indexing...")
domain_endpoint = OS_ENDPOINT
service = 'es'
credentials = boto3.Session().get_credentials()
awsauth = AWS4Auth(credentials.access_key, credentials.secret_key, REGION, service, session_token=credentials.token)
os_ = OpenSearch(
hosts = [{'host': OS_ENDPOINT, 'port': 443}],
http_auth = awsauth,
use_ssl = True,
verify_certs = True,
timeout=120,
# http_compress = True, # enables gzip compression for request bodies
connection_class = RequestsHttpConnection
)
mapping = {
'settings': {
'index': {
'knn': True,
"knn.algo_param.ef_search": round(float(param["ef_search"])),
"knn.space_type": "cosinesimil",
}
},
'mappings': {
'properties': {
'embedding': {
'type': 'knn_vector',
'dimension': EMB_MODEL_DICT[param['emb'].lower()],
"method": {
"name": "hnsw",
"space_type": "l2",
"engine": param["engine"],
"parameters": {
"ef_construction": round(float(param["ef_construction"])),
"m": round(float(param["m"]))
}
}
},
'passage_id': {
'type': 'keyword'
},
'passage': {
'type': 'text'
},
'doc_id': {
'type': 'keyword'
}
}
}
}
domain_index = f"{param['domain']}_{param['engine']}"
if not os_.indices.exists(index=domain_index):
os_.indices.create(index=domain_index, body=mapping)
# Verify that the index has been created
if os_.indices.exists(index=domain_index):
st.write(f"Index {domain_index} created successfully.")
else:
st.write(f"Failed to create index '{domain_index}'.")
else:
st.write(f'{domain_index} Index already exists!')
i = 1
for pages, chunk in chunks.items(): # Iterate through dict with chunk page# and content
chunk_id = pages.split('*')[0] # take care of multiple chunks in same page (*) is used as delimiter
if "titan" in param["emb"].lower():
prompt= {
"inputText": chunk
}
body=json.dumps(prompt)
modelId = param["emb_model"]
accept = 'application/json'
contentType = 'application/json'
response = BEDROCK.invoke_model(body=body, modelId=modelId, accept=accept,contentType=contentType)
response_body = json.loads(response.get('body').read())
embedding=response_body['embedding']
elif "cohere" in param["emb"].lower():
prompt= {
"texts": [chunk],
"input_type": "search_document"
}
body=json.dumps(prompt)
modelId = param["emb_model"]
accept = "*/*"
contentType = 'application/json'
response = BEDROCK.invoke_model(body=body, modelId=modelId, accept=accept,contentType=contentType)
response_body = json.loads(response.get('body').read())
embedding=response_body['embeddings'][0]
else:
payload = {'text_inputs': [chunk]}
payload = json.dumps(payload).encode('utf-8')
response = SAGEMAKER.invoke_endpoint(EndpointName=param["emb_model"],
ContentType='application/json',
Body=payload)
model_predictions = json.loads(response['Body'].read())
embedding = model_predictions['embedding'][0]
document = {
'doc_id': st.session_state['file_name'],
'passage_id': chunk_id,
'passage': chunk,
'embedding': embedding}
try:
response = os_.index(index=domain_index, body=document)
i += 1
# Check the response to see if the indexing was successful
if response["result"] == "created":
print(f"Document indexed successfully with ID: {response['_id']}")
else:
print("Failed to index document.")
except RequestError as e:
logging.error(f"Error indexing document to index '{domain_index}': {e}")
return domain_index
def kendra_index(doc_name):
"""Create kendra s3 data source and sync files into kendra index"""
import time
response=KENDRA.list_data_sources(IndexId=KENDRA_ID)['SummaryItems']
data_sources=[x["Name"] for x in response if KENDRA_S3_DATA_SOURCE_NAME in x["Name"]]
if data_sources: # Check if s3 data source already exist and sync files
data_source_id=[x["Id"] for x in response if KENDRA_S3_DATA_SOURCE_NAME in x["Name"] ][0]
sync_response = KENDRA.start_data_source_sync_job(
Id = data_source_id,
IndexId =KENDRA_ID
)
status=True
while status:
jobs = KENDRA.list_data_source_sync_jobs(
Id = data_source_id,
IndexId = KENDRA_ID
)
# For this example, there should be one job
try:
status = jobs["History"][0]["Status"]
st.write(" Syncing data source. Status: "+status)
if status != "SYNCING":
status=False
time.sleep(2)
except:
time.sleep(2)
else: # Create a Kendra s3 data source and sync files
index_id=KENDRA_ID
response = KENDRA.create_data_source(
Name=KENDRA_S3_DATA_SOURCE_NAME,
IndexId=index_id,
Type='S3',
Configuration={
'S3Configuration': {
'BucketName': BUCKET,
'InclusionPrefixes': [
f"{PREFIX}/",
],
},
},
RoleArn=KENDRA_ROLE,
ClientToken=doc_name,
)
data_source_id=response['Id']
import time
status=True
while status:
# Get the details of the data source, such as the status
data_source_description = KENDRA.describe_data_source(
Id = data_source_id,
IndexId = index_id
)
# If status is not CREATING, then quit
status = data_source_description["Status"]
st.write(" Creating data source. Status: "+status)
time.sleep(2)
if status != "CREATING":
status=False
sync_response = KENDRA.start_data_source_sync_job(
Id = data_source_id,
IndexId = index_id
)
status=True
while status:
jobs = KENDRA.list_data_source_sync_jobs(
Id = data_source_id,
IndexId = index_id
)
try:
status = jobs["History"][0]["Status"]
st.write(" Syncing data source. Status: "+status)
if status != "SYNCING":
status=False
time.sleep(2)
except:
time.sleep(2)
def get_chunk_pages(page_dict,chunk):
"""
Getting chunk page number of each chunk to use as metadata while creating the opensearch index.
"""
token_dict={}
length=0
for pages in page_dict.keys():
length+=len(page_dict[pages].split())
token_dict[pages]=length
chunk_page={}
cumm_chunk=chunk
for page, token_size in token_dict.items():
while True:
if token_size%cumm_chunk==token_size:
try:
chunk_page[round(cumm_chunk/chunk)]+=f'_{page}'
except:
chunk_page[round(cumm_chunk/chunk)]=str(page)
break
elif token_size%cumm_chunk==0:
try:
chunk_page[round(cumm_chunk/chunk)]+=f'_{page}'
except:
chunk_page[round(cumm_chunk/chunk)]=str(page)
cumm_chunk=+chunk
break
else:
try:
chunk_page[round(cumm_chunk/chunk)]+=f'_{page}'
except:
chunk_page[round(cumm_chunk/chunk)]=str(page)
cumm_chunk+=chunk
return chunk_page
def chunker(chunk_size, file):
"""
Chunking by number of words, rule of thumb (1 token is ~3/5th a word).
I did not clean punctuation marks or do any text cleaning.
"""
chunk_size=round(chunk_size)
result={}
text=' '.join(file.values())
words=text.split()
n_docs = 1
chunk_pages=get_chunk_pages(file,chunk_size) # get page number for each chunk to use as metadata
for i in range(0, len(words), chunk_size): # iterate through doc and create chunks not exceeding chunk size
chunk_words = words[i: i+chunk_size]
chunk = ' '.join(chunk_words)
if chunk_pages[(int(i)//chunk_size)+1] in result.keys():
result[f"{chunk_pages[(int(i)//chunk_size)+1]}*{str(time.time()).split('.')[-1]}"]=chunk
else:
result[chunk_pages[(int(i)//chunk_size)+1]]=chunk
n_docs += 1
return result
def full_doc_extraction(file):
""" This is the function for the full-page retrieval technique.
It uses the metadata collected from the retrieval system to get the original source document
and extract the full page content, if pdf, or entire document content (txt, json, xml files etc.)
You can append functions to handle any other file format including web bages.
"""
link=file.split('###')[0]
if "pdf" in os.path.splitext(link)[-1]:
files=file.split('###')
bucket=files[0].split('/',4)[3]
key=files[0].split('/',4)[-1]
## Read pdf file in memory
s3 = boto3.resource('s3')
obj = s3.Object(bucket, key)
pdf_bytes=obj.get()['Body']
## open pdf file
with io.BytesIO(pdf_bytes.read()) as open_pdf_file:
doc = fitz.open(stream=open_pdf_file)
if doc.page_count>1:
## Extract the page from pdf file and send to textract
page = doc.load_page(int(files[-1]))
pix = page.get_pixmap(matrix=fitz.Matrix(2, 2))
response = TEXTRACT.detect_document_text(
Document={
'Bytes': pix.tobytes("png", 100),
}
)
blocks = response['Blocks']
bbox=[]
word=[]
for item in response['Blocks']:
if item["BlockType"] == "WORD" :
# bbox.append(item['Geometry']['BoundingBox'])
word.append(item["Text"])
result=" ".join([x for x in word])
else:
## pdf has one page, send to textract
response = TEXTRACT.detect_document_text(
Document={
'S3Object': {
'Bucket': bucket,
'Name': key,
}
}
)
blocks = response['Blocks']
bbox=[]
word=[]
for item in response['Blocks']:
if item["BlockType"] == "WORD" :
# bbox.append(item['Geometry']['BoundingBox'])
word.append(item["Text"])
result=" ".join([x for x in word])
elif "txt" in os.path.splitext(link)[-1]:
files=file.split('###')
bucket=files[0].split('/',4)[3]
key=files[0].split('/',4)[-1]
## Read pdf file in memory
s3 = boto3.resource('s3')
obj = s3.Object(bucket, key)
result=obj.get()['Body'].read().decode()
elif "html" in os.path.splitext(link)[-1]:
files=file.split('###')
bucket=files[0].split('/',4)[3]
key=files[0].split('/',4)[-1]
## Read pdf file in memory
s3 = boto3.resource('s3')
obj = s3.Object(bucket, key)
html=obj.get()['Body'].read().decode()
part1=html.split('<head>')
part2=part1[-1].split('</head>')
result=part1[0]+part2[1]
elif "xml" in os.path.splitext(link)[-1]:
pass
elif "csv" in os.path.splitext(link)[-1]:
pass
return result
def retrieval_quality_check(doc, question):
template=f"""\n\nHuman:
Here is a document:
<document>
{doc}
</document>
Here is a question:
Question: {question}
Review the document and check if the document is sufficient enough to answer the question completely.
If the complete answer is contained in the document respond with:
<answer>
yes
</answer>
Else respond with:
<answer>
no
</answer>
Your response should not include any preamble, just provide the answer alone in your response.\n\nAssistant:"""
prompt={
"prompt": template,
"max_tokens_to_sample": 10,
"temperature": 0.1,
# "top_k": 250,
# "top_p": 1,
# "stop_sequences": []
}
prompt=json.dumps(prompt)
output = BEDROCK.invoke_model(body=prompt,
modelId='anthropic.claude-v2', #Change model ID to a diffent anthropic model id
accept="application/json",
contentType="application/json")
output=output['body'].read().decode()
answer=json.loads(output)['completion']
idx1 = answer.index('<answer>')
idx2 = answer.index('</answer>')
response=answer[idx1 + len('<answer>') + 1: idx2]
print(response)
return response
def single_passage_retrieval(responses,prompt,params, handler=None):
"""
Sends one retrieved passage a time per TopK selected to the LLM together with the user prompt.
"""
models=["claude","llama","cohere","ai21","titan","mistral"] # mapping for the prompt template stored locally
chosen_model=[x for x in models if x in params['model_name'].lower()][0]
total_response=[]
# Assigning roles dynamically to the LLM based on persona
persona_dict={"General":"assistant","Finance":"finanacial analyst","Insurance":"insurance analyst","Medical":"medical expert"}
with open(f"{PARENT_TEMPLATE_PATH}/rag/{chosen_model}/prompt1.txt","r") as f:
prompt_template=f.read()
if "Kendra" in params["rag"]:
for x in range(0, round(params['K'])): # provide an answer for each number of passage retrieved by the Retriever
score = responses['ResultItems'][x]['ScoreAttributes']["ScoreConfidence"]
passage = responses['ResultItems'][x]['Content']
doc_link = responses['ResultItems'][x]['DocumentURI']
page_no=""
if os.path.splitext(doc_link)[-1]:
page_no=responses['ResultItems'][x]['DocumentAttributes'][1]['Value']['LongValue']
s3_uri=responses['ResultItems'][x]['DocumentId']
doc_name=doc_link.split('/')[-1] if doc_link.split('/')[-1] else doc_link.split('/')[-2]
qa_prompt =prompt_template.format(doc=passage, prompt=prompt, role=persona_dict[params['persona']])
if "claude" in params['model_name'].lower():
qa_prompt=f"\n\nHuman:\n{qa_prompt}\n\nAssistant:"
answer, in_token, out_token=query_endpoint(params, qa_prompt,handler)
answer1={'Answer':answer, 'Name':doc_name,'Link':doc_link, 'Score':score, 'Page': page_no, "Input Token":in_token,"Output Token":out_token}
total_response.append(answer1)
elif "OpenSearch" in params["rag"]:
for response in responses:
score = response['_score']
passage = response['_source']['passage']
doc_link = f"https://{BUCKET}.s3.amazonaws.com/file_store/{response['_source']['doc_id']}"
page_no = response['_source']['passage_id']
doc_name = response['_source']['doc_id']
qa_prompt =prompt_template.format(doc=passage, prompt=prompt, role=persona_dict[params['persona']])
if "claude" in params['model_name'].lower():
qa_prompt=f"\n\nHuman:\n{qa_prompt}\n\nAssistant:"
answer, in_token, out_token=query_endpoint(params, qa_prompt,handler)
answer1={'Answer':answer, "Name":doc_name,'Link':doc_link, 'Score':score, 'Page': page_no,"Input Token":in_token,"Output Token":out_token}
total_response.append(answer1)
if params["memory"]:
chat_history={"user" :prompt,
"assistant":answer}
if DYNAMODB_TABLE:
put_db(chat_history)
else:
st.session_state['chat_memory'].append(chat_history)
return total_response
def combined_passages_retrieval_technique(responses,prompt,params, handler=None):
"""
Function implements the combined passaged retrieval technique.
It combines topK retrieved passages into a single context and pass to the text LLM together with the user prompt.
"""
models=["claude","llama","cohere","ai21","titan","mistral"] # mapping for the prompt template stored locally
chosen_model=[x for x in models if x in params['model_name'].lower()][0]
# Assigning roles dynamically to the LLM based on persona
persona_dict={"General":"assistant","Finance":"finanacial analyst","Insurance":"insurance analyst","Medical":"medical expert"}
if "Kendra" in params["rag"]:
score = ", ".join([x['ScoreAttributes']["ScoreConfidence"] for x in responses['ResultItems'][:round(params['K'])]])
doc_link = [x['DocumentURI'] for x in responses['ResultItems'][:round(params['K'])]]
page_no=", ".join([str(x['DocumentAttributes'][1]['Value']['LongValue']) for x in responses['ResultItems'][:round(params['K'])] if os.path.splitext(x['DocumentURI'])[-1]])
doc_name=doc_name = ", ".join([x.split('/')[-1] if x.split('/')[-1] else x.split('/')[-2] for x in doc_link])
# page_no = ", ".join([x.split('/')[-1].split('-')[-1].split('.')[0] for x in doc_link])
holder={}
for x,y in enumerate(responses['ResultItems'][:round(params['K'])]):
holder[x]={"document":y["Content"], "source":y['DocumentURI']}
# Reading the prompt template based on chosen model and assigning the model roles based on chosen persona
with open(f"{PARENT_TEMPLATE_PATH}/rag/{chosen_model}/prompt1.txt","r") as f:
prompt_template=f.read()
qa_prompt =prompt_template.format(doc=holder, prompt=prompt, role=persona_dict[params['persona']])
if "claude" in params['model_name'].lower():
qa_prompt=f"\n\nHuman:\n{qa_prompt}\n\nAssistant:"
answer, in_token, out_token=query_endpoint(params, qa_prompt,handler)
answer1={'Answer':answer, 'Name':doc_name,'Link':doc_link, 'Score':score, 'Page': page_no, "Input Token":in_token,"Output Token":out_token}
elif "OpenSearch" in params["rag"]:
with open(f"{PARENT_TEMPLATE_PATH}/rag/{chosen_model}/prompt1.txt","r") as f:
prompt_template=f.read()
score = ",".join([str(x['_score']) for x in responses])
passage = [x['_source']['passage'] for x in responses]
doc_link = f"https://{BUCKET}.s3.amazonaws.com/file_store/{responses[0]['_source']['doc_id']}"
page_no = ",".join([x['_source']['passage_id'] for x in responses])
doc_name = ", ".join([x['_source']['doc_id'] for x in responses])
qa_prompt =prompt_template.format(doc=passage, prompt=prompt, role=persona_dict[params['persona']])
if "claude" in params['model_name'].lower():
qa_prompt=f"\n\nHuman:\n{qa_prompt}\n\nAssistant:"
answer, in_token, out_token=query_endpoint(params, qa_prompt,handler)
answer1={'Answer':answer, "Name":doc_name,'Link':doc_link, 'Score':score, 'Page': page_no,"Input Token":in_token,"Output Token":out_token}
# Saving chat history if enabled
if params["memory"]:
chat_history={"user" :prompt,
"assistant":answer}
# Store chat history in DynamoDb or in-memory
if DYNAMODB_TABLE:
put_db(chat_history)
else:
st.session_state['chat_memory'].append(chat_history)
return answer1
def full_page_retrieval_technique_kendra(responses,prompt,params, handler=None):
"""
Function implements the full-page retrieval technique.
It gets the metatdata (page number, doc location etc) from the topK retrieved responses.
extracts the entire page (if pdf) or entire doc (json, txt, etc.), combines all topK extraction into a single context and passes to the LLM
together with the user prompt.
"""
models=["claude","llama","cohere","ai21","titan","mistral"] # mapping for the prompt template stored locally
chosen_model=[x for x in models if x in params['model_name'].lower()][0]
# Assigning roles dynamically to the LLM based on persona
persona_dict={"General":"assistant","Finance":"finanacial analyst","Insurance":"insurance analyst","Medical":"medical expert"}
score = ", ".join([x['ScoreAttributes']["ScoreConfidence"] for x in responses['ResultItems'][:round(params['K'])]])
doc_link = [x['DocumentURI'] for x in responses['ResultItems'][:round(params['K'])]]
doc_name=", ".join([x.split('/')[-1] for x in doc_link])
sources = []
page_no=[str(x['DocumentAttributes'][1]['Value']['LongValue']) for x in responses['ResultItems'][:round(params['K'])] if os.path.splitext(x['DocumentURI'])[-1]]
holder={}
from itertools import zip_longest
for item1, item2 in zip_longest(doc_link, page_no, fillvalue=''):
sources.append('###'.join([str(item1), str(item2)]))
page_no=", ".join(page_no)
## Parallely extracting the full document pages
import multiprocessing
num_concurrent_invocations = len(sources)
pool = multiprocessing.Pool(processes=num_concurrent_invocations)
context=pool.map(full_doc_extraction, sources)
pool.close()
pool.join()
with open(f"{PARENT_TEMPLATE_PATH}/rag/{chosen_model}/prompt1.txt","r") as f:
prompt_template=f.read()
qa_prompt =prompt_template.format(doc=context, prompt=prompt, role=persona_dict[params['persona']])
if "claude" in params['model_name'].lower():
qa_prompt=f"\n\nHuman:\n{qa_prompt}\n\nAssistant:"
answer, in_token, out_token=query_endpoint(params, qa_prompt,handler)
answer1={'Answer':answer, 'Name':doc_name,'Link':doc_link, 'Score':score, 'Page': page_no, "Input Token":in_token,"Output Token":out_token}
if params["memory"]:
chat_history={"user" :prompt,
"assistant":answer}
if DYNAMODB_TABLE:
put_db(chat_history)
else:
st.session_state['chat_memory'].append(chat_history)
return answer1
def doc_qna_endpoint(endpoint, responses,prompt,params, handler=None):
"""This function implements the retrieval technique selected for each retriever, collects retrieved passage metadata and queries the
Text generation LLm endpoint.
"""
total_response=[]
# If auto retriever technique is selected, the an interim LLM call is made to check the quality of a single retrieved passage
if params["auto_rtv"]:
passage = responses['ResultItems'][0]['Content']
q_c=retrieval_quality_check(passage, prompt)
# If the single passage contains sufficient information, pass to the final LLM to get a response
if "yes" in q_c:
params["K"]=1
total_response=single_passage_retrieval(responses,prompt,params, handler)
return total_response
else:
# If not, call the full_page_retriever technique with topK=3
params["K"]=3
answer1=full_page_retrieval_technique_kendra(responses,prompt,params, handler)
total_response.append(answer1)
return total_response
else:
if "Kendra" in params["rag"]:
if 'combined-passages' in params['method']:
answer1=combined_passages_retrieval_technique(responses,prompt,params, handler)
total_response.append(answer1)
return total_response
elif 'full-pages' in params['method']:
answer1=full_page_retrieval_technique_kendra(responses,prompt,params, handler)
total_response.append(answer1)
return total_response
elif 'single-passages' in params['method']:
total_response=single_passage_retrieval(responses,prompt,params, handler)
return total_response
elif "OpenSearch" in params["rag"]:
if 'single-passages' in params['method']:
total_response=single_passage_retrieval(responses,prompt,params, handler)
return total_response
elif 'combined-passages' or 'full-pages' in params['method']:
answer1=combined_passages_retrieval_technique(responses,prompt,params, handler)
total_response.append(answer1)
return total_response
def llm_memory(question, params=None):
""" This function determines the context of each new question looking at the conversation history...
to send the appropiate question to the retriever.
Messages are stored in DynamoDb if a table is provided or in memory, in the absence of a provided DynamoDb table
"""
if DYNAMODB_TABLE:
chat_histories = DYNAMODB.Table(DYNAMODB_TABLE).get_item(Key={"UserId": DYNAMODB_USER})
if "Item" in chat_histories:
st.session_state['chat_memory']=chat_histories['Item']['messages']
else:
st.session_state['chat_memory']=[]
chat_string = ""
for entry in st.session_state['chat_memory']:
chat_string += f"user: {entry['user']}\nassistant: {entry['assistant']}\n"
memory_template = f"""\n\nHuman:
Here is the history of your conversation dialogue with a user:
<history>
{chat_string}
</history>
Here is a new question from the user:
user: {question}
Your task is to determine if the question is a follow-up to the previous conversation:
- If it is, rephrase the question as an independent question while retaining the original intent.
- If it is not, respond with "_no_".
Remember, your role is not to answer the question!
Format your response as:
<response>
answer
</response>\n\nAssistant:"""
if chat_string:
inference_modifier = {'max_tokens_to_sample':70,
"temperature":0.1,
}
llm = Bedrock(model_id='anthropic.claude-v2', client=BEDROCK, model_kwargs = inference_modifier,
streaming=False, # Toggle this to turn streaming on or off
callbacks=[StreamingStdOutCallbackHandler() ])
answer=llm(memory_template)
idx1 = answer.index('<response>')
idx2 = answer.index('</response>')
question_2=answer[idx1 + len('<response>') + 1: idx2]
if '_no_' not in question_2:
question=question_2
print(question)
return question
def put_db(messages):
"""Store long term chat history in DynamoDB"""
chat_item = {
"UserId": DYNAMODB_USER,
"messages": [messages] # Assuming 'messages' is a list of dictionaries
}
# Check if the user already exists in the table
existing_item = DYNAMODB.Table(DYNAMODB_TABLE).get_item(Key={"UserId": DYNAMODB_USER})
# If the user exists, append new messages to the existing ones
if "Item" in existing_item:
existing_messages = existing_item["Item"]["messages"]
chat_item["messages"] = existing_messages + [messages]
response = DYNAMODB.Table(DYNAMODB_TABLE).put_item(
Item=chat_item
)
def llm_streamer():
output = ""
i = 1
if stream:
for event in stream:
chunk = event.get('chunk')
if chunk:
chunk_obj = json.loads(chunk.get('bytes').decode())
text = chunk_obj["generation"]
output+=text
print(f'{text}', end="")
i+=1
def query_endpoint(params, qa_prompt, handler=None):
"""
Function to query the LLM endpoint and count tokens in and out.
"""
if 'ai21' in params['model_name'].lower():
import json
prompt={
"prompt": qa_prompt,
"maxTokens": params['max_len'],
"temperature": round(params['temp'],2),
"topP": params['top_p'],
}
prompt=json.dumps(prompt)
response = BEDROCK.invoke_model(body=prompt,
modelId=params['endpoint-llm'],
accept="application/json",
contentType="application/json")
answer=response['body'].read().decode()
answer=json.loads(answer)
input_token=len(answer['prompt']['tokens'])
output_token=len(answer['completions'][0]['data']['tokens'])
tokens=input_token+output_token
answer=answer['completions'][0]['data']['text']
st.session_state['token']+=tokens
elif 'claude' in params['model_name'].lower():
import json
qa_prompt=f"\n\nHuman:\n{qa_prompt}\n\nAssistant:"
prompt={
"prompt": qa_prompt,
"max_tokens_to_sample": round(params['max_len']),
"temperature": params['temp'],
# "top_k": 250,
"top_p":params['top_p'],
# "stop_sequences": []
}
prompt=json.dumps(prompt)
response = BEDROCK.invoke_model_with_response_stream(body=prompt, modelId=params['endpoint-llm'], accept="application/json", contentType="application/json")
stream = response.get('body')
answer = ""
i = 1
if stream:
for event in stream:
chunk = event.get('chunk')
if chunk:
chunk_obj = json.loads(chunk.get('bytes').decode())
text = chunk_obj['completion']
answer+=text
handler.markdown(answer.replace("$","USD ").replace("%", " percent"))
i+=1
claude = Anthropic()
input_token=claude.count_tokens(qa_prompt)
output_token=claude.count_tokens(answer)
tokens=claude.count_tokens(f"{qa_prompt} {answer}")
st.session_state['token']+=tokens
elif 'titan' in params['model_name'].lower():
import json
encoding = tiktoken.get_encoding('cl100k_base') #using openai tokenizer, replace with Titan's tokenizer
prompt={
"inputText": qa_prompt,
"textGenerationConfig": {
"maxTokenCount": params['max_len'],
"temperature":params['temp'],
"topP":params['top_p'],
},
}
prompt=json.dumps(prompt)
response = BEDROCK.invoke_model_with_response_stream(body=prompt, modelId=params['endpoint-llm'], accept="application/json", contentType="application/json")
stream = response.get('body')
answer = ""
i = 1
if stream:
for event in stream:
chunk = event.get('chunk')
if chunk:
chunk_obj = json.loads(chunk.get('bytes').decode())
text = chunk_obj["outputText"]
answer+=text
handler.markdown(answer.replace("$","USD ").replace("%", " percent"))
i+=1
input_token=len(encoding.encode(qa_prompt))
output_token=len(encoding.encode(answer))
tokens=len(encoding.encode(f"{qa_prompt} {answer}"))
st.session_state['token']+=tokens
elif 'cohere' in params['model_name'].lower():
import json
prompt={
"prompt": qa_prompt,
"max_tokens": round(params['max_len']),
"temperature": params['temp'],
"return_likelihoods": "GENERATION"
}
prompt=json.dumps(prompt)
response = BEDROCK.invoke_model_with_response_stream(body=prompt, modelId=params['endpoint-llm'], accept="application/json", contentType="application/json")
stream = response.get('body')
answer = ""
i = 1
if stream:
for event in stream:
chunk = event.get('chunk')
if chunk:
chunk_obj = json.loads(chunk.get('bytes').decode())
text = chunk_obj["generations"][0]['text']
answer+=text
handler.markdown(answer.replace("$","USD ").replace("%", " percent"))
i+=1
encoding=token_cohere("Cohere/command-nightly")
input_token=len(encoding.encode(qa_prompt))
output_token=len(encoding.encode(answer))
tokens=len(encoding.encode(f"{qa_prompt} {answer}"))
st.session_state['token']+=tokens
elif 'mistral' in params['model_name'].lower():
import json
payload = {
"inputs": qa_prompt,
"parameters": {"max_new_tokens": params['max_len'],
"top_p": params['top_p'] if params['top_p']<1 else 0.99 ,
"temperature": params['temp'] if params['temp']>0 else 0.01,
"return_full_text": False,}
}
output=SAGEMAKER.invoke_endpoint(Body=json.dumps(payload), EndpointName=params['endpoint-llm'],ContentType="application/json")
answer=json.loads(output['Body'].read().decode())[0]['generated_text']
tkn=token_counter("mistralai/Mistral-7B-v0.1")
input_token=len(tkn.encode(qa_prompt))
output_token=len(tkn.encode(answer))
tokens=len(tkn.encode(f"{qa_prompt} {answer}"))
st.session_state['token']+=tokens
elif 'llama2' in params['model_name'].lower():
import json
if "bedrock" in params['model_name'].lower():
prompt={
"prompt": qa_prompt,
"max_gen_len":params['max_len'],
"temperature":params['temp'] if params['temp']>0 else 0.01,
"top_p": params['top_p'] if params['top_p']<1 else 0.99
}
prompt=json.dumps(prompt)
# st.write(prompt)
response = BEDROCK.invoke_model_with_response_stream(body=prompt, modelId=params['endpoint-llm'], accept="application/json", contentType="application/json")
stream = response.get('body')
answer = ""
i = 1
if stream:
for event in stream:
chunk = event.get('chunk')
if chunk:
chunk_obj = json.loads(chunk.get('bytes').decode())
text = chunk_obj["generation"]
answer+=text
handler.markdown(answer.replace("$","USD ").replace("%", " percent"))
i+=1
else:
payload = {
"inputs": qa_prompt,
"parameters": {"max_new_tokens": params['max_len'],