-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathclient.py
More file actions
2040 lines (1699 loc) · 79.9 KB
/
client.py
File metadata and controls
2040 lines (1699 loc) · 79.9 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
"""AgentCore Memory SDK - High-level client for memory operations.
This SDK handles the asymmetric API where:
- Input parameters use old field names (memoryStrategies, memoryStrategyId, etc.)
- Output responses use new field names (strategies, strategyId, etc.)
The SDK automatically normalizes responses to provide both field names for
backward compatibility.
"""
import copy
import logging
import time
import uuid
import warnings
from datetime import datetime
from typing import Any, Callable, Dict, List, Optional, Tuple
import boto3
from botocore.config import Config
from botocore.exceptions import ClientError
from bedrock_agentcore._utils.snake_case import accept_snake_case_kwargs
from bedrock_agentcore._utils.user_agent import build_user_agent_suffix
from .constants import (
CUSTOM_CONSOLIDATION_WRAPPER_KEYS,
CUSTOM_EXTRACTION_WRAPPER_KEYS,
CUSTOM_REFLECTION_WRAPPER_KEYS,
DEFAULT_NAMESPACES,
EXTRACTION_WRAPPER_KEYS,
MemoryStatus,
MemoryStrategyTypeEnum,
MessageRole,
OverrideType,
Role,
StrategyType,
)
from .models.filters import EventMetadataFilter, MetadataValue
logger = logging.getLogger(__name__)
class MemoryClient:
"""High-level Bedrock AgentCore Memory client with essential operations."""
# AgentCore Memory data plane methods
_ALLOWED_GMDP_METHODS = {
"retrieve_memory_records",
"get_memory_record",
"delete_memory_record",
"list_memory_records",
"create_event",
"get_event",
"delete_event",
"list_events",
}
# AgentCore Memory control plane methods
_ALLOWED_GMCP_METHODS = {
"create_memory",
"get_memory",
"list_memories",
"update_memory",
"delete_memory",
"list_memory_strategies",
}
def __init__(
self,
region_name: Optional[str] = None,
integration_source: Optional[str] = None,
boto3_session: Optional[boto3.Session] = None,
):
"""Initialize the Memory client.
Args:
region_name: AWS region name. If not provided, uses the session's region or "us-west-2".
integration_source: Optional integration source for user-agent telemetry.
boto3_session: Optional boto3 Session to use. If not provided, a default session
is created. Useful for named profiles or custom credentials.
"""
session = boto3_session if boto3_session else boto3.Session()
self.region_name = region_name or session.region_name or "us-west-2"
self.integration_source = integration_source
# Build config with user-agent for telemetry
user_agent_extra = build_user_agent_suffix(integration_source)
client_config = Config(user_agent_extra=user_agent_extra)
self.gmcp_client = session.client(
"bedrock-agentcore-control", region_name=self.region_name, config=client_config
)
self.gmdp_client = session.client("bedrock-agentcore", region_name=self.region_name, config=client_config)
logger.info(
"Initialized MemoryClient for control plane: %s, data plane: %s",
self.gmcp_client.meta.region_name,
self.gmdp_client.meta.region_name,
)
def __getattr__(self, name: str) -> Any:
"""Dynamically forward method calls to the appropriate boto3 client.
This method enables access to all boto3 client methods without explicitly
defining them. Methods are looked up in the following order:
1. gmdp_client (bedrock-agentcore) - for data plane operations
2. gmcp_client (bedrock-agentcore-control) - for control plane operations
Args:
name: The method name being accessed
Returns:
A callable method from the appropriate boto3 client
Raises:
AttributeError: If the method doesn't exist on either client
Example:
# Access any boto3 method directly
client = MemoryClient()
# These calls are forwarded to the appropriate boto3 client
response = client.list_memory_records(memoryId="mem-123", namespace="test/")
metadata = client.get_memory_metadata(memoryId="mem-123")
"""
if name in self._ALLOWED_GMDP_METHODS and hasattr(self.gmdp_client, name):
method = getattr(self.gmdp_client, name)
logger.debug("Forwarding method '%s' to gmdp_client", name)
return accept_snake_case_kwargs(method)
if name in self._ALLOWED_GMCP_METHODS and hasattr(self.gmcp_client, name):
method = getattr(self.gmcp_client, name)
logger.debug("Forwarding method '%s' to gmcp_client", name)
return accept_snake_case_kwargs(method)
# Method not found on either client
raise AttributeError(
f"'{self.__class__.__name__}' object has no attribute '{name}'. "
f"Method not found on gmdp_client or gmcp_client. "
f"Available methods can be found in the boto3 documentation for "
f"'bedrock-agentcore' and 'bedrock-agentcore-control' services."
)
def create_memory(
self,
name: str,
strategies: Optional[List[Dict[str, Any]]] = None,
description: Optional[str] = None,
event_expiry_days: int = 90,
memory_execution_role_arn: Optional[str] = None,
stream_delivery_resources: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
"""Create a memory with simplified configuration."""
if strategies is None:
strategies = []
try:
processed_strategies = self._add_default_namespaces(strategies)
params = {
"name": name,
"eventExpiryDuration": event_expiry_days,
"memoryStrategies": processed_strategies, # Using old field name for input
"clientToken": str(uuid.uuid4()),
}
if description is not None:
params["description"] = description
if memory_execution_role_arn is not None:
params["memoryExecutionRoleArn"] = memory_execution_role_arn
if stream_delivery_resources is not None:
params["streamDeliveryResources"] = stream_delivery_resources
response = self.gmcp_client.create_memory(**params)
memory = response["memory"]
# Normalize response to handle new field names
memory = self._normalize_memory_response(memory)
logger.info("Created memory: %s", memory["memoryId"])
return memory
except ClientError as e:
logger.error("Failed to create memory: %s", e)
raise
def create_or_get_memory(
self,
name: str,
strategies: Optional[List[Dict[str, Any]]] = None,
description: Optional[str] = None,
event_expiry_days: int = 90,
memory_execution_role_arn: Optional[str] = None,
stream_delivery_resources: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
"""Create a memory resource or fetch the existing memory details if it already exists.
Returns:
Memory object, either newly created or existing
"""
try:
memory = self.create_memory_and_wait(
name=name,
strategies=strategies, # type: ignore[arg-type]
description=description,
event_expiry_days=event_expiry_days,
memory_execution_role_arn=memory_execution_role_arn,
stream_delivery_resources=stream_delivery_resources,
)
return memory
except ClientError as e:
if e.response["Error"]["Code"] == "ValidationException" and "already exists" in str(e):
memories = self.list_memories()
memory = next((m for m in memories if m["id"].startswith(name)), None) # type: ignore[arg-type]
logger.info("Memory already exists. Using existing memory ID: %s", memory["id"])
return memory
else:
logger.error("ClientError: Failed to create or get memory: %s", e)
raise
except Exception:
raise
def create_memory_and_wait(
self,
name: str,
strategies: List[Dict[str, Any]],
description: Optional[str] = None,
event_expiry_days: int = 90,
memory_execution_role_arn: Optional[str] = None,
stream_delivery_resources: Optional[Dict[str, Any]] = None,
max_wait: int = 300,
poll_interval: int = 10,
) -> Dict[str, Any]:
"""Create a memory and wait for it to become ACTIVE.
This method creates a memory and polls until it reaches ACTIVE status,
providing a convenient way to ensure the memory is ready for use.
Args:
name: Name for the memory resource
strategies: List of strategy configurations
description: Optional description
event_expiry_days: How long to retain events (default: 90 days)
memory_execution_role_arn: IAM role ARN for memory execution
stream_delivery_resources: Optional delivery configuration for streaming memory records
max_wait: Maximum seconds to wait (default: 300)
poll_interval: Seconds between status checks (default: 10)
Returns:
Created memory object in ACTIVE status
Raises:
TimeoutError: If memory doesn't become ACTIVE within max_wait
RuntimeError: If memory creation fails
"""
# Create the memory
memory = self.create_memory(
name=name,
strategies=strategies,
description=description,
event_expiry_days=event_expiry_days,
memory_execution_role_arn=memory_execution_role_arn,
stream_delivery_resources=stream_delivery_resources,
)
memory_id = memory.get("memoryId", memory.get("id")) # Handle both field names
if memory_id is None:
memory_id = ""
logger.info("Created memory %s, waiting for ACTIVE status...", memory_id)
start_time = time.time()
while time.time() - start_time < max_wait:
elapsed = int(time.time() - start_time)
try:
status = self.get_memory_status(memory_id)
if status == MemoryStatus.ACTIVE.value:
logger.info("Memory %s is now ACTIVE (took %d seconds)", memory_id, elapsed)
# Get fresh memory details
response = self.gmcp_client.get_memory(memoryId=memory_id) # Input uses old field name
memory = self._normalize_memory_response(response["memory"])
return memory
elif status == MemoryStatus.FAILED.value:
# Get failure reason if available
response = self.gmcp_client.get_memory(memoryId=memory_id) # Input uses old field name
failure_reason = response["memory"].get("failureReason", "Unknown")
raise RuntimeError("Memory creation failed: %s" % failure_reason)
else:
logger.debug("Memory status: %s (%d seconds elapsed)", status, elapsed)
except ClientError as e:
logger.error("Error checking memory status: %s", e)
raise
time.sleep(poll_interval)
raise TimeoutError("Memory %s did not become ACTIVE within %d seconds" % (memory_id, max_wait))
def retrieve_memories(
self, memory_id: str, namespace: str, query: str, actor_id: Optional[str] = None, top_k: int = 3
) -> List[Dict[str, Any]]:
"""Retrieve relevant memories from a namespace.
Note: Wildcards (*) are NOT supported in namespaces. You must provide the
exact namespace path with all variables resolved.
Args:
memory_id: Memory resource ID
namespace: Exact namespace path (no wildcards)
query: Search query
actor_id: Optional actor ID (deprecated, use namespace)
top_k: Number of results to return
Returns:
List of memory records
Example:
# Correct - exact namespace
memories = client.retrieve_memories(
memory_id="mem-123",
namespace="support/facts/session-456/",
query="customer preferences"
)
# Incorrect - wildcards not supported
# memories = client.retrieve_memories(..., namespace="support/facts/*/", ...)
"""
if "*" in namespace:
logger.error("Wildcards are not supported in namespaces. Please provide exact namespace.")
return []
try:
# Let service handle all namespace validation
response = self.gmdp_client.retrieve_memory_records(
memoryId=memory_id, namespace=namespace, searchCriteria={"searchQuery": query, "topK": top_k}
)
memories: list[Dict[str, Any]] = response.get("memoryRecordSummaries", [])
logger.info("Retrieved %d memories from namespace: %s", len(memories), namespace)
return memories
except ClientError as e:
error_code = e.response["Error"]["Code"]
error_msg = e.response["Error"]["Message"]
if error_code == "ResourceNotFoundException":
logger.warning(
"Memory or namespace not found. Ensure memory %s exists and namespace '%s' is configured",
memory_id,
namespace,
)
elif error_code == "ValidationException":
logger.warning("Invalid search parameters: %s", error_msg)
elif error_code == "ServiceException":
logger.warning("Service error: %s. This may be temporary - try again later", error_msg)
else:
logger.warning("Memory retrieval failed (%s): %s", error_code, error_msg)
return []
def create_event(
self,
memory_id: str,
actor_id: str,
session_id: str,
messages: List[Tuple[str, str]],
event_timestamp: Optional[datetime] = None,
branch: Optional[Dict[str, str]] = None,
metadata: Optional[Dict[str, MetadataValue]] = None,
) -> Dict[str, Any]:
"""Save an event of an agent interaction or conversation with a user.
This is the basis of short-term memory. If you configured your Memory resource
to have MemoryStrategies, then events that are saved in short-term memory via
create_event will be used to extract long-term memory records.
Args:
memory_id: Memory resource ID
actor_id: Actor identifier (could be id of your user or an agent)
session_id: Session identifier (meant to logically group a series of events)
messages: List of (text, role) tuples. Role can be USER, ASSISTANT, TOOL, etc.
event_timestamp: timestamp for the entire event (not per message)
branch: Optional branch info. For new branches: {"rootEventId": "...", "name": "..."}
For continuing existing branch: {"name": "..."} or {"name": "...", "rootEventId": "..."}
A branch is used when you want to have a different history of events.
metadata: Optional custom key-value metadata to attach to the event.
Maximum 15 key-value pairs. Keys must be 1-128 characters.
Example: {"location": {"stringValue": "NYC"}}
Returns:
Created event
Example:
event = client.create_event(
memory_id=memory.get("id"),
actor_id="weatherWorrier",
session_id="WeatherSession",
messages=[
("What's the weather?", "USER"),
("Today is sunny", "ASSISTANT")
]
)
root_event_id = event.get("eventId")
print(event)
# Continue the conversation
event = client.create_event(
memory_id=memory.get("id"),
actor_id="weatherWorrier",
session_id="WeatherSession",
messages=[
("How about the weather tomorrow", "USER"),
("Tomorrow is cold!", "ASSISTANT")
]
)
print(event)
# branch the conversation so that the previous message is not part of the history
# (suppose you did not mean to ask about the weather tomorrow and want to undo
# that, and replace with a new message)
event = client.create_event(
memory_id=memory.get("id"),
actor_id="weatherWorrier",
session_id="WeatherSession",
branch={"name": "differentWeatherQuestion", "rootEventId": root_event_id},
messages=[
("How about the weather a year from now", "USER"),
("I can't predict that far into the future!", "ASSISTANT")
]
)
print(event)
"""
try:
if not messages:
raise ValueError("At least one message is required")
payload = []
for msg in messages:
if len(msg) != 2:
raise ValueError("Each message must be (text, role)")
text, role = msg
try:
role_enum = MessageRole(role.upper())
except ValueError as err:
raise ValueError(
"Invalid role '%s'. Must be one of: %s" % (role, ", ".join([r.value for r in MessageRole]))
) from err
payload.append({"conversational": {"content": {"text": text}, "role": role_enum.value}})
# Use provided timestamp or current time
if event_timestamp is None:
event_timestamp = datetime.utcnow()
params = {
"memoryId": memory_id,
"actorId": actor_id,
"sessionId": session_id,
"eventTimestamp": event_timestamp,
"payload": payload,
}
if branch:
params["branch"] = branch
if metadata:
params["metadata"] = metadata
response = self.gmdp_client.create_event(**params)
event: Dict[str, Any] = response["event"]
logger.info("Created event: %s", event["eventId"])
return event
except ClientError as e:
logger.error("Failed to create event: %s", e)
raise
def create_blob_event(
self,
memory_id: str,
actor_id: str,
session_id: str,
blob_data: Any,
event_timestamp: Optional[datetime] = None,
branch: Optional[Dict[str, str]] = None,
metadata: Optional[Dict[str, MetadataValue]] = None,
) -> Dict[str, Any]:
"""Save a blob event to AgentCore Memory.
Args:
memory_id: Memory resource ID
actor_id: Actor identifier
session_id: Session identifier
blob_data: Binary or structured data to store
event_timestamp: Optional timestamp for the event
branch: Optional branch info
metadata: Optional custom key-value metadata to attach to the event.
Maximum 15 key-value pairs. Keys must be 1-128 characters.
Example: {"location": {"stringValue": "NYC"}}
Returns:
Created event
Example:
event = client.create_blob_event(
memory_id="mem-xyz",
actor_id="user-123",
session_id="session-456",
blob_data={"file_content": "base64_encoded_data"},
metadata={"type": {"stringValue": "image"}}
)
"""
try:
payload = [{"blob": blob_data}]
if event_timestamp is None:
event_timestamp = datetime.utcnow()
params = {
"memoryId": memory_id,
"actorId": actor_id,
"sessionId": session_id,
"eventTimestamp": event_timestamp,
"payload": payload,
}
if branch:
params["branch"] = branch
if metadata:
params["metadata"] = metadata
response = self.gmdp_client.create_event(**params)
event: Dict[str, Any] = response["event"]
logger.info("Created blob event: %s", event["eventId"])
return event
except ClientError as e:
logger.error("Failed to create blob event: %s", e)
raise
def save_conversation(
self,
memory_id: str,
actor_id: str,
session_id: str,
messages: List[Tuple[str, str]],
event_timestamp: Optional[datetime] = None,
branch: Optional[Dict[str, str]] = None,
) -> Dict[str, Any]:
"""DEPRECATED: Use create_event() instead.
Args:
memory_id: Memory resource ID
actor_id: Actor identifier
session_id: Session identifier
messages: List of (text, role) tuples. Role can be USER, ASSISTANT, TOOL, etc.
event_timestamp: Optional timestamp for the entire event (not per message)
branch: Optional branch info. For new branches: {"rootEventId": "...", "name": "..."}
For continuing existing branch: {"name": "..."} or {"name": "...", "rootEventId": "..."}
Returns:
Created event
Example:
# Save multi-turn conversation
event = client.save_conversation(
memory_id="mem-xyz",
actor_id="user-123",
session_id="session-456",
messages=[
("What's the weather?", "USER"),
("And tomorrow?", "USER"),
("Checking weather...", "TOOL"),
("Today sunny, tomorrow rain", "ASSISTANT")
]
)
# Continue existing branch (only name required)
event = client.save_conversation(
memory_id="mem-xyz",
actor_id="user-123",
session_id="session-456",
messages=[("Continue conversation", "USER")],
branch={"name": "existing-branch"}
)
"""
try:
if not messages:
raise ValueError("At least one message is required")
# Build payload
payload = []
for msg in messages:
if len(msg) != 2:
raise ValueError("Each message must be (text, role)")
text, role = msg
# Validate role
try:
role_enum = MessageRole(role.upper())
except ValueError as err:
raise ValueError(
"Invalid role '%s'. Must be one of: %s" % (role, ", ".join([r.value for r in MessageRole]))
) from err
payload.append({"conversational": {"content": {"text": text}, "role": role_enum.value}})
# Use provided timestamp or current time
if event_timestamp is None:
event_timestamp = datetime.utcnow()
params = {
"memoryId": memory_id,
"actorId": actor_id,
"sessionId": session_id,
"eventTimestamp": event_timestamp,
"payload": payload,
"clientToken": str(uuid.uuid4()),
}
if branch:
params["branch"] = branch
response = self.gmdp_client.create_event(**params)
event: Dict[str, Any] = response["event"]
logger.info("Created event: %s", event["eventId"])
return event
except ClientError as e:
logger.error("Failed to create event: %s", e)
raise
def process_turn_with_llm(
self,
memory_id: str,
actor_id: str,
session_id: str,
user_input: str,
llm_callback: Callable[[str, List[Dict[str, Any]]], str],
retrieval_namespace: Optional[str] = None,
retrieval_query: Optional[str] = None,
top_k: int = 3,
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:
memory_id: Memory resource ID
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_namespace: Namespace to search for memories (optional)
retrieval_query: Custom search query (defaults to user_input)
top_k: Number of memories to retrieve
event_timestamp: Optional timestamp for the event
Returns:
Tuple of (retrieved_memories, agent_response, created_event)
Example:
def my_llm(user_input: str, memories: List[Dict]) -> str:
# Format context from memories
context = "\\n".join([m['content']['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']
memories, response, event = client.process_turn_with_llm(
memory_id="mem-xyz",
actor_id="user-123",
session_id="session-456",
user_input="What did we discuss yesterday?",
llm_callback=my_llm,
retrieval_namespace="support/facts/{sessionId}/"
)
"""
# Step 1: Retrieve relevant memories
retrieved_memories = []
if retrieval_namespace:
search_query = retrieval_query or user_input
retrieved_memories = self.retrieve_memories(
memory_id=memory_id, namespace=retrieval_namespace, query=search_query, top_k=top_k
)
logger.info("Retrieved %d memories for LLM context", len(retrieved_memories))
# 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.create_event(
memory_id=memory_id,
actor_id=actor_id,
session_id=session_id,
messages=[(user_input, "USER"), (agent_response, "ASSISTANT")],
event_timestamp=event_timestamp,
)
logger.info("Completed full conversation turn with LLM")
return retrieved_memories, agent_response, event
def list_events(
self,
memory_id: str,
actor_id: str,
session_id: str,
branch_name: Optional[str] = None,
include_parent_branches: bool = False,
event_metadata: Optional[List[EventMetadataFilter]] = None,
max_results: int = 100,
include_payload: bool = True,
) -> List[Dict[str, Any]]:
"""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:
memory_id: Memory resource ID
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)
event_metadata: Optional list of event metadata filters to apply.
Example: [{"left": {"metadataKey": "location"}, "operator": "EQUALS_TO",
"right": {"metadataValue": {"stringValue": "NYC"}}}]
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(memory_id, actor_id, session_id)
# Get events filtered by metadata
events = client.list_events(
memory_id, actor_id, session_id,
event_metadata=[{
"left": {"metadataKey": "location"},
"operator": "EQUALS_TO",
"right": {"metadataValue": {"stringValue": "NYC"}}
}]
)
"""
try:
all_events: List[Dict[str, Any]] = []
next_token = None
while len(all_events) < max_results:
params = {
"memoryId": memory_id,
"actorId": actor_id,
"sessionId": session_id,
"maxResults": 100,
"includePayloads": include_payload,
}
if next_token:
params["nextToken"] = next_token
# Build filter map
filter_map: Dict[str, Any] = {}
# Add branch filter if specified (but not for "main")
if branch_name and branch_name != "main":
filter_map["branch"] = {"name": branch_name, "includeParentBranches": include_parent_branches}
# Add event metadata filter if specified
if event_metadata:
filter_map["eventMetadata"] = event_metadata
if filter_map:
params["filter"] = filter_map
response = self.gmdp_client.list_events(**params)
events = response.get("events", [])
all_events.extend(events)
next_token = response.get("nextToken")
# Break if: no more pages or reached max
if not next_token or len(all_events) >= max_results:
break
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, memory_id: str, actor_id: str, session_id: str) -> List[Dict[str, Any]]:
"""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
while True:
params = {"memoryId": memory_id, "actorId": actor_id, "sessionId": session_id, "maxResults": 100}
if next_token:
params["nextToken"] = next_token
response = self.gmdp_client.list_events(**params)
all_events.extend(response.get("events", []))
next_token = response.get("nextToken")
if not next_token:
break
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 = []
# 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 result
except ClientError as e:
logger.error("Failed to list branches: %s", e)
raise
def list_branch_events(
self,
memory_id: str,
actor_id: str,
session_id: str,
branch_name: Optional[str] = None,
include_parent_branches: bool = False,
max_results: int = 100,
) -> List[Dict[str, Any]]:
"""List events in a specific branch.
This method provides complex filtering and pagination that would require
significant boilerplate code with raw boto3. It handles:
- Automatic pagination across multiple API calls
- Branch filtering with parent event inclusion logic
- Main branch isolation (events without branch info)
Args:
memory_id: Memory resource ID
actor_id: Actor identifier
session_id: Session identifier
branch_name: Branch name (None for main branch)
include_parent_branches: Whether to include events from parent branches
max_results: Maximum events to return
Returns:
List of events in the branch
"""
try:
params = {
"memoryId": memory_id,
"actorId": actor_id,
"sessionId": session_id,
"maxResults": min(100, max_results),
}
# Only add filter when we have a specific branch name
if branch_name:
params["filter"] = {"branch": {"name": branch_name, "includeParentBranches": include_parent_branches}}
response = self.gmdp_client.list_events(**params)
events: list[Dict[str, Any]] = response.get("events", [])
# Handle pagination
next_token = response.get("nextToken")
while next_token and len(events) < max_results:
params["nextToken"] = next_token
params["maxResults"] = min(100, max_results - len(events))
response = self.gmdp_client.list_events(**params)
events.extend(response.get("events", []))
next_token = response.get("nextToken")
# Filter for main branch if no branch specified
if not branch_name:
events = [e for e in events if not e.get("branch")]
logger.info("Retrieved %d events from branch '%s'", len(events), branch_name or "main")
return events
except ClientError as e:
logger.error("Failed to list branch events: %s", e)
raise
def get_conversation_tree(self, memory_id: str, actor_id: str, session_id: str) -> Dict[str, Any]:
"""Get a tree structure of the conversation with all branches.
This method transforms a flat list of events into a hierarchical tree structure,
providing visualization-ready data that would be complex to build from raw events.
It handles:
- Full pagination to get all events
- Grouping by branches
- Message summarization
- Tree structure building
Returns:
Dictionary representing the conversation tree structure
"""
try:
# Get all events - need to handle pagination for complete list
all_events = []
next_token = None
while True:
params = {"memoryId": memory_id, "actorId": actor_id, "sessionId": session_id, "maxResults": 100}
if next_token:
params["nextToken"] = next_token
response = self.gmdp_client.list_events(**params)
all_events.extend(response.get("events", []))
next_token = response.get("nextToken")
if not next_token:
break
# Build tree structure
tree: Dict[str, Any] = {
"session_id": session_id,
"actor_id": actor_id,
"main_branch": {"events": [], "branches": {}},
}