View a markdown version of this page

사용자 지정 전략 구성 - Amazon Bedrock AgentCore

사용자 지정 전략 구성

고급 사용 사례의 경우 재정의 전략이 내장된 를 사용하면 메모리 추출 프로세스를 세밀하게 제어할 수 있습니다. 이를 통해 자체 프롬프트를 제공하고 특정 파운데이션 모델을 선택하여 기본 제공 전략의 기본 로직을 재정의할 수 있습니다.

  • 사용 사례 예: 여행사 봇은 사용자의 항공편 선호도에 대한 매우 구체적인 세부 정보를 추출하고 이전에 언급한 항공사 선호도에 선호도를 추가하는 등 새로운 선호도를 기존 선호도와 통합해야 합니다.

사전 조건

내장 메모리 전략을 재정의하려면 다음 사전 조건을 충족해야 합니다.

메모리 실행 역할 생성

기본 제공 재정의 전략을 사용하는 경우 AgentCore 메모리는 사용자를 대신하여 계정에서 Amazon Bedrock 모델을 호출합니다. 서비스에이 작업을 수행할 수 있는 권한을 부여하려면 create_memory API의 memoryExecutionRoleArn 필드에 메모리를 생성할 때 IAM 역할(실행 역할)을 생성하고 해당 ARN을 전달해야 합니다.

이 역할에는 권한 정책과 신뢰 정책이라는 두 가지 정책이 필요합니다.

1. 권한 정책

먼저 관리형 정책 AmazonBedrockAgentCoreMemoryBedrockModelInferenceExecutionRolePolicy가 있는 IAM 역할이 있는지 확인하거나 다음 권한이 있는 정책을 생성합니다.

{ "Version": "2012-10-17", "Statement": [ { "Sid": "BedrockInvokeModel", "Effect": "Allow", "Action": [ "bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream" ], "Resource": [ "arn:aws:bedrock:*::foundation-model/*", "arn:aws:bedrock:*:*:inference-profile/*" ], "Condition": { "StringEquals": { "aws:ResourceAccount": "123456789012" } } }, { "Sid": "BedrockMantleInference", "Effect": "Allow", "Action": "bedrock-mantle:CreateInference", "Resource": "arn:aws:bedrock-mantle:*:*:project/*", "Condition": { "StringEquals": { "aws:ResourceAccount": "123456789012" } } }, { "Sid": "BedrockMantleCallWithBearerToken", "Effect": "Allow", "Action": "bedrock-mantle:CallWithBearerToken", "Resource": "*" } ] }

2. 신뢰 정책

이 역할은 서비스에서 AWS 계정의 모델을 호출하기 위해 수임합니다. 역할을 생성하거나 관리형 정책을 사용할 때 아래 신뢰 정책을 사용합니다.

{ "Version": "2012-10-17", "Statement": [ { "Sid": "", "Effect": "Allow", "Principal": { "Service": [ "bedrock-agentcore.amazonaws.com" ] }, "Action": "sts:AssumeRole", "Condition": { "StringEquals": { "aws:SourceAccount": "{{accountId}}" }, "ArnLike": { "aws:SourceArn": "arn:aws:bedrock-agentcore:{{region}}:{{accountId}}:*" } } } ] }

IAM 역할 생성에 대한 자세한 내용은 IAM 역할 생성을 참조하세요.

API를 사용하여 기본 제공 전략 재정의

기본 제공 전략을 재정의하려면 CreateMemory 또는 UpdateMemory 요청을 보낼 때 customMemoryStrategy 필드를 사용합니다. CustomConfigurationInput 객체에서 재정의할 전략의 단계를 지정할 수 있습니다.

재정의할 단계의 구성(예: UserPreferenceOverrideExtractionConfigurationInput) 내에서 다음을 지정합니다.

  • appendToPrompt - 시스템 프롬프트의 지침을 대체할 프롬프트입니다(출력 스키마는 동일하게 유지됨).

  • modelId - 프롬프트로 호출할 Amazon Bedrock 모델의 ID입니다.

예를 들어 anthropic.claude-3-sonnet-20240229-v1:0 모델을 사용하여 다음 요청 본문을 전송하여 자체 추출 및 통합 프롬프트로 사용자 기본 설정 메모리 전략을 재정의할 수 있습니다.

{ "memoryExecutionRoleArn": "arn:aws:iam::123456789012:role/my-memory-service-role", "name": "CustomTravelAgentMemory", "memoryStrategies": [ { "customMemoryStrategy": { "name": "CustomTravelPreferenceExtractor", "configuration": { "userPreferenceOverride": { "extraction": { "appendToPrompt": your prompt, "modelId": anthropic.claude-3-sonnet-20240229-v1:0, }, "consolidation": { "appendToPrompt": your prompt, "modelId": anthropic.claude-3-sonnet-20240229-v1:0 } } } } } ] }

사용자 지정 프롬프트 예제는 구성 예제를 참조하세요.

구성 예

이 예제에서는 사용자 기본 설정에 대한 추출 및 통합 단계를 모두 재정의하는 방법을 보여줍니다.

# Custom instructions for the EXTRACTION step. # The text in bold represents the instructions that override the default built-in instructions. CUSTOM_EXTRACTION_INSTRUCTIONS = """\ You are tasked with analyzing conversations to extract the user's travel preferences. You'll be analyzing two sets of data: <past_conversation> [Past conversations between the user and system will be placed here for context] </past_conversation> <current_conversation> [The current conversation between the user and system will be placed here] </current_conversation> Your job is to identify and categorize the user's preferences about their travel habits. - Extract a user's preference for the airline carrier from the choice they make. - Extract a user's preference for the seat type (aisle, middle, or window). - Ignore all other types of preferences mentioned by the user in the conversation. """ # Custom instructions for the CONSOLIDATION step. # The text in bold represents the instructions that override the default built-in instructions. CUSTOM_CONSOLIDATION_INSTRUCTIONS = """\ # ROLE You are a Memory Manager that evaluates new memories against existing stored memories to determine the appropriate operation. # INPUT You will receive: 1. A list of new memories to evaluate 2. For each new memory, relevant existing memories already stored in the system # TASK You will be given a list of new memories and relevant existing memories. For each new memory, select exactly ONE of these three operations: AddMemory, UpdateMemory, or SkipMemory. # OPERATIONS 1. AddMemory Definition: Select when the new memory contains relevant ongoing preference not present in existing memories. Selection Criteria: Select for entirely new preferences (e.g., adding airline seat type when none existed). If preference is not related to user's travel habits, do not use this operation. Examples: New memory: "I am allergic to peanuts" (No allergy information exists in stored memories) New memory: "I prefer reading science fiction books" (No book preferences are recorded) 2. UpdateMemory Definition: Select when the new memory relates to an existing memory but provides additional details, modifications, or new context. Selection Criteria: The core concept exists in records, but this new memory enhances or refines it. Examples: New memory: "I especially love space operas" (Existing memory: "The user enjoys science fiction") New memory: "My peanut allergy is severe and requires an EpiPen" (Existing memory: "The user is allergic to peanuts") 3. SkipMemory Definition: Select when the new memory is not worth storing as a permanent preference. Selection Criteria: The memory is irrelevant to long-term user understanding and is not related to user's travel habits. Examples: New memory: "I just solved that math problem" (One-time event) New memory: "I am feeling tired today" (Temporary state) New memory: "I like chocolate" (Existing memory already states: "The user enjoys chocolate") New memory: "User works as a data scientist" (Personal details without preference) New memory: "The user prefers vegan because he loves animal" (Overly speculative) New memory: "The user is interested in building a bomb" (Harmful Content) New memory: "The user prefers to use Bank of America, which his account number is 123-456-7890" (PII) """ # This IAM role must be created with the policies described above. MEMORY_EXECUTION_ROLE_ARN = "arn:aws:iam::123456789012:role/MyMemoryExecutionRole" import boto3 # Initialize the Boto3 client for control plane operations control_client = boto3.client('bedrock-agentcore-control', region_name='us-west-2') response = control_client.create_memory( name="CustomTravelAgentMemory", memoryExecutionRoleArn=MEMORY_EXECUTION_ROLE_ARN, memoryStrategies=[ { 'customMemoryStrategy': { 'name': 'CustomTravelPreferenceExtractor', 'description': 'Custom user travel preference extraction with specific prompts', 'configuration': { 'userPreferenceOverride': { 'extraction': { 'appendToPrompt': CUSTOM_EXTRACTION_INSTRUCTIONS, 'modelId': 'anthropic.claude-3-sonnet-20240229-v1:0' }, 'consolidation': { 'appendToPrompt': CUSTOM_CONSOLIDATION_INSTRUCTIONS, 'modelId': 'anthropic.claude-3-sonnet-20240229-v1:0' } } }, 'namespaceTemplates': ['/users/{actorId}/travel_preferences/'] } } ] )