-
Notifications
You must be signed in to change notification settings - Fork 0
/
lambda_function.py
4938 lines (4005 loc) · 187 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
from io import BytesIO
import PyPDF2
import csv
import traceback
import re
import base64
import datetime
import requests
import docx
import uuid
from urllib import parse
from botocore.config import Config
from PIL import Image
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.memory import ConversationBufferWindowMemory
from langchain_community.docstore.document import Document
from langchain_community.vectorstores.faiss import FAISS
from langchain_community.vectorstores.opensearch_vector_search import OpenSearchVectorSearch
from langchain_aws import BedrockEmbeddings
from langchain_community.retrievers import AmazonKendraRetriever
from multiprocessing import Process, Pipe
from googleapiclient.discovery import build
from opensearchpy import OpenSearch
from langchain_core.prompts import PromptTemplate
from langchain_core.prompts import MessagesPlaceholder, ChatPromptTemplate
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_aws import ChatBedrock
from langchain.agents import tool
from langchain.agents import AgentExecutor, create_react_agent
from bs4 import BeautifulSoup
from pytz import timezone
from langchain_community.tools.tavily_search import TavilySearchResults
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
from pydantic.v1 import BaseModel, Field
from typing import Literal
from langchain_aws import AmazonKnowledgeBasesRetriever
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')
kendra_region = os.environ.get('kendra_region', 'us-west-2')
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'))
priority_search_embedding = json.loads(os.environ.get('priority_search_embedding'))
selected_chat = 0
selected_multimodal = 0
selected_embedding = 0
selected_ps_embedding = 0
rag_method = os.environ.get('rag_method', 'RetrievalPrompt') # RetrievalPrompt, RetrievalQA, ConversationalRetrievalChain
separated_chat_history = os.environ.get('separated_chat_history')
enableParentDocumentRetrival = os.environ.get('enableParentDocumentRetrival')
opensearch_account = os.environ.get('opensearch_account')
opensearch_passwd = os.environ.get('opensearch_passwd')
enableReference = os.environ.get('enableReference', 'false')
debugMessageMode = os.environ.get('debugMessageMode', 'false')
opensearch_url = os.environ.get('opensearch_url')
path = os.environ.get('path')
doc_prefix = s3_prefix+'/'
speech_prefix = 'speech/'
useParallelRAG = os.environ.get('useParallelRAG', 'true')
kendraIndex = os.environ.get('kendraIndex')
kendra_method = os.environ.get('kendraMethod')
roleArn = os.environ.get('roleArn')
top_k = int(os.environ.get('numberOfRelevantDocs'))
capabilities = json.loads(os.environ.get('capabilities'))
print('capabilities: ', capabilities)
MSG_LENGTH = 100
MSG_HISTORY_LENGTH = 20
speech_generation = os.environ.get('speech_generation')
history_length = 0
token_counter_history = 0
allowDualSearch = os.environ.get('allowDualSearch')
allowDualSearchWithMulipleProcessing = True
enableHybridSearch = os.environ.get('enableHybridSearch')
useParrelWebSearch = True
useEnhancedSearch = True
minDocSimilarity = 200
minCodeSimilarity = 300
projectName = os.environ.get('projectName')
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')
reference_docs = []
# google search api
googleApiSecret = os.environ.get('googleApiSecret')
secretsmanager = boto3.client('secretsmanager')
try:
get_secret_value_response = secretsmanager.get_secret_value(
SecretId=googleApiSecret
)
#print('get_secret_value_response: ', get_secret_value_response)
secret = json.loads(get_secret_value_response['SecretString'])
#print('secret: ', secret)
google_api_key = secret['google_api_key']
google_cse_id = secret['google_cse_id']
#print('google_cse_id: ', google_cse_id)
except Exception as e:
raise e
# api key to get weather information in agent
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']
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 == len(LLM_for_chat):
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
def get_ps_embedding():
global selected_ps_embedding
profile = priority_search_embedding[selected_ps_embedding]
bedrock_region = profile['bedrock_region']
model_id = profile['model_id']
print(f'selected_ps_embedding: {selected_ps_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_ps_embedding = BedrockEmbeddings(
client=boto3_bedrock,
region_name = bedrock_region,
model_id = model_id
)
selected_ps_embedding = selected_ps_embedding + 1
if selected_ps_embedding == len(priority_search_embedding):
selected_ps_embedding = 0
return bedrock_ps_embedding
def sendMessage(id, body):
try:
client.post_to_connection(
ConnectionId=id,
Data=json.dumps(body)
)
except Exception:
err_msg = traceback.format_exc()
print('err_msg: ', err_msg)
raise Exception ("Not able to send a message")
def sendResultMessage(connectionId, requestId, msg):
result = {
'request_id': requestId,
'msg': msg,
'status': 'completed'
}
#print('debug: ', json.dumps(debugMsg))
sendMessage(connectionId, result)
def sendDebugMessage(connectionId, requestId, msg):
debugMsg = {
'request_id': requestId,
'msg': msg,
'status': 'debug'
}
#print('debug: ', json.dumps(debugMsg))
sendMessage(connectionId, debugMsg)
def sendErrorMessage(connectionId, requestId, msg):
errorMsg = {
'request_id': requestId,
'msg': msg,
'status': 'error'
}
print('error: ', json.dumps(errorMsg))
sendMessage(connectionId, errorMsg)
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 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):
global time_for_inference, history_length, token_counter_history
time_for_inference = history_length = token_counter_history = 0
if debugMessageMode == 'true':
start_time_for_inference = time.time()
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
# print('msg: ', msg)
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")
if debugMessageMode == 'true':
chat_history = ""
for dialogue_turn in history:
#print('type: ', dialogue_turn.type)
#print('content: ', dialogue_turn.content)
dialog = f"{dialogue_turn.type}: {dialogue_turn.content}\n"
chat_history = chat_history + dialog
history_length = len(chat_history)
print('chat_history length: ', history_length)
token_counter_history = 0
if chat_history:
token_counter_history = chat.get_num_tokens(chat_history)
print('token_size of history: ', token_counter_history)
end_time_for_inference = time.time()
time_for_inference = end_time_for_inference - start_time_for_inference
return msg
def traslation(chat, text, input_language, output_language):
system = (
"You are a helpful assistant that translates {input_language} to {output_language} in <article> tags. Put it in <result> tags."
)
human = "<article>{text}</article>"
prompt = ChatPromptTemplate.from_messages([("system", system), ("human", human)])
# print('prompt: ', prompt)
chain = prompt | chat
try:
result = chain.invoke(
{
"input_language": input_language,
"output_language": output_language,
"text": text,
}
)
msg = result.content
# print('translated text: ', msg)
except Exception:
err_msg = traceback.format_exc()
print('error message: ', err_msg)
raise Exception ("Not able to request to LLM")
return msg[msg.find('<result>')+8:len(msg)-9] # remove <result> tag
def translate_text(chat, text):
global time_for_inference
if debugMessageMode == 'true':
start_time_for_inference = time.time()
system = (
"You are a helpful assistant that translates {input_language} to {output_language} in <article> tags. Put it in <result> tags."
)
human = "<article>{text}</article>"
prompt = ChatPromptTemplate.from_messages([("system", system), ("human", human)])
# print('prompt: ', prompt)
if isKorean(text)==False :
input_language = "English"
output_language = "Korean"
else:
input_language = "Korean"
output_language = "English"
chain = prompt | chat
try:
result = chain.invoke(
{
"input_language": input_language,
"output_language": output_language,
"text": text,
}
)
msg = result.content
print('translated text: ', msg)
except Exception:
err_msg = traceback.format_exc()
print('error message: ', err_msg)
raise Exception ("Not able to request to LLM")
if debugMessageMode == 'true':
end_time_for_inference = time.time()
time_for_inference = end_time_for_inference - start_time_for_inference
return msg[msg.find('<result>')+8:len(msg)-9] # remove <result> tag
def check_grammer(chat, text):
global time_for_inference
if debugMessageMode == 'true':
start_time_for_inference = time.time()
if isKorean(text)==True:
system = (
"다음의 <article> tag안의 문장의 오류를 찾아서 설명하고, 오류가 수정된 문장을 답변 마지막에 추가하여 주세요."
)
else:
system = (
"Here is pieces of article, contained in <article> tags. Find the error in the sentence and explain it, and add the corrected sentence at the end of your answer."
)
human = "<article>{text}</article>"
prompt = ChatPromptTemplate.from_messages([("system", system), ("human", human)])
# print('prompt: ', prompt)
chain = prompt | chat
try:
result = chain.invoke(
{
"text": text
}
)
msg = result.content
print('result of grammer correction: ', msg)
except Exception:
err_msg = traceback.format_exc()
print('error message: ', err_msg)
raise Exception ("Not able to request to LLM")
if debugMessageMode == 'true':
end_time_for_inference = time.time()
time_for_inference = end_time_for_inference - start_time_for_inference
return msg
def extract_sentiment(chat, text):
if isKorean(text)==True:
system = (
"""아래의 <example> review와 Extracted Topic and sentiment 인 <result>가 있습니다.
<example>
객실은 작지만 깨끗하고 편안합니다. 프론트 데스크는 정말 분주했고 체크인 줄도 길었지만, 직원들은 프로페셔널하고 매우 유쾌하게 각 사람을 응대했습니다. 우리는 다시 거기에 머물것입니다.
</example>
<result>
청소: 긍정적,
서비스: 긍정적
</result>
아래의 <review>에 대해서 위의 <result> 예시처럼 Extracted Topic and sentiment 을 만들어 주세요."""
)
else:
system = (
"""Here is <example> review and extracted topics and sentiments as <result>.
<example>
The room was small but clean and comfortable. The front desk was really busy and the check-in line was long, but the staff were professional and very pleasant with each person they helped. We will stay there again.
</example>
<result>
Cleanliness: Positive,
Service: Positive
</result>"""
)
human = "<review>{text}</review>"
prompt = ChatPromptTemplate.from_messages([("system", system), ("human", human)])
# print('prompt: ', prompt)
chain = prompt | chat
try:
result = chain.invoke(
{
"text": text
}
)
msg = result.content
print('result of sentiment extraction: ', msg)
except Exception:
err_msg = traceback.format_exc()
print('error message: ', err_msg)
raise Exception ("Not able to request to LLM")
return msg
def extract_information(chat, text):
if isKorean(text)==True:
system = (
"""다음 텍스트에서 이메일 주소를 정확하게 복사하여 한 줄에 하나씩 적어주세요. 입력 텍스트에 정확하게 쓰여있는 이메일 주소만 적어주세요. 텍스트에 이메일 주소가 없다면, "N/A"라고 적어주세요. 또한 결과는 <result> tag를 붙여주세요."""
)
else:
system = (
"""Please precisely copy any email addresses from the following text and then write them, one per line. Only write an email address if it's precisely spelled out in the input text. If there are no email addresses in the text, write "N/A". Do not say anything else. Put it in <result> tags."""
)
human = "<text>{text}</text>"
prompt = ChatPromptTemplate.from_messages([("system", system), ("human", human)])
# print('prompt: ', prompt)
chain = prompt | chat
try:
result = chain.invoke(
{
"text": text
}
)
output = result.content
msg = output[output.find('<result>')+8:len(output)-9] # remove <result>
print('result of information extraction: ', msg)
except Exception:
err_msg = traceback.format_exc()
print('error message: ', err_msg)
raise Exception ("Not able to request to LLM")
return msg
def remove_pii(chat, text):
if isKorean(text)==True:
system = (
"""아래의 <text>에서 개인식별정보(PII)를 모두 제거하여 외부 계약자와 안전하게 공유할 수 있도록 합니다. 이름, 전화번호, 주소, 이메일을 XXX로 대체합니다. 또한 결과는 <result> tag를 붙여주세요."""
)
else:
system = (
"""We want to de-identify some text by removing all personally identifiable information from this text so that it can be shared safely with external contractors.
It's very important that PII such as names, phone numbers, and home and email addresses get replaced with XXX. Put it in <result> tags."""
)
human = "<text>{text}</text>"
prompt = ChatPromptTemplate.from_messages([("system", system), ("human", human)])
# print('prompt: ', prompt)
chain = prompt | chat
try:
result = chain.invoke(
{
"text": text
}
)
output = result.content
msg = output[output.find('<result>')+8:len(output)-9] # remove <result>
print('result of removing PII : ', msg)
except Exception:
err_msg = traceback.format_exc()
print('error message: ', err_msg)
raise Exception ("Not able to request to LLM")
return msg
def do_step_by_step(chat, text):
if isKorean(text)==True:
system = (
"""다음은 Human과 Assistant의 친근한 대화입니다. Assistant은 상황에 맞는 구체적인 세부 정보를 충분히 제공합니다. 아래 문맥(context)을 참조했음에도 답을 알 수 없다면, 솔직히 모른다고 말합니다. 여기서 Assistant의 이름은 서연입니다.
Assistant: 단계별로 생각할까요?
Human: 예, 그렇게하세요."""
)
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.
Assistant: Can I think step by step?
Human: Yes, please do."""
)
human = "<text>{text}</text>"
prompt = ChatPromptTemplate.from_messages([("system", system), ("human", human)])
# print('prompt: ', prompt)
chain = prompt | chat
try:
result = chain.invoke(
{
"text": text
}
)
msg = result.content
print('result of sentiment extraction: ', msg)
except Exception:
err_msg = traceback.format_exc()
print('error message: ', err_msg)
raise Exception ("Not able to request to LLM")
return msg
def extract_timestamp(chat, text):
system = (
"""Human: 아래의 <text>는 시간을 포함한 텍스트입니다. 친절한 AI Assistant로서 시간을 추출하여 아래를 참조하여 <example>과 같이 정리해주세요.
- 년도를 추출해서 <year>/<year>로 넣을것
- 월을 추출해서 <month>/<month>로 넣을것
- 일을 추출해서 <day>/<day>로 넣을것
- 시간을 추출해서 24H으로 정리해서 <hour>/<hour>에 넣을것
- 분을 추출해서 <minute>/<minute>로 넣을것
이때의 예제는 아래와 같습니다.
<example>
2022년 11월 3일 18시 26분
</example>
<result>
<year>2022</year>
<month>11</month>
<day>03</day>
<hour>18</hour>
<minute>26</minute>
</result>
결과에 개행문자인 "\n"과 글자 수와 같은 부가정보는 절대 포함하지 마세요."""
)
human = "<text>{text}</text>"
prompt = ChatPromptTemplate.from_messages([("system", system), ("human", human)])
# print('prompt: ', prompt)
chain = prompt | chat
try:
result = chain.invoke(
{
"text": text
}
)
output = result.content
msg = output[output.find('<result>')+8:len(output)-9] # remove <result>
print('result of sentiment extraction: ', msg)
except Exception:
err_msg = traceback.format_exc()
print('error message: ', err_msg)
raise Exception ("Not able to request to LLM")
return msg
def use_multimodal(img_base64, query):
multimodal = get_multimodal()
if query == "":
query = "그림에 대해 상세히 설명해줘."
messages = [
SystemMessage(content="답변은 500자 이내의 한국어로 설명해주세요."),
HumanMessage(
content=[
{
"type": "image_url",
"image_url": {
"url": f"data:image/png;base64,{img_base64}",
},
},
{
"type": "text", "text": query
},
]
)
]
try:
result = multimodal.invoke(messages)
summary = result.content
print('result of code 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 get_prompt_template(query, conv_type, rag_type):
if isKorean(query):
if conv_type == "normal": # for General Conversation
prompt_template = """\n\nHuman: 다음의 <history>는 Human과 Assistant의 친근한 이전 대화입니다. Assistant은 상황에 맞는 구체적인 세부 정보를 충분히 제공합니다. Assistant의 이름은 서연이고, 모르는 질문을 받으면 솔직히 모른다고 말합니다.
<history>
{history}
</history>
<question>
{input}
</question>
Assistant:"""
elif conv_type=='qa':
# for RAG, context and question
#prompt_template = """\n\nHuman: 다음의 참고자료(<context>)를 참조하여 상황에 맞는 구체적인 세부 정보를 충분히 제공합니다. Assistant의 이름은 서연이고, 모르는 질문을 받으면 솔직히 모른다고 말합니다.
#prompt_template = """\n\nHuman: 참고자료로 부터 구체적인 세부 정보를 충분히 제공합니다. 참고자료는 <context></context> XML tags안에 있습니다. Assistant의 이름은 서연이고, 모르는 질문을 받으면 솔직히 모른다고 말합니다.
prompt_template = """\n\nHuman: 다음의 <context> tag안의 참고자료를 이용하여 상황에 맞는 구체적인 세부 정보를 충분히 제공합니다. Assistant의 이름은 서연이고, 모르는 질문을 받으면 솔직히 모른다고 말합니다.
<context>
{context}
</context>
<question>
{question}
</question>
Assistant:"""
elif conv_type == "translation": # for translation, input
prompt_template = """\n\nHuman: 다음의 <article>를 English로 번역하세요. 머리말은 건너뛰고 본론으로 바로 들어가주세요. 또한 결과는 <result> tag를 붙여주세요.
<article>
{input}
</article>
Assistant:"""
elif conv_type == "sentiment": # for sentiment, input
prompt_template = """\n\nHuman: 아래의 <example> review와 Extracted Topic and sentiment 인 <result>가 있습니다.
<example>
객실은 작지만 깨끗하고 편안합니다. 프론트 데스크는 정말 분주했고 체크인 줄도 길었지만, 직원들은 프로페셔널하고 매우 유쾌하게 각 사람을 응대했습니다. 우리는 다시 거기에 머물것입니다.
</example>
<result>
청소: 긍정적,
서비스: 긍정적
</result>
아래의 <review>에 대해서 위의 <result> 예시처럼 Extracted Topic and sentiment 을 만들어 주세요..
<review>
{input}
</review>
Assistant:"""
elif conv_type == "extraction": # information extraction
prompt_template = """\n\nHuman: 다음 텍스트에서 이메일 주소를 정확하게 복사하여 한 줄에 하나씩 적어주세요. 입력 텍스트에 정확하게 쓰여있는 이메일 주소만 적어주세요. 텍스트에 이메일 주소가 없다면, "N/A"라고 적어주세요. 또한 결과는 <result> tag를 붙여주세요.
<text>
{input}
</text>
Assistant:"""
elif conv_type == "pii": # removing PII(personally identifiable information) containing name, phone number, address
prompt_template = """\n\nHuman: 아래의 <text>에서 개인식별정보(PII)를 모두 제거하여 외부 계약자와 안전하게 공유할 수 있도록 합니다. 이름, 전화번호, 주소, 이메일을 XXX로 대체합니다. 또한 결과는 <result> tag를 붙여주세요.
<text>
{input}
</text>
Assistant:"""
elif conv_type == "grammar": # Checking Grammatical Errors
prompt_template = """\n\nHuman: 다음의 <article>에서 문장의 오류를 찾아서 설명하고, 오류가 수정된 문장을 답변 마지막에 추가하여 주세요.
<article>
{input}
</article>
Assistant: """
elif conv_type == "step-by-step": # compelex question
prompt_template = """\n\nHuman: 다음은 Human과 Assistant의 친근한 대화입니다. Assistant은 상황에 맞는 구체적인 세부 정보를 충분히 제공합니다. 아래 문맥(context)을 참조했음에도 답을 알 수 없다면, 솔직히 모른다고 말합니다. 여기서 Assistant의 이름은 서연입니다.
{input}
Assistant: 단계별로 생각할까요?
Human: 예, 그렇게하세요.
Assistant:"""
elif conv_type == "like-child": # Child Conversation (few shot)
prompt_template = """\n\nHuman: 다음 대화를 완성하기 위해 "A"로 말하는 다음 줄을 작성하세요. Assistant는 유치원 선생님처럼 대화를 합니다.
Q: 이빨 요정은 실제로 있을까?
A: 물론이죠, 오늘 밤 당신의 이를 감싸서 베개 밑에 넣어두세요. 아침에 뭔가 당신을 기다리고 있을지도 모릅니다.
Q: {input}
Assistant:"""
elif conv_type == "timestamp-extraction":
prompt_template = """\n\nHuman: 아래의 <text>는 시간을 포함한 텍스트입니다. 친절한 AI Assistant로서 시간을 추출하여 아래를 참조하여 <example>과 같이 정리해주세요.
- 년도를 추출해서 <year>/<year>로 넣을것
- 월을 추출해서 <month>/<month>로 넣을것
- 일을 추출해서 <day>/<day>로 넣을것
- 시간을 추출해서 24H으로 정리해서 <hour>/<hour>에 넣을것
- 분을 추출해서 <minute>/<minute>로 넣을것
이때의 예제는 아래와 같습니다.
<example>
2022년 11월 3일 18시 26분
</example>
<result>
<year>2022</year>
<month>11</month>
<day>03</day>
<hour>18</hour>
<minute>26</minute>
</result>
결과에 개행문자인 "\n"과 글자 수와 같은 부가정보는 절대 포함하지 마세요.
<text>
{input}
</text>
Assistant:"""
elif conv_type == "funny": # for free conversation
prompt_template = """\n\nHuman: 다음의 <history>는 Human과 Assistant의 친근한 이전 대화입니다. 모든 대화는 반말로하여야 합니다. Assistant의 이름은 서서이고 10살 여자 어린이 상상력이 풍부하고 재미있는 대화를 합니다. 때로는 바보같은 답변을 해서 재미있게 해줍니다.
<history>
{history}
</history>
<question>
{input}
</question>
Assistant:"""
elif conv_type == "get-weather": # getting weather (function calling)
prompt_template = """\n\nHuman: In this environment you have access to a set of tools you can use to answer the user's question.
You may call them like this. Only invoke one function at a time and wait for the results before invoking another function:
<function_calls>
<invoke>