-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathlambda_function.py
7519 lines (6010 loc) · 265 KB
/
lambda_function.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 json
import boto3
import os
import time
import datetime
import PyPDF2
import csv
import re
import traceback
import requests
import base64
import operator
import uuid
import functools
from botocore.config import Config
from botocore.exceptions import ClientError
from io import BytesIO
from urllib import parse
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.docstore.document import Document
from langchain.chains.summarize import load_summarize_chain
from langchain_core.prompts import MessagesPlaceholder, ChatPromptTemplate
from langchain.memory import ConversationBufferWindowMemory
from langchain_aws import ChatBedrock
from langchain_community.vectorstores.opensearch_vector_search import OpenSearchVectorSearch
from multiprocessing import Process, Pipe
from langchain_aws import BedrockEmbeddings
from langchain_community.vectorstores.faiss import FAISS
# from langchain.agents import tool
from langchain_core.tools import tool
from bs4 import BeautifulSoup
from pytz import timezone
from langchain_community.tools.tavily_search import TavilySearchResults
from PIL import Image
from opensearchpy import OpenSearch
from langchain_core.agents import AgentAction, AgentFinish
from langchain_core.messages import BaseMessage, HumanMessage, AIMessage, SystemMessage, ToolMessage
from langgraph.prebuilt.tool_executor import ToolExecutor
from langgraph.graph import START, END, StateGraph
from langgraph.prebuilt import ToolNode
from langgraph.graph.message import add_messages
from langgraph.prebuilt import tools_condition
from pydantic.v1 import BaseModel, Field
from typing import Any, List, Tuple, Dict, Optional, cast, Literal, Sequence, Union
from typing_extensions import Annotated, TypedDict
from langchain_aws import AmazonKnowledgeBasesRetriever
from tavily import TavilyClient
from dataclasses import dataclass, field
from langchain_core.runnables import RunnableConfig, ensure_config
from langchain_core.tools import InjectedToolArg
from langgraph.prebuilt import InjectedState
s3 = boto3.client('s3')
s3_bucket = os.environ.get('s3_bucket') # bucket name
s3_prefix = os.environ.get('s3_prefix')
callLogTableName = os.environ.get('callLogTableName')
path = os.environ.get('path')
doc_prefix = s3_prefix+'/'
debugMessageMode = os.environ.get('debugMessageMode', 'false')
agentLangMode = 'kor'
projectName = os.environ.get('projectName')
opensearch_account = os.environ.get('opensearch_account')
opensearch_passwd = os.environ.get('opensearch_passwd')
opensearch_url = os.environ.get('opensearch_url')
LLM_for_chat = json.loads(os.environ.get('LLM_for_chat'))
LLM_for_multimodal= json.loads(os.environ.get('LLM_for_multimodal'))
LLM_embedding = json.loads(os.environ.get('LLM_embedding'))
selected_chat = 0
length_of_models = 1
selected_multimodal = 0
selected_embedding = 0
separated_chat_history = os.environ.get('separated_chat_history')
enableParentDocumentRetrival = os.environ.get('enableParentDocumentRetrival')
enableHybridSearch = os.environ.get('enableHybridSearch')
useParrelWebSearch = True
useEnhancedSearch = True
vectorIndexName = os.environ.get('vectorIndexName')
index_name = vectorIndexName
grade_state = "LLM" # LLM, PRIORITY_SEARCH, OTHERS
numberOfDocs = 2
minDocSimilarity = 400
prompt_flow_name = os.environ.get('prompt_flow_name')
rag_prompt_flow_name = os.environ.get('rag_prompt_flow_name')
knowledge_base_name = os.environ.get('knowledge_base_name')
"""
multi_region_models = [ # claude sonnet 3.5
{
"bedrock_region": "us-west-2", # Oregon
"model_type": "claude3.5",
"model_id": "anthropic.claude-3-5-sonnet-20240620-v1:0"
},
{
"bedrock_region": "us-east-1", # N.Virginia
"model_type": "claude3.5",
"model_id": "anthropic.claude-3-5-sonnet-20240620-v1:0"
},
{
"bedrock_region": "eu-central-1", # Frankfurt
"model_type": "claude3.5",
"model_id": "anthropic.claude-3-5-sonnet-20240620-v1:0"
},
{
"bedrock_region": "ap-northeast-1", # Tokyo
"model_type": "claude3.5",
"model_id": "anthropic.claude-3-5-sonnet-20240620-v1:0"
}
]
"""
multi_region_models = [ # claude sonnet 3.0
{
"bedrock_region": "us-west-2", # Oregon
"model_type": "claude3",
"model_id": "anthropic.claude-3-sonnet-20240229-v1:0"
},
{
"bedrock_region": "us-east-1", # N.Virginia
"model_type": "claude3",
"model_id": "anthropic.claude-3-sonnet-20240229-v1:0"
},
{
"bedrock_region": "ca-central-1", # Canada
"model_type": "claude3",
"model_id": "anthropic.claude-3-sonnet-20240229-v1:0"
},
{
"bedrock_region": "eu-west-2", # London
"model_type": "claude3",
"model_id": "anthropic.claude-3-sonnet-20240229-v1:0"
},
{
"bedrock_region": "sa-east-1", # Sao Paulo
"model_type": "claude3",
"model_id": "anthropic.claude-3-sonnet-20240229-v1:0"
}
]
multi_region = 'enable'
titan_embedding_v1 = [ # dimension = 1536
{
"bedrock_region": "us-west-2", # Oregon
"model_type": "titan",
"model_id": "amazon.titan-embed-text-v1"
},
{
"bedrock_region": "us-east-1", # N.Virginia
"model_type": "titan",
"model_id": "amazon.titan-embed-text-v1"
}
]
priority_search_embedding = titan_embedding_v1
selected_ps_embedding = 0
reference_docs = []
# api key to get weather information in agent
secretsmanager = boto3.client('secretsmanager')
try:
get_weather_api_secret = secretsmanager.get_secret_value(
SecretId=f"openweathermap-{projectName}"
)
#print('get_weather_api_secret: ', get_weather_api_secret)
secret = json.loads(get_weather_api_secret['SecretString'])
#print('secret: ', secret)
weather_api_key = secret['weather_api_key']
except Exception as e:
raise e
# api key to use LangSmith
langsmith_api_key = ""
try:
get_langsmith_api_secret = secretsmanager.get_secret_value(
SecretId=f"langsmithapikey-{projectName}"
)
#print('get_langsmith_api_secret: ', get_langsmith_api_secret)
secret = json.loads(get_langsmith_api_secret['SecretString'])
#print('secret: ', secret)
langsmith_api_key = secret['langsmith_api_key']
langchain_project = secret['langchain_project']
except Exception as e:
raise e
if langsmith_api_key:
os.environ["LANGCHAIN_API_KEY"] = langsmith_api_key
os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_PROJECT"] = langchain_project
# api key to use Tavily Search
tavily_api_key = []
try:
get_tavily_api_secret = secretsmanager.get_secret_value(
SecretId=f"tavilyapikey-{projectName}"
)
#print('get_tavily_api_secret: ', get_tavily_api_secret)
secret = json.loads(get_tavily_api_secret['SecretString'])
# print('secret: ', secret)
if secret['tavily_api_key']:
tavily_api_key = json.loads(secret['tavily_api_key'])
# print('tavily_api_key: ', tavily_api_key)
except Exception as e:
raise e
def check_tavily_secret(tavily_api_key):
query = 'what is LangGraph'
valid_keys = ""
for i, key in enumerate(tavily_api_key):
try:
tavily_client = TavilyClient(api_key=key)
response = tavily_client.search(query, max_results=1)
# print('tavily response: ', response)
if 'results' in response and len(response['results']):
print('the valid tavily api keys: ', i)
valid_keys = key
break
except Exception as e:
print('Exception: ', e)
# print('valid_keys: ', valid_keys)
return valid_keys
tavily_key = check_tavily_secret(tavily_api_key)
# print('tavily_api_key: ', tavily_api_key)
os.environ["TAVILY_API_KEY"] = tavily_key
def tavily_search(query, k):
docs = []
try:
tavily_client = TavilyClient(api_key=tavily_key)
response = tavily_client.search(query, max_results=k)
# print('tavily response: ', response)
for r in response["results"]:
name = r.get("title")
if name is None:
name = 'WWW'
docs.append(
Document(
page_content=r.get("content"),
metadata={
'name': name,
'url': r.get("url"),
'from': 'tavily'
},
)
)
except Exception as e:
print('Exception: ', e)
return docs
# result = tavily_search('what is LangChain', 2)
# print('search result: ', result)
os_client = OpenSearch(
hosts = [{
'host': opensearch_url.replace("https://", ""),
'port': 443
}],
http_compress = True,
http_auth=(opensearch_account, opensearch_passwd),
use_ssl = True,
verify_certs = True,
ssl_assert_hostname = False,
ssl_show_warn = False,
)
def reflesh_opensearch_index():
#########################
# opensearch index (reflesh)
#########################
print(f"deleting opensearch index... {index_name}")
try: # create index
response = os_client.indices.delete(
index_name
)
print('opensearch index was deleted:', response)
except Exception:
err_msg = traceback.format_exc()
print('error message: ', err_msg)
#raise Exception ("Not able to create the index")
return
# websocket
connection_url = os.environ.get('connection_url')
client = boto3.client('apigatewaymanagementapi', endpoint_url=connection_url)
print('connection_url: ', connection_url)
HUMAN_PROMPT = "\n\nHuman:"
AI_PROMPT = "\n\nAssistant:"
map_chain = dict()
MSG_LENGTH = 100
# Multi-LLM
def get_chat():
global selected_chat
if multi_region == 'enable':
profile = multi_region_models[selected_chat]
length_of_models = len(multi_region_models)
else:
profile = LLM_for_chat[selected_chat]
length_of_models = 1
bedrock_region = profile['bedrock_region']
modelId = profile['model_id']
maxOutputTokens = 4096
print(f'LLM: {selected_chat}, bedrock_region: {bedrock_region}, modelId: {modelId}')
# bedrock
boto3_bedrock = boto3.client(
service_name='bedrock-runtime',
region_name=bedrock_region,
config=Config(
retries = {
'max_attempts': 30
}
)
)
parameters = {
"max_tokens":maxOutputTokens,
"temperature":0.1,
"top_k":250,
"top_p":0.9,
"stop_sequences": [HUMAN_PROMPT]
}
# print('parameters: ', parameters)
chat = ChatBedrock( # new chat model
model_id=modelId,
client=boto3_bedrock,
model_kwargs=parameters,
)
selected_chat = selected_chat + 1
if selected_chat == length_of_models:
selected_chat = 0
return chat
def get_multi_region_chat(models, selected):
profile = models[selected]
bedrock_region = profile['bedrock_region']
modelId = profile['model_id']
maxOutputTokens = 4096
print(f'selected_chat: {selected}, bedrock_region: {bedrock_region}, modelId: {modelId}')
# bedrock
boto3_bedrock = boto3.client(
service_name='bedrock-runtime',
region_name=bedrock_region,
config=Config(
retries = {
'max_attempts': 30
}
)
)
parameters = {
"max_tokens":maxOutputTokens,
"temperature":0.1,
"top_k":250,
"top_p":0.9,
"stop_sequences": [HUMAN_PROMPT]
}
# print('parameters: ', parameters)
chat = ChatBedrock( # new chat model
model_id=modelId,
client=boto3_bedrock,
model_kwargs=parameters,
)
return chat
def get_multimodal():
global selected_multimodal
print('LLM_for_chat: ', LLM_for_chat)
print('selected_multimodal: ', selected_multimodal)
profile = LLM_for_multimodal[selected_multimodal]
bedrock_region = profile['bedrock_region']
modelId = profile['model_id']
maxOutputTokens = 4096
print(f'LLM: {selected_multimodal}, bedrock_region: {bedrock_region}, modelId: {modelId}')
# bedrock
boto3_bedrock = boto3.client(
service_name='bedrock-runtime',
region_name=bedrock_region,
config=Config(
retries = {
'max_attempts': 30
}
)
)
parameters = {
"max_tokens":maxOutputTokens,
"temperature":0.1,
"top_k":250,
"top_p":0.9,
"stop_sequences": [HUMAN_PROMPT]
}
# print('parameters: ', parameters)
multimodal = ChatBedrock( # new chat model
model_id=modelId,
client=boto3_bedrock,
model_kwargs=parameters,
)
selected_multimodal = selected_multimodal + 1
if selected_multimodal == len(LLM_for_multimodal):
selected_multimodal = 0
return multimodal
def get_embedding():
global selected_embedding
profile = LLM_embedding[selected_embedding]
bedrock_region = profile['bedrock_region']
model_id = profile['model_id']
print(f'selected_embedding: {selected_embedding}, bedrock_region: {bedrock_region}, model_id: {model_id}')
# bedrock
boto3_bedrock = boto3.client(
service_name='bedrock-runtime',
region_name=bedrock_region,
config=Config(
retries = {
'max_attempts': 30
}
)
)
bedrock_embedding = BedrockEmbeddings(
client=boto3_bedrock,
region_name = bedrock_region,
model_id = model_id
)
selected_embedding = selected_embedding + 1
if selected_embedding == len(LLM_embedding):
selected_embedding = 0
return bedrock_embedding
# load documents from s3 for pdf and txt
def load_document(file_type, s3_file_name):
s3r = boto3.resource("s3")
doc = s3r.Object(s3_bucket, s3_prefix+'/'+s3_file_name)
if file_type == 'pdf':
contents = doc.get()['Body'].read()
reader = PyPDF2.PdfReader(BytesIO(contents))
raw_text = []
for page in reader.pages:
raw_text.append(page.extract_text())
contents = '\n'.join(raw_text)
elif file_type == 'txt':
contents = doc.get()['Body'].read().decode('utf-8')
print('contents: ', contents)
new_contents = str(contents).replace("\n"," ")
print('length: ', len(new_contents))
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=1000,
chunk_overlap=100,
separators=["\n\n", "\n", ".", " ", ""],
length_function = len,
)
texts = text_splitter.split_text(new_contents)
print('texts[0]: ', texts[0])
return texts
# load csv documents from s3
def load_csv_document(s3_file_name):
s3r = boto3.resource("s3")
doc = s3r.Object(s3_bucket, s3_prefix+'/'+s3_file_name)
lines = doc.get()['Body'].read().decode('utf-8').split('\n') # read csv per line
print('lins: ', len(lines))
columns = lines[0].split(',') # get columns
#columns = ["Category", "Information"]
#columns_to_metadata = ["type","Source"]
print('columns: ', columns)
docs = []
n = 0
for row in csv.DictReader(lines, delimiter=',',quotechar='"'):
# print('row: ', row)
#to_metadata = {col: row[col] for col in columns_to_metadata if col in row}
values = {k: row[k] for k in columns if k in row}
content = "\n".join(f"{k.strip()}: {v.strip()}" for k, v in values.items())
doc = Document(
page_content=content,
metadata={
'name': s3_file_name,
'row': n+1,
}
#metadata=to_metadata
)
docs.append(doc)
n = n+1
print('docs[0]: ', docs[0])
return docs
def get_summary(chat, docs):
text = ""
for doc in docs:
text = text + doc
if isKorean(text)==True:
system = (
"다음의 <article> tag안의 문장을 요약해서 500자 이내로 설명하세오."
)
else:
system = (
"Here is pieces of article, contained in <article> tags. Write a concise summary within 500 characters."
)
human = "<article>{text}</article>"
prompt = ChatPromptTemplate.from_messages([("system", system), ("human", human)])
# print('prompt: ', prompt)
chain = prompt | chat
try:
result = chain.invoke(
{
"text": text
}
)
summary = result.content
print('result of summarization: ', summary)
except Exception:
err_msg = traceback.format_exc()
print('error message: ', err_msg)
raise Exception ("Not able to request to LLM")
return summary
def load_chatHistory(userId, allowTime, chat_memory):
dynamodb_client = boto3.client('dynamodb')
response = dynamodb_client.query(
TableName=callLogTableName,
KeyConditionExpression='user_id = :userId AND request_time > :allowTime',
ExpressionAttributeValues={
':userId': {'S': userId},
':allowTime': {'S': allowTime}
}
)
# print('query result: ', response['Items'])
for item in response['Items']:
text = item['body']['S']
msg = item['msg']['S']
type = item['type']['S']
if type == 'text' and text and msg:
memory_chain.chat_memory.add_user_message(text)
if len(msg) > MSG_LENGTH:
memory_chain.chat_memory.add_ai_message(msg[:MSG_LENGTH])
else:
memory_chain.chat_memory.add_ai_message(msg)
def getAllowTime():
d = datetime.datetime.now() - datetime.timedelta(days = 2)
timeStr = str(d)[0:19]
print('allow time: ',timeStr)
return timeStr
def isKorean(text):
# check korean
pattern_hangul = re.compile('[\u3131-\u3163\uac00-\ud7a3]+')
word_kor = pattern_hangul.search(str(text))
# print('word_kor: ', word_kor)
if word_kor and word_kor != 'None':
print('Korean: ', word_kor)
return True
else:
print('Not Korean: ', word_kor)
return False
def general_conversation(connectionId, requestId, chat, query):
if isKorean(query)==True:
system = (
"당신의 이름은 서연이고, 질문에 대해 친절하게 답변하는 사려깊은 인공지능 도우미입니다."
"상황에 맞는 구체적인 세부 정보를 충분히 제공합니다."
"모르는 질문을 받으면 솔직히 모른다고 말합니다."
)
else:
system = (
"You will be acting as a thoughtful advisor."
"Using the following conversation, answer friendly for the newest question."
"If you don't know the answer, just say that you don't know, don't try to make up an answer."
)
human = "{input}"
prompt = ChatPromptTemplate.from_messages([
("system", system),
MessagesPlaceholder(variable_name="history"),
("human", human)])
# print('prompt: ', prompt)
history = memory_chain.load_memory_variables({})["chat_history"]
# print('memory_chain: ', history)
chain = prompt | chat
try:
isTyping(connectionId, requestId, "")
stream = chain.invoke(
{
"history": history,
"input": query,
}
)
msg = readStreamMsg(connectionId, requestId, stream.content)
usage = stream.response_metadata['usage']
print('prompt_tokens: ', usage['prompt_tokens'])
print('completion_tokens: ', usage['completion_tokens'])
print('total_tokens: ', usage['total_tokens'])
msg = stream.content
except Exception:
err_msg = traceback.format_exc()
print('error message: ', err_msg)
sendErrorMessage(connectionId, requestId, err_msg)
raise Exception ("Not able to request to LLM")
return msg
def get_answer_using_opensearch(connectionId, requestId, chat, text):
# retrieve
isTyping(connectionId, requestId, "retrieving...")
relevant_docs = retrieve_documents_from_opensearch(text, top_k=4)
# grade
isTyping(connectionId, requestId, "grading...")
filtered_docs = grade_documents(text, relevant_docs) # grading
filtered_docs = check_duplication(filtered_docs) # check duplication
# generate
isTyping(connectionId, requestId, "generating...")
msg = generate_answer_with_stream(connectionId, requestId, chat, filtered_docs, text)
return msg
def retrieve_documents_from_opensearch(query, top_k=4):
print("###### retrieve_documents_from_opensearch ######")
bedrock_embedding = get_embedding()
vectorstore_opensearch = OpenSearchVectorSearch(
index_name = index_name,
is_aoss = False,
ef_search = 1024, # 512(default)
m=48,
#engine="faiss", # default: nmslib
embedding_function = bedrock_embedding,
opensearch_url=opensearch_url,
http_auth=(opensearch_account, opensearch_passwd), # http_auth=awsauth,
)
relevant_docs = []
if enableParentDocumentRetrival == 'enable':
result = vectorstore_opensearch.similarity_search_with_score(
query = query,
k = top_k*2,
search_type="script_scoring",
pre_filter={"term": {"metadata.doc_level": "child"}}
)
print('result: ', result)
relevant_documents = []
docList = []
for re in result:
if 'parent_doc_id' in re[0].metadata:
parent_doc_id = re[0].metadata['parent_doc_id']
doc_level = re[0].metadata['doc_level']
print(f"doc_level: {doc_level}, parent_doc_id: {parent_doc_id}")
if doc_level == 'child':
if parent_doc_id in docList:
print('duplicated!')
else:
relevant_documents.append(re)
docList.append(parent_doc_id)
if len(relevant_documents)>=top_k:
break
# print('relevant_documents: ', relevant_documents)
for i, doc in enumerate(relevant_documents):
if len(doc[0].page_content)>=100:
text = doc[0].page_content[:100]
else:
text = doc[0].page_content
print(f"--> vector search doc[{i}]: {text}, metadata:{doc[0].metadata}")
for i, document in enumerate(relevant_documents):
print(f'## Document(opensearch-vector) {i+1}: {document}')
parent_doc_id = document[0].metadata['parent_doc_id']
doc_level = document[0].metadata['doc_level']
#print(f"child: parent_doc_id: {parent_doc_id}, doc_level: {doc_level}")
content, name, url = get_parent_content(parent_doc_id) # use pareant document
#print(f"parent_doc_id: {parent_doc_id}, doc_level: {doc_level}, url: {url}, content: {content}")
relevant_docs.append(
Document(
page_content=content,
metadata={
'name': name,
'url': url,
'doc_level': doc_level,
'from': 'vector'
},
)
)
else:
print("###### similarity_search_with_score ######")
relevant_documents = vectorstore_opensearch.similarity_search_with_score(
query = query,
k = top_k
)
for i, document in enumerate(relevant_documents):
print(f'## Document(opensearch-vector) {i+1}: {document}')
name = document[0].metadata['name']
url = document[0].metadata['url']
content = document[0].page_content
relevant_docs.append(
Document(
page_content=content,
metadata={
'name': name,
'url': url,
'from': 'vector'
},
)
)
# print('the number of docs (vector search): ', len(relevant_docs))
if enableHybridSearch == 'true':
relevant_docs += lexical_search(query, top_k)
return relevant_docs
def retrieve_documents_from_tavily(query, top_k):
print("###### retrieve_documents_from_tavily ######")
relevant_documents = []
search = TavilySearchResults(
max_results=top_k,
include_answer=True,
include_raw_content=True,
search_depth="advanced",
include_domains=["google.com", "naver.com"]
)
try:
output = search.invoke(query)
# print('tavily output: ', output)
for result in output:
print('result of tavily: ', result)
if result:
content = result.get("content")
url = result.get("url")
relevant_documents.append(
Document(
page_content=content,
metadata={
'name': 'WWW',
'url': url,
'from': 'tavily'
},
)
)
except Exception:
err_msg = traceback.format_exc()
print('error message: ', err_msg)
# raise Exception ("Not able to request to tavily")
return relevant_documents
def get_parent_content(parent_doc_id):
response = os_client.get(
index = index_name,
id = parent_doc_id
)
source = response['_source']
# print('parent_doc: ', source['text'])
metadata = source['metadata']
#print('name: ', metadata['name'])
#print('url: ', metadata['url'])
#print('doc_level: ', metadata['doc_level'])
url = ""
if "url" in metadata:
url = metadata['url']
return source['text'], metadata['name'], url
@tool
def get_book_list(keyword: str) -> str:
"""
Search book list by keyword and then return book list
keyword: search keyword
return: book list
"""
keyword = keyword.replace('\'','')
answer = ""
url = f"https://search.kyobobook.co.kr/search?keyword={keyword}&gbCode=TOT&target=total"
response = requests.get(url)
if response.status_code == 200:
soup = BeautifulSoup(response.text, "html.parser")
prod_info = soup.find_all("a", attrs={"class": "prod_info"})
if len(prod_info):
answer = "추천 도서는 아래와 같습니다.\n"
for prod in prod_info[:5]:
title = prod.text.strip().replace("\n", "")
link = prod.get("href")
answer = answer + f"{title}, URL: {link}\n\n"
return answer
@tool
def get_current_time(format: str=f"%Y-%m-%d %H:%M:%S")->str:
"""Returns the current date and time in the specified format"""
# f"%Y-%m-%d %H:%M:%S"
format = format.replace('\'','')
timestr = datetime.datetime.now(timezone('Asia/Seoul')).strftime(format)
# print('timestr:', timestr)
return timestr
@tool
def get_weather_info(city: str) -> str:
"""
retrieve weather information by city name and then return weather statement.
city: the name of city to retrieve
return: weather statement
"""
city = city.replace('\n','')
city = city.replace('\'','')
city = city.replace('\"','')
chat = get_chat()
if isKorean(city):
place = traslation(chat, city, "Korean", "English")
print('city (translated): ', place)
else:
place = city
city = traslation(chat, city, "English", "Korean")
print('city (translated): ', city)
print('place: ', place)
weather_str: str = f"{city}에 대한 날씨 정보가 없습니다."
if weather_api_key:
apiKey = weather_api_key
lang = 'en'
units = 'metric'
api = f"https://api.openweathermap.org/data/2.5/weather?q={place}&APPID={apiKey}&lang={lang}&units={units}"
# print('api: ', api)
try:
result = requests.get(api)
result = json.loads(result.text)
print('result: ', result)
if 'weather' in result:
overall = result['weather'][0]['main']
current_temp = result['main']['temp']
min_temp = result['main']['temp_min']
max_temp = result['main']['temp_max']
humidity = result['main']['humidity']
wind_speed = result['wind']['speed']
cloud = result['clouds']['all']
weather_str = f"{city}의 현재 날씨의 특징은 {overall}이며, 현재 온도는 {current_temp}도 이고, 최저온도는 {min_temp}도, 최고 온도는 {max_temp}도 입니다. 현재 습도는 {humidity}% 이고, 바람은 초당 {wind_speed} 미터 입니다. 구름은 {cloud}% 입니다."
#weather_str = f"Today, the overall of {city} is {overall}, current temperature is {current_temp} degree, min temperature is {min_temp} degree, highest temperature is {max_temp} degree. huminity is {humidity}%, wind status is {wind_speed} meter per second. the amount of cloud is {cloud}%."
except Exception:
err_msg = traceback.format_exc()
print('error message: ', err_msg)
# raise Exception ("Not able to request to LLM")
print('weather_str: ', weather_str)
return weather_str
@tool
def search_by_tavily(keyword: str) -> str:
"""
Search general information by keyword and then return the result as a string.
keyword: search keyword
return: the information of keyword
"""
global reference_docs
answer = ""
if tavily_api_key:
keyword = keyword.replace('\'','')
search = TavilySearchResults(
max_results=3,
include_answer=True,
include_raw_content=True,
search_depth="advanced", # "basic"
include_domains=["google.com", "naver.com"]
)
try:
output = search.invoke(keyword)
print('tavily output: ', output)
for result in output:
print('result: ', result)
if result:
content = result.get("content")
url = result.get("url")
reference_docs.append(
Document(
page_content=content,
metadata={
'name': 'WWW',
'url': url,
'from': 'tavily'
},
)
)
answer = answer + f"{content}, URL: {url}\n"
except Exception:
err_msg = traceback.format_exc()
print('error message: ', err_msg)
# raise Exception ("Not able to request to tavily")
return answer
@tool
def search_by_opensearch(keyword: str) -> str:
"""
Search technical information by keyword and then return the result as a string.
keyword: search keyword
return: the technical information of keyword
"""
print('keyword: ', keyword)
keyword = keyword.replace('\'','')
keyword = keyword.replace('|','')
keyword = keyword.replace('\n','')
print('modified keyword: ', keyword)
# retrieve
relevant_docs = retrieve_documents_from_opensearch(keyword, top_k=2)
print('relevant_docs length: ', len(relevant_docs))
# grade
filtered_docs = grade_documents(keyword, relevant_docs)
for i, doc in enumerate(filtered_docs):
if len(doc.page_content)>=100: