View a markdown version of this page

Configure uma estratégia personalizada - Amazon Bedrock AgentCore

Configure uma estratégia personalizada

Para casos de uso avançados, estratégias integradas com substituições oferecem controle refinado sobre o processo de extração de memória. Isso permite que você substitua a lógica padrão de uma estratégia integrada fornecendo seus próprios prompts e selecionando um modelo básico específico.

  • Exemplo de caso de uso: um bot de agente de viagens precisa extrair detalhes muito específicos sobre as preferências de voo do usuário e consolidar novas preferências com as existentes, como adicionar uma preferência de assento a uma preferência de companhia aérea declarada anteriormente.

Pré-requisitos

Para substituir uma estratégia de memória incorporada, você deve atender aos seguintes pré-requisitos:

Criando a função de execução de memória

Quando você usa uma estratégia integrada com substituições, o AgentCore Memory invoca um modelo Amazon Bedrock em sua conta em seu nome. Para conceder permissão ao serviço para fazer isso, você deve criar uma função do IAM (uma função de execução) e passar seu ARN ao criar a memória no memoryExecutionRoleArn campo da create_memory API.

Essa função requer duas políticas: uma política de permissões e uma política de confiança.

1. Política de permissões

Comece verificando se você tem uma função do IAM com a política AmazonBedrockAgentCoreMemoryBedrockModelInferenceExecutionRolePolicygerenciada ou crie uma política com as seguintes permissões:

{ "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. Política de confiança

Essa função é assumida pelo Serviço para chamar o modelo em sua AWS conta. Use a política de confiança abaixo ao criar a função ou ao usar a política gerenciada:

{ "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}}:*" } } } ] }

Para obter informações sobre como criar uma função do IAM, consulte Criação de função do IAM.

Substitua uma estratégia integrada com a API

Para substituir uma estratégia integrada, use o customMemoryStrategy campo ao enviar uma UpdateMemorysolicitação CreateMemoryou. No CustomConfigurationInputobjeto, você pode especificar uma etapa na estratégia a ser substituída.

Na configuração da etapa a ser substituída (por exemplo, UserPreferenceOverrideExtractionConfigurationInput), especifique o seguinte:

  • appendToPrompt— O prompt com o qual substituir as instruções no prompt do sistema (o esquema de saída permanece o mesmo).

  • modelId— O ID do modelo Amazon Bedrock a ser invocado com o prompt.

Por exemplo, você pode enviar o seguinte corpo de solicitação para substituir a estratégia de memória preferencial do usuário com seus próprios prompts de extração e consolidação, usando o modelo anthropic.claude-3-sonnet-20240229-v 1: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 } } } } } ] }

Por exemplo, prompts personalizados, consulte Exemplo de configuração.

Exemplo de configuração

Este exemplo demonstra como substituir as etapas de extração e consolidação de acordo com as preferências do usuário.

# 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/'] } } ] )