-
Notifications
You must be signed in to change notification settings - Fork 1
/
lambda_function.py
2071 lines (1656 loc) · 69.8 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
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 langchain_community.embeddings import BedrockEmbeddings
from langchain.agents import tool
from langchain.agents import AgentExecutor, create_react_agent
from bs4 import BeautifulSoup
from langchain.prompts import PromptTemplate
from langchain.agents import AgentExecutor, create_tool_calling_agent
from pytz import timezone
from langchain_community.tools.tavily_search import TavilySearchResults
from PIL import Image
from opensearchpy import OpenSearch
from typing import TypedDict, Annotated, Sequence, List, Union
from langchain_core.agents import AgentAction, AgentFinish
from langchain_core.messages import BaseMessage, HumanMessage, AIMessage, SystemMessage
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
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
selected_multimodal = 0
selected_embedding = 0
maxOutputTokens = 4096
separated_chat_history = os.environ.get('separated_chat_history')
enalbeParentDocumentRetrival = os.environ.get('enalbeParentDocumentRetrival')
enableHybridSearch = os.environ.get('enableHybridSearch')
# 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)
tavily_api_key = secret['tavily_api_key']
except Exception as e:
raise e
if tavily_api_key:
os.environ["TAVILY_API_KEY"] = tavily_api_key
# 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
profile = LLM_for_chat[selected_chat]
bedrock_region = profile['bedrock_region']
modelId = profile['model_id']
print(f'selected_chat: {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 == len(LLM_for_chat):
selected_chat = 0
return chat
def get_multimodal():
profile = LLM_for_multimodal[selected_multimodal]
bedrock_region = profile['bedrock_region']
modelId = profile['model_id']
print(f'selected_multimodal: {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':
print('text: ', text)
print('msg: ', msg)
chat_memory.save_context({"input": text}, {"output": 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 = (
"다음의 Human과 Assistant의 친근한 이전 대화입니다. Assistant은 상황에 맞는 구체적인 세부 정보를 충분히 제공합니다. Assistant의 이름은 서연이고, 모르는 질문을 받으면 솔직히 모른다고 말합니다."
)
else:
system = (
"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. You will be acting as a thoughtful advisor."
)
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_documents_from_opensearch(vectorstore_opensearch, query, top_k):
result = vectorstore_opensearch.similarity_search_with_score(
query = query,
k = top_k*2,
pre_filter={"doc_level": {"$eq": "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('lexical query result: ', json.dumps(response))
print('relevant_documents: ', relevant_documents)
return relevant_documents
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 get_parent_document(parent_doc_id):
response = os_client.get(
index="idx-rag",
id = parent_doc_id
)
source = response['_source']
# print('parent_doc: ', source['text'])
metadata = source['metadata']
#print('name: ', metadata['name'])
#print('uri: ', metadata['uri'])
#print('doc_level: ', metadata['doc_level'])
return source['text'], metadata['name'], metadata['uri'], metadata['doc_level']
@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]:
# \n문자를 replace합니다.
title = prod.text.strip().replace("\n", "")
link = prod.get("href")
answer = answer + f"{title}, URL: {link}\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
def get_lambda_client(region):
return boto3.client(
service_name='lambda',
region_name=region
)
@tool
def get_system_time() -> str:
"""
retrive system time to earn the current date and time.
return: a string of date and time
"""
function_name = "lambda-datetime-for-llm-agent"
lambda_region = 'ap-northeast-2'
try:
lambda_client = get_lambda_client(region=lambda_region)
payload = {}
print("Payload: ", payload)
response = lambda_client.invoke(
FunctionName=function_name,
Payload=json.dumps(payload),
)
print("Invoked function %s.", function_name)
print("Response: ", response)
except ClientError:
print("Couldn't invoke function %s.", function_name)
raise
payload = response['Payload']
print('payload: ', payload)
body = json.load(payload)['body']
print('body: ', body)
jsonBody = json.loads(body)
print('jsonBody: ', jsonBody)
timestr = jsonBody['timestr']
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
"""
answer = ""
if tavily_api_key:
keyword = keyword.replace('\'','')
search = TavilySearchResults(k=3)
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")
answer = answer + f"{content}, URL: {url}\n"
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)
bedrock_embedding = get_embedding()
vectorstore_opensearch = OpenSearchVectorSearch(
index_name = "idx-*", # all
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,
)
answer = ""
top_k = 2
if enalbeParentDocumentRetrival == 'true':
relevant_documents = get_documents_from_opensearch(vectorstore_opensearch, keyword, top_k)
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}")
excerpt, name, uri, doc_level = get_parent_document(parent_doc_id) # use pareant document
print(f"parent: name: {name}, uri: {uri}, doc_level: {doc_level}")
answer = answer + f"{excerpt}, URL: {uri}\n\n"
else:
relevant_documents = vectorstore_opensearch.similarity_search_with_score(
query = keyword,
k = top_k,
)
for i, document in enumerate(relevant_documents):
print(f'## Document(opensearch-vector) {i+1}: {document}')
excerpt = document[0].page_content
uri = document[0].metadata['uri']
answer = answer + f"{excerpt}, URL: {uri}\n\n"
if enableHybridSearch == 'true':
answer = answer + lexical_search_for_tool(keyword, top_k)
return answer
def lexical_search_for_tool(query, top_k):
# lexical search (keyword)
min_match = 0
query = {
"query": {
"bool": {
"must": [
{
"match": {
"text": {
"query": query,
"minimum_should_match": f'{min_match}%',
"operator": "or",
}
}
},
],
"filter": [
]
}
}
}
response = os_client.search(
body=query,
index="idx-*", # all
)
# print('lexical query result: ', json.dumps(response))
answer = ""
for i, document in enumerate(response['hits']['hits']):
if i>=top_k:
break
excerpt = document['_source']['text']
uri = ""
if "uri" in document['_source']['metadata']:
uri = document['_source']['metadata']['uri']
print(f"lexical search --> doc[{i}]: {excerpt}, uri:{uri}\n")
answer = answer + f"{excerpt}, URL: {uri}\n\n"
return answer
# define tools
tools = [get_current_time, get_book_list, get_weather_info, search_by_tavily, search_by_opensearch]
def get_react_prompt_template(mode: str): # (hwchase17/react) https://smith.langchain.com/hub/hwchase17/react
# Get the react prompt template
if mode=='eng':
return PromptTemplate.from_template("""Answer the following questions as best you can. You have access to the following tools:
{tools}
Use the following format:
Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should use only the tool name from [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat 5 times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question
When you have a response to say to the Human, or if you do not need to use a tool, you MUST use the format:
'''
Thought: Do I need to use a tool? No
Final Answer: [your response here]
'''
Begin!
Question: {input}
Thought:{agent_scratchpad}
""")
else:
return PromptTemplate.from_template("""다음은 Human과 Assistant의 친근한 대화입니다. Assistant은 상황에 맞는 구체적인 세부 정보를 충분히 제공합니다. Assistant의 이름은 서연이고, 모르는 질문을 받으면 솔직히 모른다고 말합니다.
사용할 수 있는 tools은 아래와 같습니다:
{tools}
다음의 format을 사용하세요.:
Question: 답변하여야 할 input question
Thought: you should always think about what to do.
Action: 해야 할 action로서 [{tool_names}]에서 tool의 name만을 가져옵니다.
Action Input: action의 input
Observation: action의 result
... (Thought/Action/Action Input/Observation을 5번 반복 할 수 있습니다.)
Thought: 나는 이제 Final Answer를 알고 있습니다.
Final Answer: original input에 대한 Final Answer
너는 Human에게 해줄 응답이 있거나, Tool을 사용하지 않아도 되는 경우에, 다음 format을 사용하세요.:
'''
Thought: Tool을 사용해야 하나요? No
Final Answer: [your response here]
'''
Begin!
Question: {input}
Thought:{agent_scratchpad}
""")
def run_agent_react(connectionId, requestId, chat, query):
prompt_template = get_react_prompt_template(agentLangMode)
print('prompt_template: ', prompt_template)
#from langchain import hub
#prompt_template = hub.pull("hwchase17/react")
#print('prompt_template: ', prompt_template)
# create agent
isTyping(connectionId, requestId)
agent = create_react_agent(chat, tools, prompt_template)
agent_executor = AgentExecutor(
agent=agent,
tools=tools,
verbose=True,
handle_parsing_errors=True,
max_iterations = 5
)
# run agent
response = agent_executor.invoke({"input": query})
print('response: ', response)
# streaming
msg = readStreamMsg(connectionId, requestId, response['output'])
msg = response['output']
print('msg: ', msg)
return msg
def get_react_chat_prompt_template(mode: str):
# Get the react prompt template
if mode=='eng':
return PromptTemplate.from_template("""Answer the following questions as best you can. You have access to the following tools:
{tools}
Use the following format:
Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should use only the tool name from [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat 5 times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question
When you have a response to say to the Human, or if you do not need to use a tool, you MUST use the format:
'''
Thought: Do I need to use a tool? No
Final Answer: [your response here]
'''
Begin!
Previous conversation history:
{chat_history}
New input: {input}
Thought:{agent_scratchpad}
""")
else:
return PromptTemplate.from_template("""다음은 Human과 Assistant의 친근한 대화입니다. Assistant은 상황에 맞는 구체적인 세부 정보를 충분히 제공합니다. Assistant의 이름은 서연이고, 모르는 질문을 받으면 솔직히 모른다고 말합니다.
사용할 수 있는 tools은 아래와 같습니다:
{tools}
다음의 format을 사용하세요.:
Question: 답변하여야 할 input question
Thought: you should always think about what to do.
Action: 해야 할 action로서 [{tool_names}]에서 tool의 name만을 가져옵니다.
Action Input: action의 input
Observation: action의 result
... (Thought/Action/Action Input/Observation을 5번 반복 할 수 있습니다.)
Thought: 나는 이제 Final Answer를 알고 있습니다.
Final Answer: original input에 대한 Final Answer
너는 Human에게 해줄 응답이 있거나, Tool을 사용하지 않아도 되는 경우에, 다음 format을 사용하세요.:
'''
Thought: Tool을 사용해야 하나요? No
Final Answer: [your response here]
'''
Begin!
Previous conversation history:
{chat_history}
New input: {input}
Thought:{agent_scratchpad}
""")
def run_agent_react_chat(connectionId, requestId, chat, query):
# get template based on react
prompt_template = get_react_chat_prompt_template(agentLangMode)
print('prompt_template: ', prompt_template)
# create agent
isTyping(connectionId, requestId)
agent = create_react_agent(chat, tools, prompt_template)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True, handle_parsing_errors=True)
history = memory_chain.load_memory_variables({})["chat_history"]
print('memory_chain: ', history)
# run agent
response = agent_executor.invoke({
"input": query,
"chat_history": history
})
print('response: ', response)
# streaming
msg = readStreamMsg(connectionId, requestId, response['output'])
msg = response['output']
print('msg: ', msg)
return msg
def run_agent_react_chat_using_revised_question(connectionId, requestId, chat, query):
# revise question
revised_question = revise_question(connectionId, requestId, chat, query)
print('revised_question: ', revised_question)
# get template based on react
prompt_template = get_react_prompt_template(agentLangMode)
print('prompt_template: ', prompt_template)
# create agent
isTyping(connectionId, requestId)
agent = create_react_agent(chat, tools, prompt_template)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True, handle_parsing_errors=True)
# run agent
response = agent_executor.invoke({"input": revised_question})
print('response: ', response)
# streaming
msg = readStreamMsg(connectionId, requestId, response['output'])
msg = response['output']
print('msg: ', msg)
return msg
####################### LangGraph #######################
# Chat Agent Executor
#########################################################
chatModel = get_chat()
model = chatModel.bind_tools(tools)
class ChatAgentState(TypedDict):
# messages: Annotated[Sequence[BaseMessage], operator.add]
messages: Annotated[list, add_messages]
tool_node = ToolNode(tools)
from typing import Literal
def should_continue(state: ChatAgentState) -> Literal["continue", "end"]:
messages = state["messages"]
last_message = messages[-1]
if not last_message.tool_calls:
return "end"
else:
return "continue"
#def call_model(state: ChatAgentState):
# response = model.invoke(state["messages"])
# return {"messages": [response]}