-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFAQ_RAG_Agent.py
More file actions
603 lines (543 loc) · 19.3 KB
/
Copy pathFAQ_RAG_Agent.py
File metadata and controls
603 lines (543 loc) · 19.3 KB
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
# You may need to add your working directory to the Python path. To do so, uncomment the following lines of code
# import sys
# sys.path.append("/Path/to/directory/besser-agentic-framework") # Replace with your directory path
import json
import logging
import operator
from baf.core.agent import Agent
from baf.library.transition.events.base_events import *
from baf.nlp.llm.llm_huggingface import LLMHuggingFace
from baf.nlp.llm.llm_huggingface_api import LLMHuggingFaceAPI
from baf.nlp.llm.llm_openai_api import LLMOpenAI
from baf.nlp.llm.llm_replicate_api import LLMReplicate
from baf.core.session import Session
from baf.nlp.intent_classifier.intent_classifier_configuration import LLMIntentClassifierConfiguration, SimpleIntentClassifierConfiguration
from baf.nlp.speech2text.openai_speech2text import OpenAISpeech2Text
from baf.nlp.text2speech.openai_text2speech import OpenAIText2Speech
from langchain_community.embeddings import OpenAIEmbeddings
from langchain_community.vectorstores import Chroma
from langchain_text_splitters import RecursiveCharacterTextSplitter
from baf import nlp
from baf.nlp.rag.rag import RAG
# Configure the logging module
logging.basicConfig(level=logging.INFO, format='{levelname} - {asctime}: {message}', style='{')
def build_agent_configuration_prompt(agent_configuration: dict) -> str:
base_prompt = """
You are a personalized AI assistant.
You will be provided with an object called `agent_configuration` as a JSON string.
This object defines how you should present yourself and formulate your responses.
It controls stylistic and presentation aspects such as:
- Response language
- Level of formality
- Language complexity
- Sentence length
- And more
You must strictly follow the preferences defined in `agent_configuration` for all responses.
Here is the current agent configuration (JSON):
{agent_configuration_json}
"""
return base_prompt.format(agent_configuration_json=json.dumps(agent_configuration, indent=2))
def build_user_profile_prompt(user_profile: dict) -> str:
profile_prompt = """
You have access to the current user's profile encoded as JSON.
Leverage these traits whenever the agent configuration instructs you to adapt content.
Here is the active user profile (JSON):
{user_profile_json}
"""
return profile_prompt.format(user_profile_json=json.dumps(user_profile, indent=2))
# Create the bot
agent = Agent('FAQ_RAG_Agent', user_profiles_path='user_profiles.json', persist_sessions=True)
# Load bot properties stored in a dedicated file
agent.load_properties('config.yaml')
# Define the platform your chatbot will use
# Collect profile names from provided personalization mappings
profile_names = []
agent_configurations = {}
user_profiles = {}
context_prompts = {}
profile_prompts = {}
profile_names.append('Layperson')
agent_configurations['Layperson'] = json.loads(r'''{
"adaptContentToUserProfile": true,
"agentLanguage": "original",
"agentPlatform": "streamlit",
"agentStyle": "original",
"avatar": null,
"inputModalities": [
"text",
"speech"
],
"intentRecognitionTechnology": "llm-based",
"interfaceStyle": {
"alignment": "left",
"color": "var(--apollon-primary-contrast)",
"contrast": "medium",
"font": "sans",
"lineSpacing": 1.5,
"size": 16
},
"languageComplexity": "original",
"llm": {
"model": "gpt-5",
"provider": "openai"
},
"outputModalities": [
"text",
"speech"
],
"responseTiming": "instant",
"sentenceLength": "original",
"useAbbreviations": false,
"userProfileName": "Layperson",
"voiceStyle": {
"gender": "male",
"speed": 1
}
}''')
user_profiles['Layperson'] = json.loads(r'''{
"model": {
"class": "User",
"id": "user_1"
},
"name": "UserProfile"
}''')
context_prompts['Layperson'] = build_agent_configuration_prompt(agent_configurations['Layperson'])
profile_prompts['Layperson'] = build_user_profile_prompt(user_profiles['Layperson'])
profile_names.append('Lawyer')
agent_configurations['Lawyer'] = json.loads(r'''{
"adaptContentToUserProfile": true,
"agentLanguage": "original",
"agentPlatform": "streamlit",
"agentStyle": "original",
"avatar": null,
"inputModalities": [
"text",
"speech"
],
"intentRecognitionTechnology": "llm-based",
"interfaceStyle": {
"alignment": "left",
"color": "var(--apollon-primary-contrast)",
"contrast": "medium",
"font": "sans",
"lineSpacing": 1.5,
"size": 16
},
"languageComplexity": "original",
"llm": {
"model": "gpt-5",
"provider": "openai"
},
"outputModalities": [
"text",
"speech"
],
"responseTiming": "instant",
"sentenceLength": "original",
"useAbbreviations": false,
"userProfileName": "Layperson",
"voiceStyle": {
"gender": "male",
"speed": 1
}
}''')
user_profiles['Lawyer'] = json.loads(r'''{
"model": {
"Competence": {
"Skill": {
"name": "Legal_Expertise",
"score": "100"
}
},
"Personal_Information": {
"age": 25
},
"class": "User",
"id": "Lawyer"
},
"name": "UserProfile"
}''')
context_prompts['Lawyer'] = build_agent_configuration_prompt(agent_configurations['Lawyer'])
profile_names.append('User 2')
agent_configurations['User_2'] = json.loads(r'''{
"adaptContentToUserProfile": true,
"agentLanguage": "original",
"agentPlatform": "streamlit",
"agentStyle": "original",
"avatar": null,
"inputModalities": [
"text",
"speech"
],
"intentRecognitionTechnology": "llm-based",
"interfaceStyle": {
"alignment": "left",
"color": "var(--apollon-primary-contrast)",
"contrast": "medium",
"font": "sans",
"lineSpacing": 1.5,
"size": 16
},
"languageComplexity": "original",
"llm": {
"model": "gpt-5",
"provider": "openai"
},
"outputModalities": [
"text",
"speech"
],
"responseTiming": "instant",
"sentenceLength": "original",
"useAbbreviations": false,
"userProfileName": "Layperson",
"voiceStyle": {
"gender": "male",
"speed": 1
}
}''')
user_profiles['User_2'] = json.loads(r'''{
"model": {
"Accessibility": {
"Disability": {
"affects": "Mobility",
"description": "can\u0027t use lower body",
"name": "Paraplegic"
}
},
"class": "User",
"id": "user_1"
},
"name": "UserProfile"
}''')
context_prompts['User_2'] = build_agent_configuration_prompt(agent_configurations['User_2'])
profile_names.append('User Diagram')
agent_configurations['User_Diagram'] = json.loads(r'''{
"adaptContentToUserProfile": true,
"agentLanguage": "original",
"agentPlatform": "streamlit",
"agentStyle": "original",
"avatar": null,
"inputModalities": [
"text",
"speech"
],
"intentRecognitionTechnology": "llm-based",
"interfaceStyle": {
"alignment": "left",
"color": "var(--apollon-primary-contrast)",
"contrast": "medium",
"font": "sans",
"lineSpacing": 1.5,
"size": 16
},
"languageComplexity": "original",
"llm": {
"model": "gpt-5",
"provider": "openai"
},
"outputModalities": [
"text",
"speech"
],
"responseTiming": "instant",
"sentenceLength": "original",
"useAbbreviations": false,
"userProfileName": "Layperson",
"voiceStyle": {
"gender": "male",
"speed": 1
}
}''')
user_profiles['User_Diagram'] = json.loads(r'''{
"model": {
"Personal_Information": {
"age": 65
},
"class": "User",
"id": "user_1"
},
"name": "UserProfile"
}''')
context_prompts['User_Diagram'] = build_agent_configuration_prompt(agent_configurations['User_Diagram'])
agent.set_agent_configurations(agent_configurations)
platform = agent.use_websocket_platform(use_ui=True, authenticate_users=True)
# LLM instantiation based on config['llm']
reply_llm = LLMOpenAI(
agent=agent,
name='gpt-5',
parameters={}
)
stt = OpenAISpeech2Text(agent=agent, model_name="whisper-1")
tts = OpenAIText2Speech(agent=agent, model_name="gpt-4o-mini-tts")
rag_llm = LLMOpenAI(
agent=agent,
name='gpt-4o-mini',
parameters={},
num_previous_messages=10
)
##############################
# RAG CONFIGURATIONS
##############################
esc_rag_vector_store = Chroma(
embedding_function=OpenAIEmbeddings(openai_api_key=agent.get_property(nlp.OPENAI_API_KEY)),
persist_directory='vector_store/esc_rag'
)
esc_rag_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
esc_rag_rag = RAG(
agent=agent,
vector_store=esc_rag_vector_store,
splitter=esc_rag_splitter,
llm_name='gpt-4o-mini',
k=4,
num_previous_messages=0
)
esc_rag_rag.load_pdfs('./esc_rag')
ic_config = LLMIntentClassifierConfiguration(
llm_name='gpt-5',
parameters={},
use_intent_descriptions=True,
use_training_sentences=True,
use_entity_descriptions=False,
use_entity_synonyms=False
)
agent.set_default_ic_config(ic_config)
##############################
# INTENTS
##############################
##############################
# PERSONALIZED INTENTS
##############################
# Intents for profile Layperson
# Intents for profile Lawyer
# Intents for profile User_2
# Intents for profile User_Diagram
##############################
# CUSTOM CONDITIONS
##############################
##############################
# STATES
##############################
# Dummy entry state to fan out to profile-specific initial states
router_initial_state = agent.new_state('router_initial_state', initial=True)
Greeting = agent.new_state('Greeting')
Idle = agent.new_state('Idle')
Response = agent.new_state('Response')
##############################
# PROFILE STATES
##############################
# States for profile Layperson
Greeting_Layperson = agent.new_state('Greeting_Layperson')
Idle_Layperson = agent.new_state('Idle_Layperson')
Response_Layperson = agent.new_state('Response_Layperson')
# States for profile Lawyer
Greeting_Lawyer = agent.new_state('Greeting_Lawyer')
Idle_Lawyer = agent.new_state('Idle_Lawyer')
Response_Lawyer = agent.new_state('Response_Lawyer')
# States for profile User_2
Greeting_User_2 = agent.new_state('Greeting_User_2')
Idle_User_2 = agent.new_state('Idle_User_2')
Response_User_2 = agent.new_state('Response_User_2')
# States for profile User_Diagram
Greeting_User_Diagram = agent.new_state('Greeting_User_Diagram')
Idle_User_Diagram = agent.new_state('Idle_User_Diagram')
Response_User_Diagram = agent.new_state('Response_User_Diagram')
##############################
# ROUTER TRANSITIONS TO PROFILE INITIAL STATES
##############################
router_initial_state.when_variable_matches_operation('user_profile', operator.eq, 'Layperson').go_to(Greeting_Layperson)
router_initial_state.when_variable_matches_operation('user_profile', operator.eq, 'Lawyer').go_to(Greeting_Lawyer)
router_initial_state.when_variable_matches_operation('user_profile', operator.eq, 'User 2').go_to(Greeting_User_2)
router_initial_state.when_variable_matches_operation('user_profile', operator.eq, 'User Diagram').go_to(Greeting_User_Diagram)
# Greeting
def Greeting_body(session: Session):
speech_messages = []
reply_text = 'Hi, I am your leagl assistant, I can answer questions related to the ESC.'
session.reply(reply_text)
speech_messages.append(reply_text)
if speech_messages:
platform.reply_speech(session, ' '.join(speech_messages))
Greeting.set_body(Greeting_body)
Greeting.go_to(Idle)
# Idle
def Idle_body(session: Session):
speech_messages = []
reply_text = 'What would you like to know about the ESC?'
session.reply(reply_text)
speech_messages.append(reply_text)
if speech_messages:
platform.reply_speech(session, ' '.join(speech_messages))
Idle.set_body(Idle_body)
Idle.when_no_intent_matched().go_to(Response)
Idle.when_variable_matches_operation('user_profile', operator.eq, 'Layperson').go_to(router_initial_state)
Idle.when_variable_matches_operation('user_profile', operator.eq, 'Lawyer').go_to(router_initial_state)
Idle.when_variable_matches_operation('user_profile', operator.eq, 'User 2').go_to(router_initial_state)
Idle.when_variable_matches_operation('user_profile', operator.eq, 'User Diagram').go_to(router_initial_state)
# Response
def Response_body(session: Session):
rag_message = session.run_rag(session.event.message)
platform.reply_rag(session, rag_message)
Response.set_body(Response_body)
Response.go_to(Idle)
##############################
# PROFILE STATE BODIES & TRANSITIONS
##############################
# Greeting (Layperson)
def Greeting_body_Layperson(session: Session):
reply_llm.add_user_context(
session=session,
context=context_prompts.get('Layperson'),
context_name='agent_configuration_Layperson'
)
reply_llm.add_user_context(
session=session,
context=profile_prompts.get('Layperson'),
context_name='user_profile_Layperson'
)
speech_messages = []
reply_text = 'Hi, I am your leagl assistant, I can answer questions related to the ESC.'
session.reply(reply_text)
speech_messages.append(reply_text)
if speech_messages:
platform.reply_speech(session, ' '.join(speech_messages))
Greeting_Layperson.set_body(Greeting_body_Layperson)
Greeting_Layperson.go_to(Idle_Layperson)
# Idle (Layperson)
def Idle_body_Layperson(session: Session):
speech_messages = []
reply_text = 'What would you like to know about the ESC?'
session.reply(reply_text)
speech_messages.append(reply_text)
if speech_messages:
platform.reply_speech(session, ' '.join(speech_messages))
Idle_Layperson.set_body(Idle_body_Layperson)
Idle_Layperson.when_no_intent_matched().go_to(Response_Layperson)
Idle_Layperson.when_variable_matches_operation('user_profile', operator.eq, 'Lawyer').go_to(router_initial_state)
Idle_Layperson.when_variable_matches_operation('user_profile', operator.eq, 'User 2').go_to(router_initial_state)
Idle_Layperson.when_variable_matches_operation('user_profile', operator.eq, 'User Diagram').go_to(router_initial_state)
# Response (Layperson)
def Response_body_Layperson(session: Session):
rag_message = session.run_rag(session.event.message)
platform.reply_rag(session, rag_message)
Response_Layperson.set_body(Response_body_Layperson)
Response_Layperson.go_to(Idle_Layperson)
# Greeting (Lawyer)
def Greeting_body_Lawyer(session: Session):
reply_llm.add_user_context(
session=session,
context=context_prompts.get('Lawyer'),
context_name='agent_configuration_Lawyer'
)
reply_llm.add_user_context(
session=session,
context=profile_prompts.get('Lawyer'),
context_name='user_profile_Lawyer'
)
speech_messages = []
reply_text = 'Hi, I am your leagl assistant, I can answer questions related to the ESC.'
session.reply(reply_text)
speech_messages.append(reply_text)
if speech_messages:
platform.reply_speech(session, ' '.join(speech_messages))
Greeting_Lawyer.set_body(Greeting_body_Lawyer)
Greeting_Lawyer.go_to(Idle_Lawyer)
# Idle (Lawyer)
def Idle_body_Lawyer(session: Session):
speech_messages = []
reply_text = 'What would you like to know about the ESC?'
session.reply(reply_text)
speech_messages.append(reply_text)
if speech_messages:
platform.reply_speech(session, ' '.join(speech_messages))
Idle_Lawyer.set_body(Idle_body_Lawyer)
Idle_Lawyer.when_no_intent_matched().go_to(Response_Lawyer)
Idle_Lawyer.when_variable_matches_operation('user_profile', operator.eq, 'Layperson').go_to(router_initial_state)
Idle_Lawyer.when_variable_matches_operation('user_profile', operator.eq, 'User 2').go_to(router_initial_state)
Idle_Lawyer.when_variable_matches_operation('user_profile', operator.eq, 'User Diagram').go_to(router_initial_state)
# Response (Lawyer)
def Response_body_Lawyer(session: Session):
rag_message = session.run_rag(session.event.message)
platform.reply_rag(session, rag_message)
Response_Lawyer.set_body(Response_body_Lawyer)
Response_Lawyer.go_to(Idle_Lawyer)
# Greeting (User_2)
def Greeting_body_User_2(session: Session):
reply_llm.add_user_context(
session=session,
context=context_prompts.get('User_2'),
context_name='agent_configuration_User_2'
)
reply_llm.add_user_context(
session=session,
context=profile_prompts.get('User_2'),
context_name='user_profile_User_2'
)
speech_messages = []
reply_text = 'Hi, I am your leagl assistant, I can answer questions related to the ESC.'
session.reply(reply_text)
speech_messages.append(reply_text)
if speech_messages:
platform.reply_speech(session, ' '.join(speech_messages))
Greeting_User_2.set_body(Greeting_body_User_2)
Greeting_User_2.go_to(Idle_User_2)
# Idle (User_2)
def Idle_body_User_2(session: Session):
speech_messages = []
reply_text = 'What would you like to know about the ESC?'
session.reply(reply_text)
speech_messages.append(reply_text)
if speech_messages:
platform.reply_speech(session, ' '.join(speech_messages))
Idle_User_2.set_body(Idle_body_User_2)
Idle_User_2.when_no_intent_matched().go_to(Response_User_2)
Idle_User_2.when_variable_matches_operation('user_profile', operator.eq, 'Layperson').go_to(router_initial_state)
Idle_User_2.when_variable_matches_operation('user_profile', operator.eq, 'Lawyer').go_to(router_initial_state)
Idle_User_2.when_variable_matches_operation('user_profile', operator.eq, 'User Diagram').go_to(router_initial_state)
# Response (User_2)
def Response_body_User_2(session: Session):
rag_message = session.run_rag(session.event.message)
platform.reply_rag(session, rag_message)
Response_User_2.set_body(Response_body_User_2)
Response_User_2.go_to(Idle_User_2)
# Greeting (User_Diagram)
def Greeting_body_User_Diagram(session: Session):
reply_llm.add_user_context(
session=session,
context=context_prompts.get('User_Diagram'),
context_name='agent_configuration_User_Diagram'
)
reply_llm.add_user_context(
session=session,
context=profile_prompts.get('User_Diagram'),
context_name='user_profile_User_Diagram'
)
speech_messages = []
reply_text = 'Hi, I am your leagl assistant, I can answer questions related to the ESC.'
session.reply(reply_text)
speech_messages.append(reply_text)
if speech_messages:
platform.reply_speech(session, ' '.join(speech_messages))
Greeting_User_Diagram.set_body(Greeting_body_User_Diagram)
Greeting_User_Diagram.go_to(Idle_User_Diagram)
# Idle (User_Diagram)
def Idle_body_User_Diagram(session: Session):
speech_messages = []
reply_text = 'What would you like to know about the ESC?'
session.reply(reply_text)
speech_messages.append(reply_text)
if speech_messages:
platform.reply_speech(session, ' '.join(speech_messages))
Idle_User_Diagram.set_body(Idle_body_User_Diagram)
Idle_User_Diagram.when_no_intent_matched().go_to(Response_User_Diagram)
Idle_User_Diagram.when_variable_matches_operation('user_profile', operator.eq, 'Layperson').go_to(router_initial_state)
Idle_User_Diagram.when_variable_matches_operation('user_profile', operator.eq, 'Lawyer').go_to(router_initial_state)
Idle_User_Diagram.when_variable_matches_operation('user_profile', operator.eq, 'User 2').go_to(router_initial_state)
# Response (User_Diagram)
def Response_body_User_Diagram(session: Session):
rag_message = session.run_rag(session.event.message)
platform.reply_rag(session, rag_message)
Response_User_Diagram.set_body(Response_body_User_Diagram)
Response_User_Diagram.go_to(Idle_User_Diagram)
# RUN APPLICATION
if __name__ == '__main__':
agent.run()