

# 자체 관리형 전략
<a name="memory-self-managed-strategies"></a>

Amazon Bedrock AgentCore 메모리의 자체 관리형 전략을 사용하면 메모리 추출 및 통합 파이프라인을 완벽하게 제어할 수 있습니다. 자체 관리형 전략을 사용하면 Amazon Bedrock AgentCore를 스토리지 및 검색에 활용하면서 사용자 지정 메모리 처리 워크플로를 구축할 수 있습니다.

배치 작업( [BatchCreateMemoryRecords](https://docs.aws.amazon.com/bedrock-agentcore/latest/APIReference/API_BatchCreateMemoryRecords.html) , [BatchUpdateMemoryRecords](https://docs.aws.amazon.com/bedrock-agentcore/latest/APIReference/API_BatchUpdateMemoryRecords.html) , [BatchDeleteMemoryRecords](https://docs.aws.amazon.com/bedrock-agentcore/latest/APIReference/API_BatchDeleteMemoryRecords.html) )과 함께 자체 관리형 전략을 사용하면 검색 기능을 위해 이러한 추출된 레코드를 Amazon Bedrock AgentCore 메모리에 직접 수집할 수 있습니다.

자체 관리형 전략을 사용하면 다음을 수행할 수 있습니다.
+ 구성 가능한 트리거를 통한 파이프라인 호출 제어
+ 외부 처리 시스템과 통합
+ 사용자 지정 추출 및 통합 알고리즘 구현
+ 추출 및 통합을 위해 원하는 모델 호출
+ 사용자 지정 메모리 레코드 스키마, 네임스페이스 등을 정의합니다.
+ 추출된 레코드를 Amazon Bedrock AgentCore 장기 메모리에 수집

**Topics**
+ [자체 관리형 전략 생성 및 사용](#use-self-managed-strategy)
+ [사전 조건](#prerequisites)
+ [인프라 설정](#setting-up-infrastructure)
+ [자체 관리형 전략 생성](#creating-self-managed-strategy)
+ [페이로드 전송 이해](#understanding-payload-delivery)
+ [사용자 지정 파이프라인 구축](#building-custom-pipeline)
+ [구현 테스트](#testing-implementation)
+ [모범 사례](#best-practices)

## 자체 관리형 전략 생성 및 사용
<a name="use-self-managed-strategy"></a>

자체 관리형 전략은 트리거 구성에서 메모리 레코드 스토리지에 이르는 5단계 프로세스를 따릅니다.

1.  **트리거 구성**: 단기 메모리 이벤트를 기반으로 파이프라인을 호출하는 트리거 조건(메시지 수, 유휴 제한 시간, 토큰 수) 정의

1.  **알림 및 페이로드 전송 수신**: Amazon Bedrock AgentCore는 SNS 주제에 알림을 게시하고 트리거 조건이 충족되면 S3 버킷에 대화 데이터를 전송합니다.

1.  **메모리 레코드 추출**: 사용자 지정 파이프라인이 페이로드를 검색하고 추출 로직을 적용하여 관련 메모리를 식별합니다.

1.  **메모리 레코드 통합**: 추출된 메모리를 처리하여 중복을 제거하고 기존 레코드와의 충돌을 해결합니다.

1.  **메모리 레코드 저장** : 배치 APIs 사용하여 처리된 메모리 레코드를 Amazon Bedrock AgentCore 장기 메모리에 다시 저장

## 사전 조건
<a name="prerequisites"></a>

자체 관리형 전략을 설정하기 전에 다음이 있는지 확인합니다.
+ 적절한 권한이 있는 AWS 계정
+ Amazon Bedrock AgentCore 액세스
+  AWS IAM, Amazon S3 및 Amazon SNS에 대한 기본 이해

## 인프라 설정
<a name="setting-up-infrastructure"></a>

Amazon Bedrock AgentCore가 AWS 리소스에 액세스하는 데 필요한 S3 버킷, SNS 주제 및 IAM 역할을 포함한 필수 리소스를 생성합니다.

### 1단계: S3 버킷 생성
<a name="create-s3-bucket"></a>

Amazon Bedrock AgentCore가 일괄 이벤트 페이로드를 전송할 계정에 S3 버킷을 생성합니다.

**중요**  
처리 후 객체를 자동으로 삭제하여 비용을 제어하도록 수명 주기 정책을 구성합니다.

### 2단계: SNS 주제 생성
<a name="create-sns-topic"></a>

작업 알림을 위한 SNS 주제를 생성합니다. 세션 내 처리 순서가 사용 사례에 중요한 경우 FIFO 주제를 사용합니다.

### 3단계 - IAM 역할 생성
<a name="create-iam-role"></a>

Amazon Bedrock AgentCore가 리소스에 액세스하기 위해 수임할 수 있는 IAM 역할을 생성합니다.

 **신뢰 정책** 

다음 신뢰 정책을 사용합니다.

```
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "bedrock-agentcore.amazonaws.com"
            },
            "Action": "sts:AssumeRole",
            "Condition": {
                "ArnLike": {
                    "aws:SourceArn": "arn:aws:bedrock-agentcore:<region>:<account-id>:memory/*"
                }
            }
        }
    ]
}
```

 **권한 정책** 

다음 권한 정책을 사용합니다.

```
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "S3PayloadDelivery",
            "Effect": "Allow",
            "Action": [
                "s3:GetBucketLocation",
                "s3:PutObject"
            ],
            "Resource": [
                "arn:aws:s3:::your-agentcore-payloads-bucket",
                "arn:aws:s3:::your-agentcore-payloads-bucket/*"
            ]
        },
        {
            "Sid": "SNSNotifications",
            "Effect": "Allow",
            "Action": [
                "sns:GetTopicAttributes",
                "sns:Publish"
            ],
            "Resource": "arn:aws:sns:us-east-1:123456789012:agentcore-memory-jobs"
        }
    ]
}
```

 **추가 KMS 권한(암호화된 리소스를 사용하는 경우)** 

암호화된 리소스를 사용하는 경우 다음 KMS 권한을 추가합니다.

```
{
    "Sid": "KMSPermissions",
    "Effect": "Allow",
    "Action": [
        "kms:GenerateDataKey",
        "kms:Decrypt"
    ],
    "Resource": "arn:aws:kms:us-east-1:123456789012:key/your-key-id"
}
```

## 자체 관리형 전략 생성
<a name="creating-self-managed-strategy"></a>

Amazon Bedrock AgentCore 컨트롤 플레인 APIs를 사용하여 자체 관리형 전략으로 AgentCore 메모리를 생성하거나 업데이트합니다.

### 필수 권한
<a name="required-permissions"></a>

IAM 사용자 또는 역할에 다음이 필요합니다.
+ bedrock-agentcore:\* 권한
+  `iam:PassRole` 실행 역할에 대한 권한

### 자체 관리형 전략을 사용하여 AgentCore 메모리 생성
<a name="create-memory-with-strategy"></a>

 AWS SDK `CreateMemory` 작업을 사용하여 자체 관리형 전략이 있는 AgentCore 메모리를 생성합니다.

```
aws bedrock-agentcore-control create-memory \
  --name "MyCustomMemory" \
  --description "Memory with self-managed extraction strategy" \
  --memory-execution-role-arn "arn:aws:iam::123456789012:role/AgentCoreMemoryRole" \
  --event-expiry-duration 90 \
  --memory-strategies '[
    {
      "customMemoryStrategy": {
        "name": "SelfManagedExtraction",
        "description": "Custom extraction strategy",
        "configuration": {
          "selfManagedConfiguration": {
            "triggerConditions": [
              {
                "messageBasedTrigger": {
                  "messageCount": 6
                }
              },
              {
                "tokenBasedTrigger": {
                  "tokenCount": 1000
                }
              },
              {
                "timeBasedTrigger": {
                  "idleSessionTimeout": 30
                }
              }
            ],
            "historicalContextWindowSize": 2,
            "invocationConfiguration": {
              "payloadDeliveryBucketName": "your-agentcore-payloads-bucket",
              "topicArn": "arn:aws:sns:us-east-1:123456789012:agentcore-memory-jobs"
            }
          }
        }
      }
    }
  ]'
```

## 페이로드 전송 이해
<a name="understanding-payload-delivery"></a>

트리거 조건이 충족되면 Amazon Bedrock AgentCore는 특정 스키마를 사용하여 알림 및 페이로드를 보냅니다.

### SNS 알림 메시지
<a name="sns-notification-message"></a>

```
{
  "jobId": "unique-job-identifier",
  "s3PayloadLocation": "s3://bucket/path/to/payload.json",
  "memoryId": "your-memory-id",
  "strategyId": "your-strategy-id"
}
```

### S3 페이로드 구조
<a name="s3-payload-structure"></a>

```
{
  "requestId": "request-identifier",
  "accountId": "123456789012",
  "memoryId": "your-memory-id",
  "actorId": "user-or-agent-id",
  "sessionId": "conversation-session-id",
  "strategyId": "your-strategy-id",
  "startingTimestamp": 1634567890,
  "endingTimestamp": 1634567920,
  "currentContext": [
    {
      "role": "USER",
      "content": {
        "text": "User message content"
      }
    },
    {
      "role": "ASSISTANT",
      "content": {
        "text": "Assistant response"
      }
    }
  ],
  "historicalContext": [
    {
      "role": "USER",
      "content": {
        "text": "User message content"
      }
    },
    {
      "role": "ASSISTANT",
      "content": {
        "text": "Previous assistant response"
      }
    },
    {
      "blob": "{}",
    }
  ]
}
```

## 사용자 지정 파이프라인 구축
<a name="building-custom-pipeline"></a>

이 섹션에서는 AWS Lambda 및 SQS를 사용하여 자체 관리형 메모리 처리 파이프라인을 구축하는 한 가지 방법을 보여줍니다. 이는 한 가지 예에 불과합니다. 요구 사항을 충족하는 모든 컴퓨팅 플랫폼(EC2, ECS, Fargate), 로직 및 처리 프레임워크를 사용하여 파이프라인을 구현할 수 있습니다.

### 1단계: 컴퓨팅 설정
<a name="set-up-compute"></a>

1. SQS 대기열을 생성하고 SNS 주제를 구독합니다.

1.  AWS Lambda 함수를 생성하여 알림 처리

1. Lambda 실행 역할 권한 구성

### 2단계: 파이프라인 처리
<a name="processing-pipeline"></a>

다음 예제 파이프라인은 네 가지 주요 구성 요소로 구성됩니다.

1. 알림 처리 - SNS 알림 처리 및 S3 페이로드 다운로드

1. 메모리 추출 - Bedrock 모델을 사용하여 대화에서 관련 정보 추출

1. 메모리 통합 - 추출된 메모리를 기존 레코드와 복제 및 병합

1. 배치 수집 - 배치 APIs를 사용하여 처리된 메모리를 Amazon Bedrock AgentCore에 다시 저장

## 구현 테스트
<a name="testing-implementation"></a>

1.  **이벤트 생성**: Amazon Bedrock AgentCore APIs 사용하여 대화 이벤트 생성(`CreateEvent`)

1.  **알림 모니터링**: 트리거가 충족될 때 SNS 주제가 알림을 수신하는지 확인합니다.

1.  **처리 검증**: Lambda 함수가 페이로드를 올바르게 처리하고 메모리 레코드를 추출하는지 확인합니다.

1.  **수집 확인**: 추출된 메모리가 저장되었는지 확인하는 `list-memory-records` 데 사용

### 예: 테스트 이벤트 생성
<a name="creating-test-events"></a>

```
aws bedrock-agentcore create-event \
  --memory-id "your-memory-id" \
  --actor-id "test-user" \
  --session-id "test-session-1" \
  --event-timestamp "2024-01-15T10:00:00Z" \
  --payload '[{
    "conversational": {
      "content": {"text": "I prefer Italian restaurants with outdoor seating"},
      "role": "USER"
    }
  }]'
```

### 예: 메모리 레코드 검색
<a name="retrieving-memory-records"></a>

```
# List records belonging to a specific namespace
aws bedrock-agentcore list-memory-records \
  --memory-id "your-memory-id" \
  --namespace "/actor/Jane/" # lists all records present in the given namespace

# List records belonging to a particular namespace hierarchy
aws bedrock-agentcore list-memory-records \
  --memory-id "your-memory-id" \
  --namespace-path "/" # lists all records present under the namespace hierarchy
```

## 모범 사례
<a name="best-practices"></a>

자체 관리형 전략을 구현할 때 성능, 신뢰성, 비용 최적화 및 보안에 대한 다음 모범 사례를 따르세요.

### 성능 및 안정성
<a name="performance-reliability"></a>
+  **SLA 공유**: Amazon Bedrock AgentCore와 자체 관리형 파이프라인 간에 장기 메모리 레코드 생성 SLA 공유
+  **오류 처리**: 처리 실패에 대한 적절한 재시도 로직 및 배달 못한 편지 대기열 구현
+  **모니터링**: 디버깅 및 처리 실패와 지연 시간에 대한 CloudWatch 로그, 지표, 경보를 설정합니다. 또한 Amazon Bedrock AgentCore의 벤딩 로그에서 페이로드 전송 실패 확인

### 비용 최적화
<a name="cost-optimization"></a>
+  **S3 수명 주기 정책**: 처리된 페이로드의 자동 삭제를 구성하여 스토리지 비용 제어
+  **올바른 크기 조정**: 처리 요구 사항에 따라 적절한 컴퓨팅 메모리 및 제한 시간 설정 선택

### 처리 고려 사항
<a name="processing-considerations"></a>
+  **트리거 최적화**: 사용 사례 요구 사항에 따라 트리거 조건 구성 - 지연 시간에 대한 애플리케이션의 허용 오차와 처리 비용을 고려하여 처리 효율성과 메모리 최신성 간의 균형을 맞춥니다.
+  **FIFO 주제**: 세션 순서 지정이 중요한 경우 FIFO SNS 주제 사용(예: 요약 워크플로용)
+  **메모리 통합**: 중복되거나 충돌하는 메모리 레코드를 저장하지 않도록 중복 제거 로직을 구현하여 스토리지 비용을 절감하고 검색 정확도를 개선합니다.
+  **메모리 레코드 조직**: 메모리 레코드를 효율적으로 분류, 필터링 및 검색할 수 있도록 레코드를 수집할 때 의미 있는 네임스페이스와 전략 IDs를 항상 포함하세요.

### 보안
<a name="security"></a>
+  **최소 권한**: 모든 IAM 역할에 필요한 최소 권한 부여
+  **암호화**: 민감한 데이터가 포함된 S3 버킷 및 SNS 주제에 KMS 암호화 사용