

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 儲存和擷取洞見
<a name="long-term-saving-and-retrieving-insights"></a>

使用至少一個長期記憶體策略設定 AgentCore 記憶體且策略為 ACTIVE 後，服務會自動開始處理對話資料，以擷取和儲存洞見。此程序包含兩個不同的步驟：儲存原始對話，然後在處理後擷取結構化洞見。

## 步驟 1：儲存對話事件以觸發擷取
<a name="long-term-step-1-save-conversational-events"></a>

當您使用 `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：擷取擷取的洞見
<a name="long-term-step-2-retrieve-extracted-insights"></a>

長期記憶體的擷取和合併是一種在背景中執行**的非同步程序**。可能需要一分鐘或更久的時間，新對話的洞見才會變成可供擷取。您的應用程式邏輯應考量此延遲。

若要擷取結構化洞見，您可以使用 `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.
```