

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# シナリオ: AgentCore Memory を使用するカスタマーサポート AI エージェント
<a name="memory-customer-scenario"></a>

このセクションでは、会話履歴を維持し、ユーザー設定に関する長期的なインサイトを抽出することで、AgentCore Memory を使用してパーソナライズされたサポートを提供するカスタマーサポート AI エージェントを構築する方法について説明します。このトピックには、AgentCore CLI と AWS SDK のコード例が含まれています。

顧客の Sarah を考えてみます。Sarah は、ショッピングウェブサイトのサポート AI エージェントと連携して、注文の遅延について問い合わせます。AgentCore Memory APIs を介したインタラクションフローは次のようになります。

![メモリ AgentCore メモリ](https://docs.aws.amazon.com/ja_jp/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
   ```
**注記**  
AgentCore CLI はメモリリソース管理を提供します。イベントオペレーション (イベントの作成、イベントの一覧表示など) には、Python SDK (Boto3) または AWS SDK AWS を使用します。

1. `agentcore` を実行して TUI を開き、**追加** を選択して**メモリ** を選択します。

1. **セマンティック**戦略を選択します。  
![メモリウィザード: SEMANTIC 戦略を選択する](https://docs.aws.amazon.com/ja_jp/bedrock-agentcore/latest/devguide/images/tui/memory-add-strategies.png)

1. 設定を確認し、Enter キーを押して以下を確認します。  
![メモリウィザード: 設定の確認](https://docs.aws.amazon.com/ja_jp/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>

Sarah が問題を説明すると、エージェントは会話の各ターン (Sarah の質問とエージェントの応答の両方) をキャプチャします。これにより、会話全体が短期メモリに入力され、処理する長期メモリ戦略の raw データが提供されます。

```
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>

バックグラウンドでは、非同期抽出プロセスが実行されます。このプロセスは、設定されたメモリ戦略を使用して最近の raw イベントを分析し、概要、セマンティックファクト、ユーザー設定などの長期的な記憶を抽出し、将来の使用のために保存します。

## ステップ 5: 短期メモリから過去のインタラクションを取得する
<a name="retrieve-shortterm-memory"></a>

コンテキスト対応の支援を提供するために、エージェントは現在の会話履歴をロードします。これにより、エージェントは Sarah が進行中のチャットでどのような問題を提起したかを理解できます。

```
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 の好み、注文履歴、過去の懸念に関する関連インサイトを見つけます。これにより、エージェントは高度にパーソナライズされた支援を提供できます。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}")
```

この統合されたアプローチにより、エージェントはセッション間でリッチコンテキストを維持し、リピート顧客を認識し、重要な詳細を再現し、パーソナライズされたエクスペリエンスをシームレスに提供できるため、より迅速で自然で効果的なカスタマーサポートを実現できます。