-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathagent.py
More file actions
1137 lines (974 loc) · 53.1 KB
/
agent.py
File metadata and controls
1137 lines (974 loc) · 53.1 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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import json
import torch
import tiktoken
from openai import OpenAI
from utils.templates import get_template
from utils.eval_data_utils import (
format_chat,
)
import re
import time
from langchain_core.documents import Document
from transformers import BitsAndBytesConfig
from transformers import AutoTokenizer, AutoModelForCausalLM, LlamaConfig
class AgentWrapper:
"""
A wrapper class for different types of memory agents including:
- Long context agents (GPT, Claude, Gemini)
- Letta agents
- Mem0 agents
- Cognee agents
- RAG agents (various implementations)
"""
def __init__(self, agent_config, dataset_config, load_agent_from):
"""
Initialize the agent wrapper with specified configuration.
Args:
agent_config: Configuration dictionary for the agent
dataset_config: Configuration dictionary for the dataset
load_agent_from: Optional path to load existing agent state from
"""
# Basic agent configuration
self.agent_name = agent_config['agent_name']
self.sub_dataset = dataset_config['sub_dataset']
self.context_max_length = dataset_config['context_max_length']
self.dataset = dataset_config['dataset']
# Output and storage configuration
self.output_dir = agent_config['output_dir']
self.agent_save_to_folder = load_agent_from
# Context and token limits
self.input_length_limit = (agent_config['input_length_limit'] -
agent_config['buffer_length'] -
dataset_config['generation_max_length'])
# Model configuration
self.model = agent_config['model']
self.max_tokens = dataset_config['generation_max_length']
self.temperature = agent_config.get('temperature', 0.0)
# Initialize tokenizer (default to gpt-4o-mini for non-gpt models)
model_for_tokenizer = self.model if "gpt-4o" in self.model else "gpt-4o-mini"
self.tokenizer = tiktoken.encoding_for_model(model_for_tokenizer)
# Initialize agent based on type
self._initialize_agent_by_type(agent_config, dataset_config)
def _initialize_agent_by_type(self, agent_config, dataset_config):
"""Initialize the specific agent type based on agent name."""
if 'Long_context_agent' in self.agent_name:
self._initialize_long_context_agent()
elif self._is_agent_type("letta"):
self._initialize_letta_agent(agent_config, dataset_config)
elif self._is_agent_type("mem0"):
self._initialize_mem0_agent(agent_config, dataset_config)
elif self._is_agent_type("cognee"):
self._initialize_cognee_agent(agent_config, dataset_config)
elif self._is_agent_type("zep"):
self._initialize_zep_agent(agent_config)
elif self._is_agent_type("rag"):
self._initialize_rag_agent(agent_config, dataset_config)
else:
raise NotImplementedError(f"Agent type not supported: {self.agent_name}")
def _is_agent_type(self, agent_type):
"""Check if the current agent is of a specific type."""
return agent_type in self.agent_name
def _create_oai_client(self):
"""Create an OpenAI-compatible client. Uses Azure OpenAI if env vars are set.
Environment variables for Azure:
- AZURE_OPENAI_ENDPOINT
- AZURE_OPENAI_API_VERSION (optional; default provided by SDK or pinned elsewhere)
- AZURE_OPENAI_API_KEY
When using Azure, ensure self.model is the deployment name.
"""
try:
azure_endpoint = os.environ.get("AZURE_OPENAI_ENDPOINT")
if azure_endpoint:
# Lazy import to avoid requiring Azure class when not used
from openai import AzureOpenAI
return AzureOpenAI(
api_key=os.environ.get("AZURE_OPENAI_API_KEY"),
api_version=os.environ.get("AZURE_OPENAI_API_VERSION"),
azure_endpoint=azure_endpoint,
)
except Exception:
pass
return OpenAI()
def _create_standard_response(self, output, input_tokens, output_tokens, memory_time, query_time):
"""Create standardized response dictionary."""
return {
"output": output,
"input_len": input_tokens,
"output_len": output_tokens,
"memory_construction_time": memory_time,
"query_time_len": query_time,
}
def _initialize_long_context_agent(self):
"""Initialize long context agent with appropriate client."""
self.context = ''
if "gpt" in self.model or "o4" in self.model:
self.client = self._create_oai_client()
elif "claude" in self.model:
import anthropic
self.client = anthropic.Anthropic(
api_key=os.environ.get('Anthropic_API_KEY'),
)
elif "gemini" in self.model:
from google import genai
self.client = genai.Client(api_key=os.environ.get('Google_API_KEY'))
else:
raise NotImplementedError(f"Model not supported for long context agent: {self.model}")
def _initialize_letta_agent(self, agent_config, dataset_config):
"""Initialize Letta agent with proper configuration."""
if "api" not in agent_config['agent_name']:
from letta import create_client, LLMConfig, EmbeddingConfig, BasicBlockMemory
self.chunk_size = agent_config['agent_chunk_size']
self.letta_mode = agent_config['letta_mode']
self.client = create_client()
self.client.set_default_llm_config(LLMConfig.default_config(agent_config['model']))
self.agent_start_time = time.time()
# Configure embedding
if agent_config['text_embedding'] == 'text-embedding-3-small':
self.client.set_default_embedding_config(EmbeddingConfig(
embedding_model="text-embedding-3-small",
embedding_endpoint_type="openai",
embedding_endpoint="https://api.openai.com/v1",
embedding_dim=1536,
embedding_chunk_size=self.chunk_size * 2,
))
else:
self.client.set_default_embedding_config(
EmbeddingConfig.default_config(agent_config['text_embedding'])
)
# Load system prompt
system_path = agent_config['system_path']
with open(system_path, 'r') as f:
self.system = f.read()
# Load or create agent
if os.path.exists(self.agent_save_to_folder):
self.load_agent()
else:
human_block = self.client.create_block(
label='human',
value='User is sharing the contents they are reading recently.',
limit=2000000
)
persona_block = self.client.create_block(
label='persona',
value='You are a helpful assistant that can help memorize details in the conversation.',
limit=2000000
)
memory = BasicBlockMemory(blocks=[human_block, persona_block])
self.agent_state = self.client.create_agent(
name='mm_agent',
memory=memory,
system=self.system
)
## use the letta api to create the agent
else:
from letta_client import Letta, CreateBlock
self.chunk_size = agent_config['agent_chunk_size']
self.letta_mode = agent_config['letta_mode']
self.agent_start_time = time.time()
self.client = Letta(token=os.environ.get('Letta_API_KEY'))
self.agent_state = self.client.agents.create(
memory_blocks=[
CreateBlock(
label="human",
limit=2000000,
value="User is sharing the contents they are reading recently."
),
CreateBlock(
label="persona",
limit=2000000,
value="You are a helpful assistant that can help memorize details in the conversation."
)
],
model=f"openai/{agent_config['model']}",
embedding=f"openai/{agent_config['text_embedding']}"
)
def _initialize_mem0_agent(self, agent_config, dataset_config):
"""Initialize Mem0 agent with retrieval configuration."""
from mem0.memory.main import Memory
self.retrieve_num = agent_config['retrieve_num']
self.context = ''
self.client = self._create_oai_client()
self.memory = Memory()
self.agent_start_time = time.time()
def _initialize_cognee_agent(self, agent_config, dataset_config):
"""Initialize Cognee agent with knowledge graph configuration."""
self.context = ''
self.chunks = []
self.retrieve_num = agent_config['retrieve_num']
self.chunk_size = agent_config['agent_chunk_size']
self.agent_start_time = time.time()
self.cognee_dir = './cognee/.cognee_system/databases/cognee.lancedb'
def _initialize_zep_agent(self, agent_config):
# from zep_cloud.client import AsyncZep
# self.client = AsyncZep(api_key=os.getenv("ZEP_API_KEY"), base_url="https://api.development.getzep.com/api/v2")
from zep_cloud import Zep
from methods.zep import OpenAIAgent
self.retrieve_num = agent_config['retrieve_num']
self.chunk_size = agent_config['agent_chunk_size']
self.context_id = -1
self.client = Zep(api_key=os.getenv("ZEP_API_KEY"))
self.oai_client = OpenAIAgent(model=self.model, source="azure", api_dict={"endpoint":os.environ.get("AZURE_OPENAI_ENDPOINT"), "api_version":os.environ.get("AZURE_OPENAI_API_VERSION"), "api_key":os.environ.get("AZURE_OPENAI_API_KEY")}, temperature=self.temperature)
self.agent_start_time = time.time()
def _initialize_rag_agent(self, agent_config, dataset_config):
"""Initialize RAG agent with retrieval configuration."""
self.context = ''
self.chunks = []
self.retrieve_num = agent_config['retrieve_num']
self.chunk_size = dataset_config['chunk_size']
self.context_len = 0
self.context_id = -1
def send_message(self, message, memorizing=False, query_id=None, context_id=None):
"""
Send a message to the agent for either memorization or querying.
Args:
message: The message content (context for memorization, query for answering)
memorizing: Whether to memorize the message (True) or answer it (False)
query_id: Unique identifier for the query
context_id: Unique identifier for the context
Returns:
dict or str: Agent response with metadata (for queries) or confirmation (for memorization)
"""
# Route to appropriate agent handler based on agent type
if 'Long_context_agent' in self.agent_name:
return self._handle_long_context_agent(message, memorizing)
elif any(self._is_agent_type(agent_type) for agent_type in ["letta", "cognee", "mem0", "zep"]):
return self._handle_memory_agent(message, memorizing, query_id, context_id)
elif self._is_agent_type("rag"):
return self._handle_rag_agent(message, memorizing, query_id, context_id)
else:
raise NotImplementedError(f"Agent type not supported: {self.agent_name}")
def _handle_long_context_agent(self, message, memorizing):
"""Handle message processing for long context agents."""
if memorizing:
# Add message to context memory
memorize_template = get_template(self.sub_dataset, 'memorize', self.agent_name)
formatted_message = memorize_template.format(context=message, **({'time_stamp': time.strftime("%Y-%m-%d %H:%M:%S")} if '{time_stamp}' in memorize_template else {}))
self.context += "\n" + formatted_message
self.context = self.context.strip()
return "Memorized"
else:
# Process query with context
return self._query_long_context_agent(message)
def _query_long_context_agent(self, message):
"""Process a query for long context agents."""
# Get appropriate tokenizer
try:
tokenizer = tiktoken.encoding_for_model(self.model)
except:
tokenizer = tiktoken.encoding_for_model("gpt-4o-mini")
# Handle context truncation for non-long context models
buffer_length = 50000
if self.input_length_limit <= self.context_max_length + buffer_length:
self._truncate_context_if_needed(tokenizer)
# Format message with context and system prompt
full_message = self.context + "\n" + message
system_message = get_template(self.sub_dataset, 'system', self.agent_name)
formatted_message = format_chat(message=full_message, system_message=system_message)
# Query the model
start_time = time.time()
if "gpt" in self.model:
response = self.client.chat.completions.create(
model=self.model,
messages=formatted_message,
temperature=self.temperature,
max_tokens=self.max_tokens
)
return self._format_openai_response(response, start_time)
elif "o4" in self.model:
response = self.client.chat.completions.create(
model=self.model,
messages=formatted_message,
)
return self._format_openai_response(response, start_time)
elif "claude" in self.model:
return self._query_claude(full_message, system_message, start_time)
elif "gemini" in self.model:
return self._query_gemini(formatted_message, start_time)
else:
raise NotImplementedError(f"Model not supported: {self.model}")
def _truncate_context_if_needed(self, tokenizer):
"""Truncate context if it exceeds limits."""
# Truncate context if it exceeds the context_max_length
if len(tokenizer.encode(self.context, disallowed_special=())) > self.context_max_length:
encoded = tokenizer.encode(self.context, disallowed_special=())
self.context = tokenizer.decode(encoded[-self.context_max_length:])
# Truncate if context exceeds the input_length_limit
if len(tokenizer.encode(self.context, disallowed_special=())) > self.input_length_limit:
encoded = tokenizer.encode(self.context, disallowed_special=())
self.context = tokenizer.decode(encoded[-self.input_length_limit:])
def _format_openai_response(self, response, start_time):
"""Format OpenAI API response into standard output format."""
return self._create_standard_response(
response.choices[0].message.content,
response.usage.prompt_tokens,
response.usage.completion_tokens,
0,
time.time() - start_time
)
def _query_claude(self, message, system_message, start_time):
"""Query Claude model with proper formatting."""
formatted_message = format_chat(message=message, system_message=system_message, include_system=False)
response = self.client.messages.create(
model=self.model,
messages=formatted_message,
temperature=self.temperature,
max_tokens=self.max_tokens
)
return self._create_standard_response(
response.content[0].text,
response.usage.input_tokens,
response.usage.output_tokens,
0,
time.time() - start_time
)
def _query_gemini(self, formatted_message, start_time):
"""Query Gemini model with proper configuration."""
from google.genai import types
response = self.client.models.generate_content(
model=self.model,
contents=formatted_message[1]["content"],
config=types.GenerateContentConfig(
system_instruction=formatted_message[0]["content"],
temperature=self.temperature,
max_output_tokens=self.max_tokens
)
)
return self._create_standard_response(
response.text,
response.usage_metadata.prompt_token_count,
response.usage_metadata.candidates_token_count,
0,
time.time() - start_time
)
def _handle_memory_agent(self, message, memorizing, query_id, context_id):
"""Handle message processing for memory-based agents (Letta, Cognee, Mem0)."""
if self._is_agent_type("letta"):
return self._handle_letta_agent(message, memorizing, query_id, context_id)
elif self._is_agent_type("cognee"):
return self._handle_cognee_agent(message, memorizing, query_id, context_id)
elif self._is_agent_type("mem0"):
return self._handle_mem0_agent(message, memorizing, query_id, context_id)
elif self._is_agent_type("zep"):
return self._handle_zep_agent(message, memorizing, query_id, context_id)
else:
raise NotImplementedError(f"Memory agent type not supported: {self.agent_name}")
def _handle_letta_agent(self, message, memorizing, query_id, context_id):
"""Handle message processing for Letta agents."""
# Format message based on context
if memorizing:
memorize_template = get_template(self.sub_dataset, 'memorize', self.agent_name)
formatted_message = memorize_template.format(context=message, **({'time_stamp': time.strftime("%Y-%m-%d %H:%M:%S")} if '{time_stamp}' in memorize_template else {}))
else:
formatted_message = message
# Handle memory construction time for queries
memory_construction_time = 0 if memorizing else time.time() - self.agent_start_time
# Reload agent for queries
if not memorizing:
if os.path.exists(self.agent_save_to_folder):
self.load_agent()
else:
print(f"\n\nAgent {self.agent_name} not found in {self.agent_save_to_folder}\n\n")
# Process based on Letta mode
response = self._process_letta_message(formatted_message, memorizing, query_id, context_id)
if memorizing:
return "Memorized"
# Create response for queries
tokenizer = self.tokenizer
query_time_len = time.time() - self.agent_start_time - memory_construction_time
output = self._create_standard_response(
response,
len(tokenizer.encode(message, disallowed_special=())),
len(tokenizer.encode(response, disallowed_special=())),
memory_construction_time,
query_time_len
)
self.agent_start_time = time.time() # Reset time
return output
def _process_letta_message(self, formatted_message, memorizing, query_id, context_id):
"""Process message with Letta client based on mode."""
from letta_client import Letta, MessageCreate
try:
if self.letta_mode == 'insert':
if memorizing:
self.client.server.passage_manager.insert_passage(
agent_state=self.agent_state,
agent_id=self.agent_state.id,
text=formatted_message,
actor=self.client.user,
)
# import ipdb; ipdb.set_trace()
return "Memorized"
else:
response = self.client.send_message(
agent_id=self.agent_state.id,
message=formatted_message,
role='user')
## save response.messages to a file / for debugging as JSON
return json.loads(response.messages[-3].tool_call.arguments)['message']
elif self.letta_mode == 'chat':
response = self.client.send_message(
agent_id=self.agent_state.id,
message=formatted_message,
role='user')
if memorizing:
return "Memorized"
else:
## save response.messages to a file / for debugging as JSON
return json.loads(response.messages[-3].tool_call.arguments)['message']
elif self.letta_mode == 'api':
response = self.client.agents.messages.create(
agent_id=self.agent_state.id,
messages=[
MessageCreate(
role="user",
content=formatted_message,
),
],
)
print(f"\n\n\nresponse: {response}\n\n\n")
return response.messages[-1].content
except Exception as e:
print(f"\n\n\nerror: {e}\n\n\n")
return "Error"
def _handle_cognee_agent(self, message, memorizing, query_id, context_id):
"""Handle message processing for Cognee agents."""
import cognee
import asyncio
dataset_name = f'default_dataset_{self.sub_dataset}_context_{context_id}'
if memorizing:
# Add context to Cognee knowledge base
memorize_template = get_template(self.sub_dataset, 'memorize', self.agent_name)
formatted_message = memorize_template.format(context=message, **({'time_stamp': time.strftime("%Y-%m-%d %H:%M:%S")} if '{time_stamp}' in memorize_template else {}))
# Add text to cognee and generate knowledge graph
asyncio.run(cognee.add(formatted_message, dataset_name=dataset_name))
asyncio.run(cognee.cognify(datasets=[dataset_name], chunk_size=self.chunk_size))
self.context += "\n" + formatted_message
self.context = self.context.strip()
return "Memorized"
else:
# Query the knowledge graph
memory_construction_time = time.time() - self.agent_start_time
searched_results = asyncio.run(cognee.search(
query_text=message,
top_k=self.retrieve_num,
datasets=[dataset_name]
))
# Format results
total_results = ("".join([f"{result}\n" for result in searched_results])
if searched_results else "No results found.")
# Return formatted output
tokenizer = self.tokenizer
query_time_len = time.time() - self.agent_start_time - memory_construction_time
output = self._create_standard_response(
total_results,
len(tokenizer.encode(self.context, disallowed_special=())),
len(tokenizer.encode(total_results, disallowed_special=())),
memory_construction_time,
query_time_len
)
self.agent_start_time = time.time() # Reset time
return output
def _handle_mem0_agent(self, message, memorizing, query_id, context_id):
"""Handle message processing for Mem0 agents."""
user_id = f'context_{context_id}_{self.sub_dataset}'
if memorizing:
system_message = get_template(self.sub_dataset, 'system', self.agent_name)
memorize_template = get_template(self.sub_dataset, 'memorize', self.agent_name)
formatted_message = memorize_template.format(context=message, **({'time_stamp': time.strftime("%Y-%m-%d %H:%M:%S")} if '{time_stamp}' in memorize_template else {}))
# Generate Assistant response
# memory_messages = [{"role": "system", "content": system_message}, {"role": "user", "content": formatted_message}]
# response = OpenAI().chat.completions.create(
# model=self.model,
# messages=memory_messages,
# max_tokens=1000,
# )
# memory_messages = [
# {"role": "system", "content": system_message},
# {"role": "user", "content": formatted_message},
# {"role": "assistant", "content": response.choices[0].message.content}
# ]
memory_messages = [
{"role": "system", "content": system_message},
{"role": "user", "content": formatted_message},
{"role": "assistant", "content": "I'll make sure to add the content into the memory."}
]
vector_results = self.memory.add(memory_messages, user_id=user_id)
print(f"\n\n\nvector_results: {vector_results}\n\n\n")
return "Memorized"
else:
# Retrieve relevant memories and generate response
memory_construction_time = time.time() - self.agent_start_time
relevant_memories = self.memory.search(query=message, user_id=user_id, limit=self.retrieve_num)
print(f"\n\n\nrelevant_memories: {relevant_memories}\n\n\n")
memories_str = "\n".join(f"- {entry['memory']}" for entry in relevant_memories["results"])
# Generate assistant response
system_prompt = f"You are a helpful AI. Answer the question based on query and memories.\n{memories_str}\n"
llm_messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": message + "\n\nCurrent Time: " + time.strftime("%Y-%m-%d %H:%M:%S")}
]
response = self.client.chat.completions.create(
model=self.model,
messages=llm_messages,
temperature=self.temperature,
max_tokens=self.max_tokens
)
memory_retrieval_length = len(self.tokenizer.encode(memories_str, disallowed_special=()))
query_time_len = time.time() - self.agent_start_time - memory_construction_time
print(f"\nmemory_length: {memory_retrieval_length}\n")
output = self._create_standard_response(
response.choices[0].message.content,
response.usage.prompt_tokens + memory_retrieval_length,
response.usage.completion_tokens,
memory_construction_time,
query_time_len
)
self.agent_start_time = time.time() # Reset time
return output
# Zep
def _handle_zep_agent(self, message, memorizing, query_id, context_id):
"""Handle Zep processing."""
import inspect
from zep_cloud import Message
from methods.zep import compose_search_context, llm_response, get_retrieval_query, construct_messages
# user id / session id / oai client
user_id = f'user_{context_id}_{self.sub_dataset}'
graph_id = f'graph_{context_id}_{self.sub_dataset}'
thread_id = f'thread_{context_id}_{self.sub_dataset}'
# check the context id for user and session creation
if self.context_id != context_id and memorizing:
# User creation
self.client.user.add(user_id=user_id)
# Thread creation
self.client.thread.create(thread_id=thread_id, user_id=user_id)
# Graph creation
self.client.graph.create(graph_id=graph_id)
self.context_id = context_id
else:
pass
if memorizing:
# graph add
memorize_template = get_template(self.sub_dataset, 'memorize', self.agent_name)
content = memorize_template.format(context=message, **({'time_stamp': time.strftime("%Y-%m-%d %H:%M:%S")} if '{time_stamp}' in memorize_template else {}))
self.client.graph.add(
graph_id=graph_id,
type="text",
data=content[:9998]
)
# # thread add
messages = construct_messages(content, user_id)
self.client.thread.add_messages(thread_id=thread_id, messages=messages)
return "Memorized"
else:
memory_construction_time = time.time() - self.agent_start_time
# graph search
retrieval_query = get_retrieval_query(message)
print(f"\n\n\nretrieval_query: {retrieval_query}\n\n\n")
edges_results = self.client.graph.search(graph_id=graph_id, query=retrieval_query[:399], scope='edges', limit=self.retrieve_num).edges
node_results = self.client.graph.search(graph_id=graph_id, query=retrieval_query[:399], scope='nodes', limit=self.retrieve_num).nodes
episode_results = self.client.graph.search(graph_id=graph_id, query=retrieval_query[:399], scope='episodes', limit=self.retrieve_num).episodes
# print(f"\n\n\nepisode_results: {episode_results}\n\n\n")
# print(f"\n\n\nedges_results: {edges_results}\n\n\n")
# print(f"\n\n\nnode_results: {node_results}\n\n\n")
# thread search / currently we do not use the thread info
memory = self.client.thread.get_user_context(thread_id=thread_id)
context_block = memory.context
# Prompt an LLM with relevant context
retrieved_context = compose_search_context(edges_results, node_results, context_block, episode_results)
import asyncio
response = asyncio.run(llm_response(self.oai_client, retrieved_context, message))
query_time_len = time.time() - self.agent_start_time - memory_construction_time
output = self._create_standard_response(
response,
len(self.tokenizer.encode(retrieved_context, disallowed_special=())),
len(self.tokenizer.encode(response, disallowed_special=())),
memory_construction_time,
query_time_len
)
self.agent_start_time = time.time() # Reset time
# save the context
save_dir = f"./outputs/rag_retrieved/{self.agent_name}/k_{self.retrieve_num}/{self.sub_dataset}/chunksize_{self.chunk_size}/query_{query_id}_context_{context_id}.json"
os.makedirs(os.path.dirname(save_dir), exist_ok=True)
with open(save_dir, "w") as f:
paragraphs = [p for p in retrieved_context.replace("\r\n", "\n").split("\n") if p.strip()]
json.dump({"retrieved_context_paragraphs": paragraphs, "response": response}, f, ensure_ascii=False, indent=2)
return output
def _handle_rag_agent(self, message, memorizing, query_id, context_id):
"""Handle message processing for RAG agents."""
if memorizing:
# Add message to chunks and context
memorize_template = get_template(self.sub_dataset, 'memorize', self.agent_name)
formatted_message = memorize_template.format(context=message, **({'time_stamp': time.strftime("%Y-%m-%d %H:%M:%S")} if '{time_stamp}' in memorize_template else {}))
self.context += "\n" + formatted_message
self.context = self.context.strip()
self.chunks.append(formatted_message)
self.context_len = self.context_len + self.chunk_size
# Truncate context if it exceeds limits
if self.context_len > self.input_length_limit:
self.chunks = self.chunks[1:]
self.context_len = self.context_len - self.chunk_size
return ''
else:
# Handle query processing for different RAG types
return self._process_rag_query(message, query_id, context_id)
def _process_rag_query(self, message, query_id, context_id):
"""Process query for RAG agents with different retrieval strategies."""
# Truncate context if needed
tokenizer = self.tokenizer
if len(tokenizer.encode(self.context, disallowed_special=())) > self.input_length_limit:
encoded = tokenizer.encode(self.context, disallowed_special=())
self.context = tokenizer.decode(encoded[-self.input_length_limit:])
if self.context_len > self.input_length_limit:
self.chunks = self.chunks[1:]
self.context_len = self.context_len - self.chunk_size
# Route to specific RAG implementation and get result
rag_handlers = {
"graph_rag": lambda: self._handle_graph_rag(message, context_id, tokenizer),
"hippo_rag_v2_nv": lambda: self._handle_hippo_rag(message, context_id, tokenizer),
"hippo_rag_v2_openai": lambda: self._handle_hippo_rag(message, context_id, tokenizer),
"rag_bm25": lambda: self._handle_bm25_rag(message, context_id, tokenizer),
"rag_contriever": lambda: self._handle_embedding_rag(message, context_id, tokenizer),
"rag_text_embedding_3_large": lambda: self._handle_embedding_rag(message, context_id, tokenizer),
"rag_text_embedding_3_small": lambda: self._handle_embedding_rag(message, context_id, tokenizer),
"rag_qwen3_embedding_4b": lambda: self._handle_embedding_rag(message, context_id, tokenizer),
"rag_raptor": lambda: self._handle_raptor_rag(message, context_id, tokenizer),
"self_rag": lambda: self._handle_self_rag(message, context_id, tokenizer),
"memo_rag": lambda: self._handle_memorag(message, context_id, tokenizer),
}
# Find matching handler
handler = next((handler for agent_type, handler in rag_handlers.items() if self._is_agent_type(agent_type)), None)
if not handler:
raise NotImplementedError(f"RAG agent type not supported: {self.agent_name}")
output = handler()
# Save the retrieved context as JSON (if the method provides it)
if output.get("retrieval_context"):
save_dir = f"./outputs/rag_retrieved/{self.agent_name}/k_{self.retrieve_num}/{self.sub_dataset}/chunksize_{self.chunk_size}/query_{query_id}_context_{context_id}.json"
os.makedirs(os.path.dirname(save_dir), exist_ok=True)
with open(save_dir, "w") as f:
json.dump(output["retrieval_context"], f)
# drop the retrieval_context
output.pop("retrieval_context")
return output
def _handle_graph_rag(self, message, context_id, tokenizer):
"""Handle Graph RAG processing."""
start_time = time.time()
# Build vectorstore if context changed
if self.context_id != context_id:
docs = [Document(page_content=t, metadata={"source":"Not provided", "chunk":i}) for i,t in enumerate(self.chunks)]
try:
from methods.graph_rag import GraphRAG
self.graph_rag = GraphRAG(temperature=self.temperature, model_name=self.model, retrieve_num=self.retrieve_num, max_tokens=self.max_tokens)
self.graph_rag.process_documents(docs)
memory_construction_time = time.time() - start_time
except Exception as e:
print(f"\n\n\n\nError: {e}\n\n\n\n")
print(f"\n\nGraph RAG build vectorstore finished...\n\n")
else:
memory_construction_time = 0
print(f"\n\nContext {context_id} already processed, skipping Graph RAG build vectorstore...\n\n")
# Process query
try:
response, retrieval_context = self.graph_rag.query(query=message)
except Exception as e:
response = f"{e}"
retrieval_context = "ERROR"
print(f"\n\n\n\nError: {e}\n\n\n\n")
self.context_id = context_id
print(f"\n\n\n\nResponse: {response}\n\n\n\n")
if isinstance(response, str):
response = response
else:
response = response.content
query_time_len = time.time() - start_time - memory_construction_time
return {
"output": response,
"input_len": len(tokenizer.encode(retrieval_context + "\n" + message, disallowed_special=())),
"output_len": len(tokenizer.encode(response, disallowed_special=())),
"memory_construction_time": memory_construction_time,
"query_time_len": query_time_len,
"retrieval_context": retrieval_context,
}
def _handle_hippo_rag(self, message, context_id, tokenizer):
"""Handle HippoRAG processing."""
start_time = time.time()
if self.context_id != context_id:
docs = self.chunks
from methods.hipporag import HippoRAG
if any(agent_name in self.agent_name for agent_name in ["hippo_rag_v2_nv"]):
save_dir = os.path.join(f"./outputs/rag_retrieved/NV-Embed-v2", self.sub_dataset, f'chunksize_{self.chunk_size}', f'context_id_{context_id}')
embedding_model_name = 'nvidia/NV-Embed-v2'
elif any(agent_name in self.agent_name for agent_name in ["hippo_rag_v2_openai"]):
save_dir = os.path.join(f"./outputs/rag_retrieved/OpenAIEmbedding", self.sub_dataset, f'chunksize_{self.chunk_size}', f'context_id_{context_id}')
embedding_model_name = 'text-embedding-ada-002'
self.hipporag = HippoRAG(save_dir=save_dir,
llm_model_name=self.model,
embedding_model_name=embedding_model_name)
self.hipporag.index(docs=docs)
memory_construction_time = time.time() - start_time
print(f"\n\nHippoRAG build vectorstore finished...\n\n")
else:
memory_construction_time = 0
print(f"\n\nContext {context_id} already processed, skipping HippoRAG build vectorstore...\n\n")
# Retrieve and answer
queries = [message]
retrieval_results, top_k_docs = self.hipporag.retrieve(queries=queries, num_to_retrieve=self.retrieve_num)
qa_results = self.hipporag.rag_qa(retrieval_results)
response = qa_results[0][0].answer
retrieval_context = "\n\n".join([f"Passage {i+1}:\n{text}" for i, text in enumerate(top_k_docs)])
query_time_len = time.time() - start_time - memory_construction_time
self.context_id = context_id
return {
"output": response,
"input_len": len(tokenizer.encode(retrieval_context + "\n" + message, disallowed_special=())),
"output_len": len(tokenizer.encode(response, disallowed_special=())),
"memory_construction_time": memory_construction_time,
"query_time_len": query_time_len,
"retrieval_context": retrieval_context,
}
# RAG implementation methods
def _handle_bm25_rag(self, message, context_id, tokenizer):
"""Handle BM25 RAG processing."""
start_time = time.time()
# Extract retrieval query from message
retrieval_query = self._extract_retrieval_query(message)
print(f"\n\n\n\nretrieval_query: {retrieval_query}\n\n\n\n")
# Build vectorstore if context changed
if self.context_id != context_id:
from langchain_community.retrievers import BM25Retriever
docs = [Document(page_content=t, metadata={"source":"Not provided", "chunk":i}) for i,t in enumerate(self.chunks)]
self.bm25_retriever = BM25Retriever.from_documents(docs)
print(f"\n\nBM25 build vectorstore finished...\n\n")
else:
print(f"\n\nContext {context_id} already processed, skipping BM25 build vectorstore...\n\n")
# Retrieve documents
self.bm25_retriever.k = self.retrieve_num
bm25_documents = self.bm25_retriever.get_relevant_documents(retrieval_query)
retrieval_context = [f"{doc.page_content}\n" for doc in bm25_documents]
memory_construction_time = time.time() - start_time
# Answer the query
retrieval_memory_string = "\n".join([f"Memory {i+1}:\n{text}" for i, text in enumerate(retrieval_context)])
# Format the message
ask_llm_message = retrieval_memory_string + "\n" + message
system_message = get_template(self.sub_dataset, 'system', self.agent_name)
format_message = format_chat(message=ask_llm_message, system_message=system_message)
# Generate response
response = self._create_oai_client().chat.completions.create(
model=self.model,
messages=format_message,
temperature=self.temperature,
max_tokens=self.max_tokens if "gpt-4" in self.model else None
)
query_time_len = time.time() - start_time - memory_construction_time
self.context_id = context_id
return {
"output": response.choices[0].message.content,
"input_len": response.usage.prompt_tokens,
"output_len": response.usage.completion_tokens,
"memory_construction_time": memory_construction_time,
"query_time_len": query_time_len,
"retrieval_context": retrieval_context,
}
def _extract_retrieval_query(self, message):
"""Extract retrieval query from message using regex patterns."""
patterns = [
r"Now Answer the Question:\s*(.*)",
r"Here is the conversation:\s*(.*)"
]
for pattern in patterns:
match = re.search(pattern, message, re.DOTALL)
if match:
return ''.join(match.groups())
return message
def _handle_embedding_rag(self, message, context_id, tokenizer):
"""Handle embedding-based RAG processing (Contriever, Text-embedding models)."""
from methods.embedding_retriever import TextRetriever, RAGSystem
# Determine embedding model
if any(agent_name in self.agent_name for agent_name in ["rag_contriever"]):
embedding_model_name = "facebook/contriever"
elif any(agent_name in self.agent_name for agent_name in ["rag_text_embedding_3_large"]):
embedding_model_name = "text-embedding-3-large"
elif any(agent_name in self.agent_name for agent_name in ["rag_text_embedding_3_small"]):
embedding_model_name = "text-embedding-3-small"
elif any(agent_name in self.agent_name for agent_name in ["rag_qwen3_embedding_4b"]):
embedding_model_name = "Qwen/Qwen3-Embedding-4B"
else:
raise NotImplementedError
# Build vectorstore if context changed
if self.context_id != context_id:
self.retriever = TextRetriever(embedding_model_name=embedding_model_name)
self.retriever.build_vectorstore(self.chunks)
print(f"\n\n{embedding_model_name} build vectorstore finished...\n\n")
else:
print(f"\n\nContext {context_id} already processed, skipping {embedding_model_name} build vectorstore...\n\n")
# Retrieve relevant passages and answer the query
rag_system = RAGSystem(self.retriever, self.model, self.temperature, self.max_tokens, use_azure=True, azure_endpoint=os.environ.get("AZURE_OPENAI_ENDPOINT"), azure_api_key=os.environ.get("AZURE_OPENAI_API_KEY"), azure_api_version=os.environ.get("AZURE_OPENAI_API_VERSION"))
system_message = get_template(self.sub_dataset, 'system', self.agent_name)
result = rag_system.answer_query(
query=message,
top_k=self.retrieve_num,
system_message=system_message
)
retrieval_context = result['context_used']
self.context_id = context_id
return {
"output": result["answer"],
"input_len": len(tokenizer.encode(retrieval_context + "\n" + message, disallowed_special=())),
"output_len": len(tokenizer.encode(result["answer"], disallowed_special=())),
"memory_construction_time": result.get("memory_construction_time", result.get("memory_construction_time", 0)),
"query_time_len": result["query_time_len"],
"retrieval_context": retrieval_context,
}
def _handle_raptor_rag(self, message, context_id, tokenizer):
"""Handle RAPTOR RAG processing."""
# Build vectorstore if context changed
if self.context_id != context_id:
texts = self.chunks
from methods.raptor import RAPTORMethod
self.raptor_method = RAPTORMethod(texts, max_levels=3)
print(f"\n\nRaptor build vectorstore finished...\n\n")
else:
print(f"\n\nContext {context_id} already processed, skipping Raptor build vectorstore...\n\n")
# Retrieve relevant passages and answer the query
result = self.raptor_method.run(query=message, k=self.retrieve_num)
response = result['answer']
retrieval_context = result['context_used']
self.context_id = context_id
return {
"output": response,
"input_len": len(tokenizer.encode(retrieval_context + "\n" + message, disallowed_special=())),
"output_len": len(tokenizer.encode(response, disallowed_special=())),
"memory_construction_time": result.get("memory_construction_time", result.get("memory_construction_time", 0)),
"query_time_len": result["query_time_len"],
"retrieval_context": retrieval_context,
}
def _handle_self_rag(self, message, context_id, tokenizer):
"""Handle Self-RAG processing."""
from methods.self_rag import SelfRAG
start_time = time.time()
# Build vectorstore if context changed
if self.context_id != context_id:
docs = [Document(page_content=t, metadata={"source":"Not provided", "chunk":i}) for i,t in enumerate(self.chunks)]
self.self_rag = SelfRAG(documents=docs, temperature=self.temperature, top_k=self.retrieve_num)
print(f"\n\nSelf-RAG build vectorstore finished...\n\n")
else:
print(f"\n\nContext {context_id} already processed, skipping Self-RAG build vectorstore...\n\n")
# Process query
try:
response, retrieval_context_list, memory_construction_time, query_time_len = self.self_rag.run(query=message)