-
Notifications
You must be signed in to change notification settings - Fork 129
Expand file tree
/
Copy pathsession.py
More file actions
1273 lines (1068 loc) · 50.4 KB
/
Copy pathsession.py
File metadata and controls
1273 lines (1068 loc) · 50.4 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
"""Module containing session management classes for AgentCore Memory interactions."""
import logging
import os
import uuid
from datetime import datetime, timezone
from typing import Any, Awaitable, Callable, Dict, List, Optional, Tuple, Union
import boto3
from botocore.config import Config as BotocoreConfig
from botocore.exceptions import ClientError
from bedrock_agentcore._utils.snake_case import accept_snake_case_kwargs
from .constants import BlobMessage, ConversationalMessage, MessageRole, RetrievalConfig
from .models import (
ActorSummary,
Branch,
DictWrapper,
Event,
EventMessage,
EventMetadataFilter,
MemoryRecord,
MetadataValue,
SessionSummary,
)
logger = logging.getLogger(__name__)
class MemorySessionManager:
"""Manages conversational sessions and memory operations for AWS Bedrock AgentCore.
The MemorySessionManager provides a high-level interface for managing conversational AI sessions,
handling both short-term (conversational events) and long-term (semantic memory) storage.
It serves as the primary entry point for data plane operations with AWS Bedrock AgentCore
Memory services.
Key Capabilities:
- **Conversation Management**: Store, retrieve, and organize conversational turns
- **Memory Operations**: Search and manage long-term semantic memory records
- **Branch Support**: Create and manage conversation branches for alternative flows
- **LLM Integration**: Built-in callback pattern for LLM processing with memory context
- **Actor & Session Tracking**: Multi-user, multi-session conversation management
Usage Patterns:
1. **Simple Conversation**: Store user/assistant message pairs
2. **Memory-Enhanced Chat**: Retrieve relevant context before LLM processing
3. **Branched Conversations**: Fork conversations for alternative responses
4. **Multi-Modal**: Handle both text and binary data (images, files, etc.)
Example:
```python
# Initialize manager
manager = MemorySessionManager(memory_id="my-memory-123", region_name="us-east-1")
# Store a conversation turn
manager.add_turns(
actor_id="user-456",
session_id="session-789",
messages=[
ConversationalMessage("Hello!", MessageRole.USER),
ConversationalMessage("Hi there!", MessageRole.ASSISTANT)
]
)
# Search long-term memory and process with LLM
def my_llm(user_input: str, memories: List[Dict]) -> str:
# Your LLM processing logic here
return "Response based on context"
memories, response, event = manager.process_turn_with_llm(
actor_id="user-456",
session_id="session-789",
user_input="What did we discuss?",
llm_callback=my_llm,
retrieval_namespace="support/facts/{sessionId}/"
)
```
Thread Safety:
This class is not thread-safe. Create separate instances for concurrent operations.
AWS Permissions Required:
- bedrock-agentcore:CreateEvent
- bedrock-agentcore:GetEvent
- bedrock-agentcore:ListEvents
- bedrock-agentcore:DeleteEvent
- bedrock-agentcore:RetrieveMemoryRecords
- bedrock-agentcore:ListMemoryRecords
- bedrock-agentcore:GetMemoryRecord
- bedrock-agentcore:DeleteMemoryRecord
- bedrock-agentcore:ListActors
- bedrock-agentcore:ListSessions
- bedrock-agentcore:BatchCreateMemoryRecords
- bedrock-agentcore:BatchDeleteMemoryRecords
- bedrock-agentcore:BatchUpdateMemoryRecords
"""
def __init__(
self,
memory_id: str,
region_name: Optional[str] = None,
boto3_session: Optional[boto3.Session] = None,
boto_client_config: Optional[BotocoreConfig] = None,
):
"""Initialize a MemorySessionManager instance.
Args:
memory_id: The memory identifier for this session manager.
region_name: AWS region for the bedrock-agentcore client. If not provided,
will use the region from boto3_session or default session.
boto3_session: Optional boto3 Session to use. If provided and region_name
parameter is also specified, validation will ensure they match.
boto_client_config: Optional boto3 client configuration. If provided, will be
merged with default configuration including user agent.
Raises:
ValueError: If region_name parameter conflicts with boto3_session region.
"""
# Initialize core attributes
self._memory_id = memory_id
# Setup session and validate region consistency
self.region_name = self._validate_and_resolve_region(region_name, boto3_session)
session = boto3_session if boto3_session else boto3.Session()
# Configure and create boto3 client
client_config = self._build_client_config(boto_client_config)
self._data_plane_client = session.client(
"bedrock-agentcore", region_name=self.region_name, config=client_config
)
# Configure timestamp serialization to use float representation
self._configure_timestamp_serialization()
# Define allowed data plane methods
self._ALLOWED_DATA_PLANE_METHODS = {
"retrieve_memory_records",
"get_memory_record",
"delete_memory_record",
"list_memory_records",
"create_event",
"get_event",
"delete_event",
"list_events",
"batch_create_memory_records",
"batch_delete_memory_records",
"batch_update_memory_records",
}
def _validate_and_resolve_region(self, region_name: Optional[str], session: Optional[boto3.Session]) -> str:
"""Validate region consistency and resolve the final region to use.
Args:
region_name: Explicitly provided region name
session: Optional Boto3 session instance
Returns:
The resolved region name to use
Raises:
ValueError: If region_name conflicts with session region
"""
session_region = session.region_name if session else None
# Validate region consistency if both are provided
if region_name and session and session_region and (region_name != session_region):
raise ValueError(
f"Region mismatch: provided region_name '{region_name}' does not match "
f"boto3_session region '{session_region}'. Please ensure both "
f"parameters specify the same region or omit the region_name parameter "
f"to use the session's region."
)
return (
region_name or session_region or os.environ.get("AWS_REGION") or boto3.Session().region_name or "us-west-2"
)
def _build_client_config(self, boto_client_config: Optional[BotocoreConfig]) -> BotocoreConfig:
"""Build the final boto3 client configuration with SDK user agent.
Args:
boto_client_config: Optional user-provided client configuration
Returns:
Final client configuration with SDK user agent
"""
sdk_user_agent = "bedrock-agentcore-sdk"
if boto_client_config:
existing_user_agent = getattr(boto_client_config, "user_agent_extra", None)
if existing_user_agent:
new_user_agent = f"{existing_user_agent} {sdk_user_agent}"
else:
new_user_agent = sdk_user_agent
return boto_client_config.merge(BotocoreConfig(user_agent_extra=new_user_agent))
else:
return BotocoreConfig(user_agent_extra=sdk_user_agent)
def _configure_timestamp_serialization(self) -> None:
"""Configure the boto3 client to serialize timestamps as float values.
This method overrides the default timestamp serialization to convert datetime objects
to float timestamps (seconds since Unix epoch) which preserves millisecond precision
when sending datetime objects to the AgentCore Memory service.
"""
original_serialize_timestamp = self._data_plane_client._serializer._serializer._serialize_type_timestamp
def serialize_timestamp_as_float(serialized, value, shape, name):
if isinstance(value, datetime):
serialized[name] = value.timestamp() # Convert to float (seconds since epoch with fractional seconds)
else:
original_serialize_timestamp(serialized, value, shape, name)
self._data_plane_client._serializer._serializer._serialize_type_timestamp = serialize_timestamp_as_float
def __getattr__(self, name: str):
"""Dynamically forward method calls to the appropriate boto3 client.
This method enables access to all data_plane boto3 client methods without explicitly
defining them. Methods are looked up in the following order:
_data_plane_client (bedrock-agentcore) - for data plane operations
Args:
name: The method name being accessed
Returns:
A callable method from the boto3 client
Raises:
AttributeError: If the method doesn't exist on _data_plane_client
Example:
# Access any boto3 method directly
manager = MemorySessionManager(region_name="us-east-1")
# These calls are forwarded to the appropriate boto3 functions
memory_records = manager.retrieve_memory_records()
events = manager.list_events(...)
"""
if name in self._ALLOWED_DATA_PLANE_METHODS and hasattr(self._data_plane_client, name):
method = getattr(self._data_plane_client, name)
logger.debug("Forwarding method '%s' to _data_plane_client", name)
return accept_snake_case_kwargs(method)
# Method not found on client
raise AttributeError(
f"'{self.__class__.__name__}' object has no attribute '{name}'. "
f"Method not found on _data_plane_client. "
f"Available methods can be found in the boto3 documentation for "
f"'bedrock-agentcore' services."
)
def process_turn_with_llm(
self,
actor_id: str,
session_id: str,
user_input: str,
llm_callback: Callable[[str, List[Dict[str, Any]]], str],
retrieval_config: Optional[Dict[str, RetrievalConfig]],
metadata: Optional[Dict[str, MetadataValue]] = None,
event_timestamp: Optional[datetime] = None,
) -> Tuple[List[Dict[str, Any]], str, Dict[str, Any]]:
r"""Complete conversation turn with LLM callback integration.
This method combines memory retrieval, LLM invocation, and response storage
in a single call using a callback pattern.
Args:
actor_id: Actor identifier (e.g., "user-123")
session_id: Session identifier
user_input: The user's message
llm_callback: Function that takes (user_input, memories) and returns agent_response
The callback receives the user input and retrieved memories,
and should return the agent's response string
retrieval_config: Optional dictionary mapping namespaces to RetrievalConfig objects.
Each namespace can contain template variables like {actorId}, {sessionId},
{memoryStrategyId} that will be resolved at runtime.
metadata: Optional custom key-value metadata to attach to an event.
event_timestamp: Optional timestamp for the event
Returns:
Tuple of (retrieved_memories, agent_response, created_event)
Example:
from bedrock_agentcore.memory.constants import RetrievalConfig
def my_llm(user_input: str, memories: List[Dict]) -> str:
# Format context from memories
context = "\\n".join([m.get('content', {}).get('text', '') for m in memories])
# Call your LLM (Bedrock, OpenAI, etc.)
response = bedrock.invoke_model(
messages=[
{"role": "system", "content": f"Context: {context}"},
{"role": "user", "content": user_input}
]
)
return response['content']
retrieval_config = {
"support/facts/{sessionId}/": RetrievalConfig(top_k=5, relevance_score=0.3),
"user/preferences/{actorId}/": RetrievalConfig(top_k=3, relevance_score=0.5)
}
memories, response, event = manager.process_turn_with_llm(
actor_id="user-123",
session_id="session-456",
user_input="What did we discuss yesterday?",
llm_callback=my_llm,
retrieval_config=retrieval_config
)
"""
# Step 1: Retrieve relevant memories
retrieved_memories = self._retrieve_memories_for_llm(actor_id, session_id, user_input, retrieval_config)
# Step 2: Invoke LLM callback
try:
agent_response = llm_callback(user_input, retrieved_memories)
if not isinstance(agent_response, str):
raise ValueError("LLM callback must return a string response")
logger.info("LLM callback generated response")
except Exception as e:
logger.error("LLM callback failed: %s", e)
raise
# Step 3: Save the conversation turn
event = self._save_conversation_turn(
actor_id, session_id, user_input, agent_response, metadata, event_timestamp
)
return retrieved_memories, agent_response, event
async def process_turn_with_llm_async(
self,
actor_id: str,
session_id: str,
user_input: str,
llm_callback: Callable[[str, List[Dict[str, Any]]], Awaitable[str]],
retrieval_config: Optional[Dict[str, RetrievalConfig]],
metadata: Optional[Dict[str, MetadataValue]] = None,
event_timestamp: Optional[datetime] = None,
) -> Tuple[List[Dict[str, Any]], str, Dict[str, Any]]:
r"""Complete conversation turn with async LLM callback integration.
This method combines memory retrieval, LLM invocation, and response storage
in a single call using an async callback pattern.
Args:
actor_id: Actor identifier (e.g., "user-123")
session_id: Session identifier
user_input: The user's message
llm_callback: Async function that takes (user_input, memories) and returns agent_response.
The callback receives the user input and retrieved memories,
and should return the agent's response string
retrieval_config: Optional dictionary mapping namespaces to RetrievalConfig objects.
Each namespace can contain template variables like {actorId}, {sessionId},
{memoryStrategyId} that will be resolved at runtime.
metadata: Optional custom key-value metadata to attach to an event.
event_timestamp: Optional timestamp for the event
Returns:
Tuple of (retrieved_memories, agent_response, created_event)
"""
# Step 1: Retrieve relevant memories
retrieved_memories = self._retrieve_memories_for_llm(actor_id, session_id, user_input, retrieval_config)
# Step 2: Invoke async LLM callback
try:
agent_response = await llm_callback(user_input, retrieved_memories)
if not isinstance(agent_response, str):
raise ValueError("LLM callback must return a string response")
logger.info("LLM callback generated response")
except Exception as e:
logger.error("LLM callback failed: %s", e)
raise
# Step 3: Save the conversation turn
event = self._save_conversation_turn(
actor_id, session_id, user_input, agent_response, metadata, event_timestamp
)
return retrieved_memories, agent_response, event
def _retrieve_memories_for_llm(
self,
actor_id: str,
session_id: str,
user_input: str,
retrieval_config: Optional[Dict[str, RetrievalConfig]],
) -> List[Dict[str, Any]]:
"""Helper method to retrieve memories for LLM context."""
retrieved_memories = []
if retrieval_config:
for namespace, config in retrieval_config.items():
resolved_namespace = namespace.format(
actorId=actor_id,
sessionId=session_id,
strategyId=config.strategy_id or "",
)
search_query = f"{config.retrieval_query} {user_input}" if config.retrieval_query else user_input
memory_records = self.search_long_term_memories(
query=search_query, namespace_prefix=resolved_namespace, top_k=config.top_k
)
# Filter memory records with a relevance score which is lower than config.relevance_score
if config.relevance_score:
memory_records = [
record
for record in memory_records
if record.get("relevanceScore", config.relevance_score) >= config.relevance_score
]
retrieved_memories.extend(memory_records)
logger.info("Retrieved %d memories for LLM context", len(retrieved_memories))
return retrieved_memories
def _save_conversation_turn(
self,
actor_id: str,
session_id: str,
user_input: str,
agent_response: str,
metadata: Optional[Dict[str, MetadataValue]],
event_timestamp: Optional[datetime],
) -> Dict[str, Any]:
"""Helper method to save conversation turn."""
event = self.add_turns(
actor_id=actor_id,
session_id=session_id,
messages=[
ConversationalMessage(user_input, MessageRole.USER),
ConversationalMessage(agent_response, MessageRole.ASSISTANT),
],
metadata=metadata,
event_timestamp=event_timestamp,
)
logger.info("Completed full conversation turn with LLM")
return event
def add_turns(
self,
actor_id: str,
session_id: str,
messages: List[Union[ConversationalMessage, BlobMessage]],
branch: Optional[Dict[str, str]] = None,
metadata: Optional[Dict[str, MetadataValue]] = None,
event_timestamp: Optional[datetime] = None,
) -> Event:
"""Adds conversational turns or blob objects to short-term memory.
Maps to: bedrock-agentcore.create_event
Args:
actor_id: Actor identifier
session_id: Session identifier
messages: List of either:
- ConversationalMessage objects for conversational messages
- BlobMessage objects for blob data
branch: Optional branch info
metadata: Optional custom key-value metadata to attach to an event.
event_timestamp: Optional timestamp for the event
Returns:
Created event
Example:
```
manager.add_turns(
actor_id="user-123",
session_id="session-456",
messages=[
ConversationalMessage("Hello", USER),
BlobMessage({"file_data": "base64_content"}),
ConversationalMessage("How can I help?", ASSISTANT)
],
metadata=[
{
'location': {
'stringValue': 'NYC'
}
}
]
)
```
"""
logger.info(" -> Storing %d messages in short-term memory...", len(messages))
if not messages:
raise ValueError("At least one message is required")
payload = []
for message in messages:
if isinstance(message, ConversationalMessage):
# Handle ConversationalMessage data class
payload.append({"conversational": {"content": {"text": message.text}, "role": message.role.value}})
elif isinstance(message, BlobMessage):
# Handle BlobMessage data class
payload.append({"blob": message.data})
else:
raise ValueError("Invalid message format. Must be ConversationalMessage or BlobMessage")
# Use provided timestamp or current time
if event_timestamp is None:
event_timestamp = datetime.now(timezone.utc)
params = {
"memoryId": self._memory_id,
"actorId": actor_id,
"sessionId": session_id,
"eventTimestamp": event_timestamp,
"payload": payload,
}
if branch:
params["branch"] = branch
if metadata:
params["metadata"] = metadata
try:
response = self._data_plane_client.create_event(**params)
logger.info(" ✅ Turn stored successfully with Event ID: %s", response.get("eventId"))
return Event(response["event"])
except ClientError as e:
logger.error(" ❌ Error storing turn: %s", e)
raise
def fork_conversation(
self,
actor_id: str,
session_id: str,
root_event_id: str,
branch_name: str,
messages: List[Union[ConversationalMessage, BlobMessage]],
metadata: Optional[Dict[str, MetadataValue]] = None,
event_timestamp: Optional[datetime] = None,
) -> Dict[str, Any]:
"""Fork a conversation from a specific event to create a new branch."""
try:
branch = {"rootEventId": root_event_id, "name": branch_name}
event = self.add_turns(
actor_id=actor_id,
session_id=session_id,
messages=messages,
event_timestamp=event_timestamp,
branch=branch,
metadata=metadata,
)
logger.info("Created branch '%s' from event %s", branch_name, root_event_id)
return event
except ClientError as e:
logger.error("Failed to fork conversation: %s", e)
raise
def list_events(
self,
actor_id: str,
session_id: str,
branch_name: Optional[str] = None,
include_parent_branches: bool = False,
eventMetadata: Optional[List[EventMetadataFilter]] = None,
max_results: int = 100,
include_payload: bool = True,
) -> List[Event]:
"""List all events in a session with pagination support.
This method provides direct access to the raw events API, allowing developers
to retrieve all events without the turn grouping logic of get_last_k_turns.
Args:
actor_id: Actor identifier
session_id: Session identifier
branch_name: Optional branch name to filter events (None for all branches)
include_parent_branches: Whether to include parent branch events (only applies with branch_name)
eventMetadata: Optional list of event metadata filters to apply
max_results: Maximum number of events to return
include_payload: Whether to include event payloads in response
Returns:
List of event dictionaries in chronological order
Example:
# Get all events
events = client.list_events(actor_id, session_id)
# Get only main branch events
main_events = client.list_events(actor_id, session_id, branch_name="main")
# Get events from a specific branch
branch_events = client.list_events(actor_id, session_id, branch_name="test-branch")
#### Get events with event metadata filter
```
filtered_events_with_metadata = client.list_events(
actor_id=actor_id,
session_id=session_id,
eventMetadata=[
{
'left': {
'metadataKey': 'location'
},
'operator': 'EQUALS_TO',
'right': {
'metadataValue': {
'stringValue': 'NYC'
}
}
}
]
)
```
#### Get events with event metadata filter + specific branch filter
```
branch_with_metadata_filtered_events = client.list_events(
actor_id=actor_id,
session_id=session_id,
branch_name="test-branch",
eventMetadata=[
{
'left': {
'metadataKey': 'location'
},
'operator': 'EQUALS_TO',
'right': {
'metadataValue': {
'stringValue': 'NYC'
}
}
}
]
)
```
"""
try:
all_events: List[Event] = []
next_token = None
max_iterations = 1000 # Safety limit to prevent infinite loops
iteration_count = 0
while len(all_events) < max_results and iteration_count < max_iterations:
iteration_count += 1
params = {
"memoryId": self._memory_id,
"actorId": actor_id,
"sessionId": session_id,
"maxResults": min(100, max_results - len(all_events)),
"includePayloads": include_payload,
}
if next_token:
params["nextToken"] = next_token
# Initialize the filterMap
filterMap = {}
# Add branch filter if specified (but not for "main")
if branch_name and branch_name != "main":
filterMap["branch"] = {"name": branch_name, "includeParentBranches": include_parent_branches}
# Add eventMetadata filter if specified
if eventMetadata:
filterMap["eventMetadata"] = eventMetadata
if filterMap:
params["filter"] = filterMap
response = self._data_plane_client.list_events(**params)
events = response.get("events", [])
# If no events returned, break to prevent infinite loop
if not events:
logger.debug("No more events returned, ending pagination")
break
all_events.extend([Event(event) for event in events])
next_token = response.get("nextToken")
if not next_token or len(all_events) >= max_results:
break
if iteration_count >= max_iterations:
logger.warning("Reached maximum iteration limit (%d) in list_events pagination", max_iterations)
logger.info("Retrieved total of %d events", len(all_events))
return all_events[:max_results]
except ClientError as e:
logger.error("Failed to list events: %s", e)
raise
def list_branches(self, actor_id: str, session_id: str) -> List[Branch]:
"""List all branches in a session.
This method handles pagination automatically and provides a structured view
of all conversation branches, which would require complex pagination and
grouping logic if done with raw boto3 calls.
Returns:
List of branch information including name and root event
"""
try:
# Get all events - need to handle pagination for complete list
all_events = []
next_token = None
max_iterations = 1000 # Safety limit to prevent infinite loops
iteration_count = 0
while iteration_count < max_iterations:
iteration_count += 1
params = {"memoryId": self._memory_id, "actorId": actor_id, "sessionId": session_id, "maxResults": 100}
if next_token:
params["nextToken"] = next_token
response = self._data_plane_client.list_events(**params)
events = response.get("events", [])
# If no events returned, break to prevent infinite loop
if not events:
logger.debug("No more events returned, ending pagination in list_branches")
break
all_events.extend(events)
next_token = response.get("nextToken")
if not next_token:
break
if iteration_count >= max_iterations:
logger.warning("Reached maximum iteration limit (%d) in list_branches pagination", max_iterations)
branches = {}
main_branch_events = []
for event in all_events:
branch_info = event.get("branch")
if branch_info:
branch_name = branch_info["name"]
if branch_name not in branches:
branches[branch_name] = {
"name": branch_name,
"rootEventId": branch_info.get("rootEventId"),
"firstEventId": event["eventId"],
"eventCount": 1,
"created": event["eventTimestamp"],
}
else:
branches[branch_name]["eventCount"] += 1
else:
main_branch_events.append(event)
# Build result list
result: List[Branch] = []
# Only add main branch if there are actual events
if main_branch_events:
result.append(
{
"name": "main",
"rootEventId": None,
"firstEventId": main_branch_events[0]["eventId"],
"eventCount": len(main_branch_events),
"created": main_branch_events[0]["eventTimestamp"],
}
)
# Add other branches
result.extend(list(branches.values()))
logger.info("Found %d branches in session %s", len(result), session_id)
return [Branch(branch) for branch in result]
except ClientError as e:
logger.error("Failed to list branches: %s", e)
raise
def get_last_k_turns(
self,
actor_id: str,
session_id: str,
k: int = 5,
branch_name: Optional[str] = None,
include_parent_branches: bool = False,
max_results: Optional[int] = None,
) -> List[List[EventMessage]]:
"""Get the last K conversation turns.
A "turn" typically consists of a user message followed by assistant response(s).
This method groups messages into logical turns for easier processing.
If max_results is specified, fetches up to that many events and finds turns within them
(backward compatible behavior).
If max_results is None, automatically paginates until k turns are found.
Returns:
List of turns, where each turn is a list of message dictionaries
"""
base_params = {
"memoryId": self._memory_id,
"actorId": actor_id,
"sessionId": session_id,
}
if branch_name and branch_name != "main":
base_params["filter"] = {"branch": {"name": branch_name, "includeParentBranches": include_parent_branches}}
try:
turns: List[List[EventMessage]] = []
current_turn: List[EventMessage] = []
next_token = None
total_fetched = 0
while len(turns) < k:
if max_results is not None:
remaining = max_results - total_fetched
if remaining <= 0:
break
batch_size = min(100, remaining)
else:
batch_size = 100
params = {**base_params, "maxResults": batch_size, "includePayloads": True}
if next_token:
params["nextToken"] = next_token
response = self._data_plane_client.list_events(**params)
events = response.get("events", [])
if not events:
break
total_fetched += len(events)
for event in events:
if len(turns) >= k:
break
for payload_item in event.get("payload", []):
if "conversational" in payload_item:
role = payload_item["conversational"].get("role")
if role == MessageRole.USER.value and current_turn:
turns.append(current_turn)
current_turn = []
current_turn.append(EventMessage(payload_item["conversational"]))
next_token = response.get("nextToken")
if not next_token:
break
if current_turn and len(turns) < k:
turns.append(current_turn)
return turns[:k]
except ClientError as e:
logger.error("Failed to get last K turns: %s", e)
raise
def get_event(self, actor_id: str, session_id: str, event_id: str) -> Event:
"""Retrieves a specific event from short-term memory by its ID.
Maps to: bedrock-agentcore.get_event.
"""
logger.info(" -> Retrieving event by ID: %s...", event_id)
try:
response = self._data_plane_client.get_event(
memoryId=self._memory_id, actorId=actor_id, sessionId=session_id, eventId=event_id
)
logger.info(" ✅ Event retrieved.")
return Event(response.get("event", {}))
except ClientError as e:
logger.error(" ❌ Error retrieving event: %s", e)
raise
def delete_event(self, actor_id: str, session_id: str, event_id: str):
"""Deletes a specific event from short-term memory by its ID.
Maps to: bedrock-agentcore.delete_event.
"""
logger.info(" -> Deleting event by ID: %s...", event_id)
try:
self._data_plane_client.delete_event(
memoryId=self._memory_id, actorId=actor_id, sessionId=session_id, eventId=event_id
)
logger.info(" ✅ Event deleted successfully.")
except ClientError as e:
logger.error(" ❌ Error deleting event: %s", e)
raise
def search_long_term_memories(
self,
query: str,
namespace_prefix: str,
top_k: int = 3,
strategy_id: str = None,
max_results: int = 20,
) -> List[MemoryRecord]:
"""Performs a semantic search against the long-term memory for this actor.
Maps to: bedrock-agentcore.retrieve_memory_records.
"""
logger.info(" -> Querying long-term memory in namespace '%s' with query: '%s'...", namespace_prefix, query)
search_criteria = {"searchQuery": query, "topK": top_k}
if strategy_id:
search_criteria["memoryStrategyId"] = strategy_id
namespace = namespace_prefix
params = {
"memoryId": self._memory_id,
"searchCriteria": search_criteria,
"namespacePath": namespace,
"maxResults": max_results,
}
try:
response = self._data_plane_client.retrieve_memory_records(**params)
records = response.get("memoryRecordSummaries", [])
logger.info(" ✅ Found %d relevant long-term records.", len(records))
return [MemoryRecord(record) for record in records]
except ClientError as e:
logger.info(" ❌ Error querying long-term memory: %s", e)
raise
def list_long_term_memory_records(
self, namespace_prefix: str, strategy_id: Optional[str] = None, max_results: int = 10
) -> List[MemoryRecord]:
"""Lists all long-term memory records for this actor without a semantic query.
Maps to: bedrock-agentcore.list_memory_records.
"""
logger.info(" -> Listing all long-term records in namespace '%s'...", namespace_prefix)
try:
paginator = self._data_plane_client.get_paginator("list_memory_records")
params = {
"memoryId": self._memory_id,
"namespacePath": namespace_prefix,
}
if strategy_id:
params["memoryStrategyId"] = strategy_id
pages = paginator.paginate(**params)
all_records: List[MemoryRecord] = []
for page in pages:
memory_records = page.get("memoryRecords", [])
# Also check for memoryRecordSummaries (which is what the API actually returns)
if not memory_records:
memory_records = page.get("memoryRecordSummaries", [])
all_records.extend([MemoryRecord(record) for record in memory_records])
# Stop if we've reached max_results
if len(all_records) >= max_results:
break
logger.info(" ✅ Found a total of %d long-term records.", len(all_records))
return all_records[:max_results]
except ClientError as e:
logger.error(" ❌ Error listing long-term records: %s", e)
raise
def list_actors(self) -> List[ActorSummary]:
"""Lists all actors who have events in a specific memory.
Maps to: bedrock-agentcore.list_actors.
"""
logger.info("👥 Listing all actors for memory %s...", self._memory_id)
try:
paginator = self._data_plane_client.get_paginator("list_actors")
pages = paginator.paginate(memoryId=self._memory_id)
all_actors = []
for page in pages:
actor_summaries = page.get("actorSummaries", [])
all_actors.extend([ActorSummary(actor) for actor in actor_summaries])
logger.info(" ✅ Found %d actors.", len(all_actors))
return all_actors
except ClientError as e:
logger.error(" ❌ Error listing actors: %s", e)
raise
def get_memory_record(self, record_id: str) -> MemoryRecord:
"""Retrieves a specific long-term memory record by its ID.
Maps to: bedrock-agentcore.get_memory_record.
"""
logger.info("📄 Retrieving long-term record by ID: %s from memory %s...", record_id, self._memory_id)
try:
response = self._data_plane_client.get_memory_record(memoryId=self._memory_id, memoryRecordId=record_id)
logger.info(" ✅ Record retrieved.")
memory_record = response.get("memoryRecord", {})
return MemoryRecord(memory_record)