

# Configure uma estratégia personalizada
<a name="long-term-configuring-custom-strategies"></a>

Para casos de uso avançados, estratégias [integradas com substituições](memory-custom-strategy.md) 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.

**Topics**
+ [Pré-requisitos](#long-term-creating-memory-prerequisites)
+ [Criando a função de execução de memória](#long-term-creating-memory-execution-role)
+ [Substitua uma estratégia integrada com a API](#long-term-custom-strategy-configuration-api)
+ [Exemplo de configuração](#long-term-custom-strategy-configuration-example)

## Pré-requisitos
<a name="long-term-creating-memory-prerequisites"></a>

Para substituir uma estratégia de memória incorporada, você deve atender aos seguintes pré-requisitos:
+ Tenha uma função AgentCore de serviço de memória. Para obter mais informações, consulte [Criação da função de execução de memória](#long-term-creating-memory-execution-role).
+ Se você planeja substituir o modelo para a solicitação, você deve ter acesso ao modelo que você escolheu para substituir. Para obter mais informações, consulte [Acesse os modelos básicos do Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html) e a [capacidade do Amazon Bedrock para estratégias integradas com substituições](bedrock-capacity.md).

## Criando a função de execução de memória
<a name="long-term-creating-memory-execution-role"></a>

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
<a name="long-term-permissions-policy"></a>

Comece verificando se você tem uma função do IAM com a política [AmazonBedrockAgentCoreMemoryBedrockModelInferenceExecutionRolePolicy](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/security-iam-awsmanpol.html#security-iam-awsmanpol-AmazonBedrockAgentCoreMemoryBedrockModelInferenceExecutionRolePolicy)gerenciada 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
<a name="long-term-trust-policy"></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](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html).

## Substitua uma estratégia integrada com a API
<a name="long-term-custom-strategy-configuration-api"></a>

Para substituir uma estratégia integrada, use o `customMemoryStrategy` campo ao enviar uma [UpdateMemory](https://docs.aws.amazon.com/bedrock-agentcore-control/latest/APIReference/API_UpdateMemory.html)solicitação [CreateMemory](https://docs.aws.amazon.com/bedrock-agentcore-control/latest/APIReference/API_CreateMemory.html)ou. No [CustomConfigurationInput](https://docs.aws.amazon.com/bedrock-agentcore-control/latest/APIReference/API_CustomConfigurationInput.html)objeto, você pode especificar uma etapa na estratégia a ser substituída.

Na configuração da etapa a ser substituída (por exemplo, [UserPreferenceOverrideExtractionConfigurationInput](https://docs.aws.amazon.com/bedrock-agentcore-control/latest/APIReference/API_UserPreferenceOverrideExtractionConfigurationInput.html)), 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](#long-term-custom-strategy-configuration-example).

## Exemplo de configuração
<a name="long-term-custom-strategy-configuration-example"></a>

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