保存和检索见解
在为 AgentCore 内存配置了至少一种长期记忆策略并且该策略处于活动状态后,该服务将自动开始处理对话数据以提取和存储见解。此过程包括两个不同的步骤:保存原始对话,然后在处理结构化见解后对其进行检索。
第 1 步:保存对话事件以触发提取
当你使用该create_event操作将对话数据保存到短期记忆时,就会触发整个长期记忆过程。每次记录事件时,您都是在为主动记忆策略提供新的原始材料以供分析。
重要
只有在内存策略的状态变为之后创建的事件才ACTIVE会被处理以进行长期内存提取。在添加和激活策略之前存储的任何对话都将不包括在内。
以下示例说明如何将多回合对话保存到内存资源。
示例:将对话另存为一系列事件
#'memory_id' is the ID of your memory resource with an active summary strategy. from bedrock_agentcore.memory.session import MemorySessionManager from bedrock_agentcore.memory.constants import ConversationalMessage, MessageRole import time actor_id = "User84" session_id = "OrderSupportSession1" # Create session manager session_manager = MemorySessionManager( memory_id=memory_id, region_name="us-west-2" ) # Create a session session = session_manager.create_memory_session( actor_id=actor_id, session_id=session_id ) print("Capturing conversational events...") # Add all conversation turns session.add_turns( messages=[ ConversationalMessage("Hi, I'm having trouble with my order #12345", MessageRole.USER), ConversationalMessage("I am sorry to hear that. Let me look up your order.", MessageRole.ASSISTANT), ConversationalMessage("lookup_order(order_id='12345')", MessageRole.TOOL), ConversationalMessage("I see your order was shipped 3 days ago. What specific issue are you experiencing?", MessageRole.ASSISTANT), ConversationalMessage("The package arrived damaged", MessageRole.USER), ] ) print("Conversation turns added successfully!")
第 2 步:检索提取的见解
长期记忆的提取和整合是一个在后台运行的异步过程。可能需要一分钟或更长时间才能检索来自新对话的见解。您的应用程序逻辑应考虑这种延迟。
要检索结构化见解,您可以使用retrieve_memory_records操作。此操作对长期内存存储执行强大的语义搜索。您必须提供您在策略中定义的正确namespace信息以及描述您要查找的信息的正确信息。searchQuery
以下示例演示如何等待处理,然后检索上一步中保存的对话摘要。
示例:等待并检索会话摘要
# 'session' is an existing session object that you created when adding the coversation turns # session should be created on a memory resource with an active summary strategy. # --- Example 1: Retrieve the user's shipping issues under a specific namespace --- memories = session.search_long_term_memories( namespace=f"/summaries/{actor_id}/{session_id}/", query="What problem did the user report with their order?", top_k=5 ) # --- Example 2: Retrieve the user's shipping issues under a particular namespace hierarchy (e.g.: shipping issues across multiple sessions) --- memories = session.search_long_term_memories( namespace_path=f"/summaries/{actor_id}/", query="What problem did the user report with their order?", top_k=5 ) print(f"Found {len(memories)} memories:") for memory_record in memories: print(f"Retrieved Issue Detail: {memory_record}") print("--------------------------------------------------------------------") # Example Output: # Retrieved Issue Detail: The user reported that their package for order #12345 arrived damaged.