

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 场景：使用 AgentCore 内存的客户支持 AI 代理
<a name="memory-customer-scenario"></a>

在本节中，您将学习如何构建客户支持 AI 代理，该代理使用 AgentCore Memory 通过维护对话历史记录和提取有关用户偏好的长期见解来提供个性化帮助。本主题包括 AgentCore CLI 和 Amazon SDK 的代码示例。

以客户莎拉为例，她与您的购物网站的支持人工智能代理合作，询问延迟订单的问题。通过 AgentCore 内存 API 的交互流程将如下所示：

![记忆记 AgentCore 忆](https://docs.amazonaws.cn/bedrock-agentcore/latest/devguide/images/memory-short-long-term.png)


**Topics**
+ [第 1 步：创建 AgentCore 内存](#create-memory-resource)
+ [第 2 步：启动会话](#start-session)
+ [第 3 步：捕获对话历史记录](#capture-conversation)
+ [第 4 步：生成长期内存](#generate-longterm-memory)
+ [第 5 步：从短期记忆中检索过去的互动](#retrieve-shortterm-memory)
+ [第 6 步：使用长期记忆获得个性化帮助](#use-longterm-memory)

## 第 1 步：创建 AgentCore 内存
<a name="create-memory-resource"></a>

首先，创建具有短期和长期记忆能力的内存资源，为要提取的长期信息配置策略。

**Example**  

1. 使用语义策略创建内存：

   ```
   agentcore add memory --name CustomerSupportSemantic --strategies SEMANTIC
   agentcore deploy
   ```
**注意**  
C AgentCore LI 提供内存资源管理。对于事件操作（创建事件、列出事件等），请使用 Amazon Python 软件开发工具包 (Boto3) 或 Amazon SDK。

1. 运行打开 `agentcore` TUI，然后选择**添加**并选择**内存**：

1. 选择语**义**策略：  
![记忆向导：选择语义策略](https://docs.amazonaws.cn/bedrock-agentcore/latest/devguide/images/tui/memory-add-strategies.png)

1. 查看配置并按 Enter 键确认：  
![内存向导：查看配置](https://docs.amazonaws.cn/bedrock-agentcore/latest/devguide/images/tui/memory-add-confirm.png)

1. 

   ```
   import boto3
   import time
   from datetime import datetime
   
   # Initialize the Boto3 clients for control plane and data plane operations
   control_client = boto3.client('bedrock-agentcore-control')
   data_client = boto3.client('bedrock-agentcore')
   
   print("Creating a new memory resource...")
   
   # Create the memory resource with defined strategies
   response = control_client.create_memory(
       name="ShoppingSupportAgentMemory",
       description="Memory for a customer support agent.",
       memoryStrategies=[
           {
               'summaryMemoryStrategy': {
                   'name': 'SessionSummarizer',
                   'namespaceTemplates': ['/summaries/{actorId}/{sessionId}/']
               }
           },
           {
               'userPreferenceMemoryStrategy': {
                   'name': 'UserPreferenceExtractor',
                   'namespaceTemplates': ['/users/{actorId}/preferences/']
               }
           }
       ]
   )
   
   memory_id = response['memory']['id']
   print(f"Memory resource created with ID: {memory_id}")
   
   # Poll the memory status until it becomes ACTIVE
   while True:
       mem_status_response = control_client.get_memory(memoryId=memory_id)
       status = mem_status_response.get('memory', {}).get('status')
       if status == 'ACTIVE':
           print("Memory resource is now ACTIVE.")
           break
       elif status == 'FAILED':
           raise Exception("Memory resource creation FAILED.")
       print("Waiting for memory to become active...")
       time.sleep(10)
   ```

## 第 2 步：启动会话
<a name="start-session"></a>

当 Sarah 发起对话时，代理会创建一个新的、唯一的会话 ID 来单独跟踪此次互动。

```
# Unique identifier for the customer, Sarah
sarah_actor_id = "user-sarah-123"

# Unique identifier for this specific support session
support_session_id = "customer-support-session-1"

print(f"Session started for Actor ID: {sarah_actor_id}, Session ID: {support_session_id}")
```

## 第 3 步：捕获对话历史记录
<a name="capture-conversation"></a>

当莎拉解释她的问题时，特工记录了谈话的每一个环节（包括她的问题和特工的回答）。这将整个对话填充到短期记忆中，并为长期记忆策略的处理提供原始数据。

```
print("Capturing conversational events...")

full_conversation_payload = [
    {
        'conversational': {
            'role': 'USER',
            'content': {'text': "Hi, my order #ABC-456 is delayed."}
        }
    },
    {
        'conversational': {
            'role': 'ASSISTANT',
            'content': {'text': "I'm sorry to hear that, Sarah. Let me check the status for you."}
        }
    },
    {
        'conversational': {
            'role': 'USER',
            'content': {'text': "By the way, for future orders, please always use FedEx. I've had issues with other carriers."}
        }
    },
    {
        'conversational': {
            'role': 'ASSISTANT',
            'content': {'text': "Thank you for that information. I have made a note to use FedEx for your future shipments."}
        }
    }
]

data_client.create_event(
    memoryId=memory_id,
    actorId=sarah_actor_id,
    sessionId=support_session_id,
    eventTimestamp=datetime.now(),
    payload=full_conversation_payload
)

print("Conversation history has been captured in short-term memory.")
```

## 第 4 步：生成长期内存
<a name="generate-longterm-memory"></a>

在后台，异步提取过程运行。此过程使用您配置的内存策略分析最近的原始事件，以提取长期记忆，例如摘要、语义事实或用户偏好，然后将其存储起来以备将来使用。

## 第 5 步：从短期记忆中检索过去的互动
<a name="retrieve-shortterm-memory"></a>

为了提供情境感知帮助，代理会加载当前的对话历史记录。这可以帮助代理了解莎拉在正在进行的聊天中提出了哪些问题。

```
print("\nRetrieving current conversation history from short-term memory...")

response = data_client.list_events(
    memoryId=memory_id,
    actorId=sarah_actor_id,
    sessionId=support_session_id,
    maxResults=10
)

# Reverse the list of events to display them in chronological order
event_list = reversed(response.get('events', []))

for event in event_list: print(event)
```

## 第 6 步：使用长期记忆获得个性化帮助
<a name="use-longterm-memory"></a>

该代理对提取的长期记忆进行语义搜索，以找到有关莎拉偏好、订单历史记录或过去担忧的相关见解。这使代理可以提供高度个性化的帮助，而无需让 Sarah 重复她在之前的聊天中已经分享的信息。

```
# Wait for the asynchronous extraction to finish
print("\nWaiting 60 seconds for long-term memory processing...")
time.sleep(60)

# --- Example 1: Retrieve the user's shipping preference ---
print("\nRetrieving user preferences from long-term memory...")
preference_response = data_client.retrieve_memory_records(
    memoryId=memory_id,
    namespace=f"/users/{sarah_actor_id}/preferences/",
    searchCriteria={"searchQuery": "Does the user have a preferred shipping carrier?"}
)
for record in preference_response.get('memoryRecordSummaries', []):
    print(f"- Retrieved Record: {record}")

# --- Example 2: Broad query about the user's issue (across sessions with the help of namespacePath) ---
print("\nPerforming a broad search for user's reported issues...")
issue_response = data_client.retrieve_memory_records(
    memoryId=memory_id,
    namespacePath=f"/summaries/{sarah_actor_id}/",
    searchCriteria={"searchQuery": "What problem did the user report with their order?"}
)
for record in issue_response.get('memoryRecordSummaries', []):
    print(f"- Retrieved Record: {record}")
```

这种综合方法使代理能够在各个会话中保持丰富的背景信息，识别回头客，回忆重要细节，无缝提供个性化体验，从而提供更快、更自然、更有效的客户支持。