

# Use long-term memory
<a name="long-term-memory-long-term"></a>

Long-term memory is enabled by adding one or more memory strategies to a memory resource. These strategies define what kind of information is extracted from conversations and stored persistently. This section guides you through configuring built-in and built-in with overrides strategies to enable long-term memory for your agent.

This section provides examples using the AWS SDK (Boto3). For complete end-to-end examples, see [Amazon Bedrock AgentCore Memory examples](memory-examples.md).

**Topics**
+ [

# Enable long-term memory
](long-term-enabling-long-term-memory.md)
+ [

# Specify long-term memory organization with namespaces
](specify-long-term-memory-organization.md)
+ [

# Configure built-in strategies
](long-term-configuring-built-in-strategies.md)
+ [

# Configure a custom strategy
](long-term-configuring-custom-strategies.md)
+ [

# Save and retrieve insights
](long-term-saving-and-retrieving-insights.md)
+ [

# Retrieve memory records
](long-term-retrieve-records.md)
+ [

# List memory records
](long-term-list-memory-records.md)
+ [

# Delete memory records
](long-term-delete-memory-records.md)
+ [

# Redrive failed ingestions
](long-term-redrive.md)

# Enable long-term memory
<a name="long-term-enabling-long-term-memory"></a>

You can enable long-term memory in two ways: by adding strategies when you first [create an AgentCore Memory](memory-create-a-memory-store.md) , or by updating an existing resource to include them.

## Creating a new memory with long-term strategies
<a name="long-term-creating-new-memory-with-strategies"></a>

The most direct method is to include strategies when you create a new AgentCore Memory. After calling `create_memory` , you must wait for the AgentCore Memory status to become `ACTIVE` before you can use it.

**Example**  

1. 

   ```
   agentcore add memory --name PersonalizedShoppingAgentMemory --strategies USER_PREFERENCE
   agentcore deploy
   ```

1. Run `agentcore` to open the TUI, then select **add** and choose **Memory** :

1. Select the **User preference** strategy:  
![\[Memory wizard: select USER_PREFERENCE strategy\]](http://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/images/tui/memory-add-strategies.png)

1. Review the configuration and press Enter to confirm:  
![\[Memory wizard: confirm memory configuration\]](http://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/images/tui/memory-add-confirm.png)

   Then run `agentcore deploy` to provision the memory in AWS.

## Adding long-term strategies to an existing AgentCore Memory
<a name="long-term-adding-strategies-to-existing-memory"></a>

To add long-term capabilities to an existing AgentCore Memory, you use the `update_memory` operation. You can add, modify or delete strategies for an existing memory.

**Note**  
The AgentCore CLI supports creating and managing memory resources. To update memory strategies on an existing memory, use the AWS SDK.

 **Example Add a Session Summary strategy to an existing AgentCore Memory** 

```
import boto3

# Initialize the Boto3 client for control plane operations
control_client = boto3.client('bedrock-agentcore-control', region_name='us-west-2')

# Assume 'memory_id' is the ID of an existing AgentCore Memory that has no strategies attached to it
memory_id = "your-existing-memory-id"

# Update the memory to add a summary strategy
response = control_client.update_memory(
    memoryId=memory_id,
    memoryStrategies=[
        {
            'summaryMemoryStrategy': {
                'name': 'SessionSummarizer',
                'description': 'Summarizes conversation sessions for context',
                'namespaceTemplates': ['/summaries/{actorId}/{sessionId}/']
            }
        }
    ]
)

print(f"Successfully submitted update for memory ID: {memory_id}")

# Validate strategy was added to the memory
memory_response = control_client.get_memory(memoryId=memory_id)
strategies = memory_response.get('memory', {}).get('strategies', [])
print(f"Memory strategies for memoryID: {memory_id} are: {strategies}")
```

**Note**  
Long-term memory records will only be extracted from conversational events that are stored **after** a new strategy becomes `ACTIVE` . Conversations stored before a strategy is added will not be processed for long-term memory.

# Specify long-term memory organization with namespaces
<a name="specify-long-term-memory-organization"></a>

When you [create](memory-create-a-memory-store.md) an AgentCore Memory, use a namespace to specify where the [long-term memories](memory-types.md#memory-long-term-memory) for a [memory strategy](memory-strategies.md) are logically grouped. Every time a new long-term memory is extracted using the memory strategy, it is saved under the namespace you set. This means that all long-term memories are scoped to their specific namespace, keeping them organized and preventing any mix-ups with other users or sessions. You should use a hierarchical format separated by forward slashes `/` . This helps keep memories organized clearly. As needed, you can choose to use the following pre-defined variables within braces in the namespace based on your application’s organization needs:
+  **actorId** – Identifies who the long-term memory belongs to.

  An actor refers to entity such as end users or agent/user combinations. For example, in a coding support chatbot, the actor is usually the developer asking questions. Using the actor ID helps the system know which user the memory belongs to, keeping each user’s data separate and organized.
+  **strategyId** – Shows which memory strategy is being used. This strategy identifier is auto-generated when you create an AgentCore Memory.
+  **sessionId** – Identifies which session or conversation the memory is from.

  A session is usually a single conversation or interaction period between the user and the AI agent. It groups all related messages and events that happen during that conversation.

For example, if you define the following namespace as the input to your strategy when creating an AgentCore Memory:

```
/strategy/{memoryStrategyId}/actor/{actorId}/session/{sessionId}/
```

After memory creation, this namespace might look like:

```
/strategy/summarization-93483043//actor/actor-9830m2w3/session/session-9330sds8
```

A namespace can have different levels of granularity:

 **Most granular Level of organization** 

 `/strategy/{memoryStrategyId}/actor/{actorId}/session/{sessionId}/` 

 **Granular at the actor Level across sessions** 

 `/strategy/{memoryStrategyId}/actor/{actorId}/` 

 **Granular at the strategy Level across actors** 

 `/strategy/{memoryStrategyId}/` 

 **Global across all strategies** 

 `/` 

For example code, see [Enable long-term memory](long-term-enabling-long-term-memory.md).

## Restrict access with IAM
<a name="memory-scope-iam"></a>

You can create IAM policies to restrict memory access by the scopes you define, such as actor, session, and namespace. Use the scopes as context keys in your IAM policies.

The following policy restricts access to retrieving memories to a specific namespace prefix. In this example, the policy allows access only to memories in namespaces starting with `summaries/agent1/` , such as `summaries/agent1/session1/` or `summaries/agent1/session2/`.

```
{
"Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "SpecificNamespaceAccess",
      "Effect": "Allow",
      "Action": [
        "bedrock-agentcore:RetrieveMemoryRecords"
      ],
      "Resource": "arn:aws:bedrock-agentcore:us-east-1:123456789012:memory/memory_id",
      "Condition": {
        "StringLike": {
          "bedrock-agentcore:namespace": "summaries/agent1/"
        }
      }
    }
  ]
}
```

# Configure built-in strategies
<a name="long-term-configuring-built-in-strategies"></a>

AgentCore Memory provides pre-configured, [built-in memory strategies](built-in-strategies.md) for common use cases.

**Topics**
+ [

## User preferences
](#long-term-user-preferences-strategy)
+ [

## Semantic
](#long-term-semantic-facts-strategy)
+ [

## Session summaries
](#long-term-session-summaries-strategy)
+ [

## Episodic
](#long-term-session-episodic-strategy)

## User preferences
<a name="long-term-user-preferences-strategy"></a>

The [user preferences](user-preference-memory-strategy.md) ( `UserPreferenceMemoryStrategy` ) strategy is designed to automatically identify and extract user preferences, choices, and styles from conversations. This lets your agent build a persistent profile of each user, leading to more personalized and relevant interactions.
+  **Example use case:** An e-commerce agent remembers a user’s favorite brands and preferred size, letting it offer tailored product recommendations in future sessions.

 **Configuration example:** 

```
import boto3

# Initialize the Boto3 client for control plane operations
control_client = boto3.client('bedrock-agentcore-control', region_name='us-west-2')

# Create memory resource with user preference strategy
response = control_client.create_memory(
    name="ECommerceAgentMemory",
    memoryStrategies=[
        {
            'userPreferenceMemoryStrategy': {
                'name': 'UserPreferenceExtractor',
                'namespaceTemplates': ['/users/{actorId}/preferences/']
            }
        }
    ]
)
```

## Semantic
<a name="long-term-semantic-facts-strategy"></a>

The [Semantic](semantic-memory-strategy.md) ( `SemanticMemoryStrategy` ) memory strategy is engineered to identify and extract key pieces of factual information and contextual knowledge from conversational data. This lets your agent build a persistent knowledge base about important entities, events, and details discussed during an interaction.
+  **Example use case:** A customer support agent remembers that order \$1ABC-123 is related to a specific support ticket, so the user doesn’t have to provide the order number again when following up.

 **Configuration example:** 

```
import boto3

# Initialize the Boto3 client for control plane operations
control_client = boto3.client('bedrock-agentcore-control', region_name='us-west-2')

# Create memory resource with semantic strategy
response = control_client.create_memory(
    name="SupportAgentFactMemory",
    memoryStrategies=[
        {
            'semanticMemoryStrategy': {
                'name': 'FactExtractor',
                'namespaceTemplates': ['/support_cases/{sessionId}/facts/']
            }
        }
    ]
)
```

## Session summaries
<a name="long-term-session-summaries-strategy"></a>

The [session summaries](summary-strategy.md) ( `SummaryMemoryStrategy` ) memory strategy creates condensed, running summaries of conversations as they happen within a single session. This captures the key topics and decisions, letting an agent quickly recall the context of a long conversation without needing to re-process the entire history.
+  **Example use case:** After a 30-minute troubleshooting session, the agent can access a summary like, "User reported issue with software v2.1, attempted a restart, and was provided a link to the knowledge base article."

 **Configuration example:** 

```
import boto3

# Initialize the Boto3 client for control plane operations
control_client = boto3.client('bedrock-agentcore-control', region_name='us-west-2')

# Create memory resource with summary strategy
response = control_client.create_memory(
    name="TroubleshootingAgentSummaryMemory",
    memoryStrategies=[
        {
            'summaryMemoryStrategy': {
                'name': 'SessionSummarizer',
                'namespaceTemplates': ['/summaries/{actorId}/{sessionId}/']
            }
        }
    ]
)
```

## Episodic
<a name="long-term-session-episodic-strategy"></a>

The [episodic](episodic-memory-strategy.md) ( `EpisodicStrategy` ) memory strategy captures interactions as structured episodes consisting of scenarios, intents, thoughts, actions taken, outcomes, and artifacts. With this strategy, reflections are also made across episodes to extract broader insights, letting an agent learn and apply successful patterns from prior interactions to new interactions.
+  **Example use case:** A customer support agent logs interactions as episodes. The system captures which phrases and actions lead to successful interactions

 **Configuration example:** 

```
import boto3

# Initialize the Boto3 client for control plane operations
control_client = boto3.client('bedrock-agentcore-control', region_name='us-west-2')

# Create memory resource with episodic strategy
response = control_client.create_memory(
    name="MyMemory",
    memoryStrategies=[
        {
            'episodicMemoryStrategy': {
                'name': 'EpisodicStrategy',
                'namespaceTemplates': ['/strategy/{memoryStrategyId}/actors/{actorId}/sessions/{sessionId}/'],
                'reflection': {
                    'namespaceTemplates': ['strategy/{memoryStrategyId}/actors/{actorId}/']
                }
            }
        }
    ]
)
```

# Configure a custom strategy
<a name="long-term-configuring-custom-strategies"></a>

For advanced use cases, [built-in with overrides](memory-custom-strategy.md) strategies give you fine-grained control over the memory extraction process. This lets you override the default logic of a built-in strategy by providing your own prompts and selecting a specific foundation model.
+  **Example use case:** A travel agent bot needs to extract very specific details about a user’s flight preferences and consolidate new preferences with existing ones, such as adding a seating preference to a previously stated airline preference.

**Topics**
+ [

## Prerequisites
](#long-term-creating-memory-prerequisites)
+ [

## Creating the memory execution role
](#long-term-creating-memory-execution-role)
+ [

## Override a built-in strategy with the API
](#long-term-custom-strategy-configuration-api)
+ [

## Configuration example
](#long-term-custom-strategy-configuration-example)

## Prerequisites
<a name="long-term-creating-memory-prerequisites"></a>

To override a built-in memory strategy, you must fulfill the following prerequisites:
+ Have an AgentCore Memory service role. For more information, see [Creating the memory execution role](#long-term-creating-memory-execution-role).
+ If you plan to override the model for the prompt, you must have access to the model you choose to override with. For more information, see [Access Amazon Bedrock foundation models](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html) and [Amazon Bedrock capacity for built-in with overrides strategies](bedrock-capacity.md).

## Creating the memory execution role
<a name="long-term-creating-memory-execution-role"></a>

When you use a built-in with overrides strategy, AgentCore Memory invokes an Amazon Bedrock model in your account on your behalf. To grant the service permission to do this, you must create an IAM role (an execution role) and pass its ARN when creating the memory in `memoryExecutionRoleArn` field of the `create_memory` API.

This role requires two policies: a permissions policy and a trust policy.

### 1. Permissions policy
<a name="long-term-permissions-policy"></a>

Start by making sure you have an IAM role with the managed policy [AmazonBedrockAgentCoreMemoryBedrockModelInferenceExecutionRolePolicy](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/security-iam-awsmanpol.html#security-iam-awsmanpol-AmazonBedrockAgentCoreMemoryBedrockModelInferenceExecutionRolePolicy) , or create a policy with the following permissions:

```
{
"Version": "2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "bedrock:InvokeModel",
                "bedrock:InvokeModelWithResponseStream"
            ],
            "Resource": [
                "arn:aws:bedrock:*::foundation-model/*",
                "arn:aws:bedrock:*:*:inference-profile/*"
            ],
            "Condition": {
                "StringEquals": {
                    "aws:ResourceAccount": "123456789012"
                }
            }
        }
    ]
}
```

### 2. Trust policy
<a name="long-term-trust-policy"></a>

This role is assumed by the Service to call the model in your AWS account. Use the trust policy below when creating the role or when using the managed policy:

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

For information about creating an IAM role, see [IAM role creation](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html).

## Override a built-in strategy with the API
<a name="long-term-custom-strategy-configuration-api"></a>

To override a built-in strategy, use the `customMemoryStrategy` field when sending a [CreateMemory](https://docs.aws.amazon.com/bedrock-agentcore-control/latest/APIReference/API_CreateMemory.html) or [UpdateMemory](https://docs.aws.amazon.com/bedrock-agentcore-control/latest/APIReference/API_UpdateMemory.html) request. In the [CustomConfigurationInput](https://docs.aws.amazon.com/bedrock-agentcore-control/latest/APIReference/API_CustomConfigurationInput.html) object, you can specify a step in the strategy to override.

Within the configuration for the step to override (for example, [UserPreferenceOverrideExtractionConfigurationInput](https://docs.aws.amazon.com/bedrock-agentcore-control/latest/APIReference/API_UserPreferenceOverrideExtractionConfigurationInput.html) ), specify the following:
+  `appendToPrompt` – The prompt with which to replace the instructions in the system prompt (the output schema remains the same).
+  `modelId` – The ID of the Amazon Bedrock model to invoke with the prompt.

For example, you can send the following request body to override the user preference memory strategy with your own extraction and consolidation prompts, using the anthropic.claude-3-sonnet-20240229-v1:0 model):

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

For example custom prompts, see [Configuration example](#long-term-custom-strategy-configuration-example).

## Configuration example
<a name="long-term-custom-strategy-configuration-example"></a>

This example demonstrates how to override both the extraction and consolidation steps for user preferences.

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

# Save and retrieve insights
<a name="long-term-saving-and-retrieving-insights"></a>

Once you have configured an AgentCore Memory with at least one long-term memory strategy and the strategy is ACTIVE, the service will automatically begin processing conversational data to extract and store insights. This process involves two distinct steps: saving the raw conversation and then retrieving the structured insights after they have been processed.

## Step 1: Save conversational events to trigger extraction
<a name="long-term-step-1-save-conversational-events"></a>

The entire long-term memory process is triggered when you save conversational data to short-term memory using the `create_event` operation. Each time you record an event, you are providing new raw material for your active memory strategies to analyze.

**Important**  
Only events that are created **after** a memory strategy’s status becomes `ACTIVE` will be processed for long-term memory extraction. Any conversations stored before the strategy was added and activated will not be included.

The following example shows how to save a multi-turn conversation to a memory resource.

 **Example Save a conversation as a series of events** 

```
#'memory_id' is the ID of your memory resource with an active summary strategy.

from bedrock_agentcore.memory.session import MemorySessionManager
from bedrock_agentcore.memory.constants import ConversationalMessage, MessageRole
import time

actor_id = "User84"
session_id = "OrderSupportSession1"

# Create session manager
session_manager = MemorySessionManager(
    memory_id=memory_id,
    region_name="us-west-2"
)

# Create a session
session = session_manager.create_memory_session(
    actor_id=actor_id,
    session_id=session_id
)

print("Capturing conversational events...")

# Add all conversation turns
session.add_turns(
    messages=[
        ConversationalMessage("Hi, I'm having trouble with my order #12345", MessageRole.USER),
        ConversationalMessage("I am sorry to hear that. Let me look up your order.", MessageRole.ASSISTANT),
        ConversationalMessage("lookup_order(order_id='12345')", MessageRole.TOOL),
        ConversationalMessage("I see your order was shipped 3 days ago. What specific issue are you experiencing?", MessageRole.ASSISTANT),
        ConversationalMessage("The package arrived damaged", MessageRole.USER),
    ]
)

print("Conversation turns added successfully!")
```

## Step 2: Retrieve extracted insights
<a name="long-term-step-2-retrieve-extracted-insights"></a>

The extraction and consolidation of long-term memories is an **asynchronous process** that runs in the background. It may take a minute or more for insights from a new conversation to become available for retrieval. Your application logic should account for this delay.

To retrieve the structured insights, you use the `retrieve_memory_records` operation. This operation performs a powerful semantic search against the long-term memory store. You must provide the correct `namespace` that you defined in your strategy and a `searchQuery` that describes the information you are looking for.

The following example demonstrates how to wait for processing and then retrieve a summary of the conversation saved in the previous step.

 **Example Wait and retrieve a session summary** 

```
# 'session' is an existing session object that you created when adding the coversation turns
# session should be created on a memory resource with an active summary strategy.

# --- Example 1: Retrieve the user's shipping preference ---
memories = session.search_long_term_memories(
    namespace_prefix=f"/summaries/{actor_id}/{session_id}/",
    query="What problem did the user report with their order?",
    top_k=5
)

print(f"Found {len(memories)} memories:")
for memory_record in memories:
    print(f"Retrieved Issue Detail: {memory_record}")
    print("--------------------------------------------------------------------")

# Example Output:
# Retrieved Issue Detail: The user reported that their package for order #12345 arrived damaged.
```

# Retrieve memory records
<a name="long-term-retrieve-records"></a>

You can retrieve extracted memories using the [RetrieveMemoryRecords](https://docs.aws.amazon.com/bedrock-agentcore/latest/APIReference/API_RetrieveMemoryRecords.html) API. This operation lets you search extracted memory records based on semantic queries, making it easy to find relevant information from your agent’s memory.

## Required parameters
<a name="retrieve-records-parameters"></a>

The `RetrieveMemoryRecords` operation requires the following key parameters:

 **memoryId**   
The identifier of the memory resource containing the records you want to retrieve.

 **namespace**   
The namespace prefix of the namespace where the memory records are stored. The operation returns paginated memory records in namespaces that start with the provided prefix.

 **searchCriteria**   
A structure containing search parameters:  
+  *searchQuery* - The semantic query text used to find relevant memories (up to 10,000 characters).
+  *memoryStrategyId* (optional) - Limits the search to memories created by a specific strategy.
+  *topK* - The maximum number of most relevant results to return (default: 10, maximum: 100).

## Response format
<a name="retrieve-records-response"></a>

The operation returns a list of memory record summaries that match your search criteria. Each summary includes a *relevance score* , which is derived from the cosine similarity of embedding vectors. This score does **not** represent a percentage match, but instead measures how closely two vectors align in a high-dimensional space. Higher scores indicate greater relevance of the memory record to the search query. The results are paginated, with a default maximum of 100 results per page. You can use the `nextToken` parameter to retrieve additional pages of results.

## Best practices
<a name="retrieve-records-best-practices"></a>

When retrieving memories, consider the following best practices:
+ Craft specific search queries that clearly describe the information you’re looking for.
+ Use the `topK` parameter to control the number of results based on your application’s needs.
+ When working with large memories, implement pagination to efficiently process all relevant results.
+ Consider filtering by `memoryStrategyId` when you need memories from a specific extraction strategy.

Once retrieved, these memory records can be incorporated into your agent’s context, enabling more personalized and contextually aware responses.

# List memory records
<a name="long-term-list-memory-records"></a>

The [ListMemoryRecords](https://docs.aws.amazon.com/bedrock-agentcore/latest/APIReference/API_ListMemoryRecords.html) operation lets you retrieve memory records from a namespace prefix without performing a semantic search. This is useful when you want to browse all memory records under a namespace hierarchy or when you need to retrieve records based on criteria other than semantic relevance.

# Delete memory records
<a name="long-term-delete-memory-records"></a>

The [DeleteMemoryRecord](https://docs.aws.amazon.com/bedrock-agentcore/latest/APIReference/API_DeleteMemoryRecord.html) API removes individual memory records from your AgentCore Memory, giving you control over what information persists in your application’s memory. This API helps maintain data hygiene by letting selective removal of outdated, sensitive, or irrelevant information while preserving the rest of your memory context.

# Redrive failed ingestions
<a name="long-term-redrive"></a>

Extraction from short-term memory to long-term memory is usually automatic. If extraction from short-term memory to long-term memory is unsuccessful for any reason, AgentCore Memory attempts to address the issue. If issues persist, developer intervention may be needed and the failed jobs are moved to a dedicated queue for your memory resource. One example is if your account is ingesting to long-term memory at a greater rate than what is allowed. In this case, you should wait until traffic is lower and manually redrive the impacted jobs.

You can call `ListMemoryExtractionJobs` to see any failed jobs and look at the failure reason code to see the reason for the failure. Call `StartMemoryExtractionJobs` to re-ingest the job into long-term memory. We recommend monitoring the vended metric `FailedExtraction` to be notified of any issues. This metric also has dimensions on StrategyId, Resource (the memory ARN), and StrategyType. AgentCore Memory emits a count of this metric whenever a extraction job fails and is written to the extraction jobs storage.

For built-in strategies, the only failure scenario is hitting the ingestion limit. For built-in with override, there are additional failure scenarios, including issues with the model you’ve selected to use in your account or the permissions you’ve granted to AgentCore Memory.


| Failure Reason Code | Description | Recommended mitigation | 
| --- | --- | --- | 
|   `LTM_RATE_EXCEEDED`   |  This account has exceeded the allocated tokens per minute quota for long-term memory processing  |  Through Service Quotas, request a higher limit for the Bedrock Agentcore quota "Tokens per minute for long-term memory extraction". Then invoke the StartMemoryExtractionJob API on the failed extraction’s jobID.  | 
|   `CUSTOM_MODEL_BEDROCK_ACCESS_DENIED`   |  The memoryExecutionRoleArn provided during CreateMemory lacks adequate permissions to invoke all of the model IDs provided in the custom strategies attached to the memory  |  Ensure that the role has the permissions and trust policy as defined here and add any missing permissions. Or call UpdateMemory to switch to a different role with adequate permissions. Then invoke the StartMemoryExtractionJobs API on the failed extraction’s jobID.  | 
|   `CUSTOM_MODEL_BEDROCK_INTERNAL_ERROR`   |  The service received an internal error from Bedrock when attempting to invoke the model provided in the custom strategy.  |  This could be a temporary service error from Bedrock. Try again later by invoking the StartMemoryExtractionJobs API on the failed extraction’s jobID.  | 
|   `CUSTOM_MODEL_BEDROCK_THROTTLING`   |  The service received a throttling exception from Bedrock when attempting to invoke the model provided in the custom strategy.  |  Ensure that your account has requested adequate TPM and RPM quota for that model from Bedrock. Invoke the StartMemoryExtractionJobs API on the failed extraction’s jobID after quota increase or during low-traffic hours.  | 
|   `CUSTOM_MODEL_BEDROCK_MODEL_ERROR`   |  The service received a Model Error Exception from Bedrock when attempting to invoke the model provided in the custom strategy.  |  This is usually a temporary service error from Bedrock. Try again later by invoking the StartMemoryExtractionJobs API on the failed extraction’s jobID.  | 
|   `CUSTOM_MODEL_BEDROCK_MODEL_TIMEOUT`   |  The service received a Model Timeout Exception from Bedrock when attempting to invoke the model provided in the custom strategy.  |  This occurs when the model processing time exceeds its timeout. Consider switching to a faster model before invoking StartMemoryExtractionJobs API on the failed extraction’s jobID.  | 
|   `CUSTOM_MODEL_BEDROCK_RESOURCE_NOT_FOUND`   |  The service received a Resource Not Found from Bedrock when attempting to invoke the model provided in the custom strategy.  |  Ensure that the modelID provided in any custom strategies associated with the memory is correct. Call UpdateMemory to update those values if necessary. Then invoke the StartMemoryExtractionJobs API on the failed extraction’s jobID.  | 
|   `CUSTOM_MODEL_BEDROCK_MODEL_NOT_READY`   |  The service received a Model Not Ready from Bedrock when attempting to invoke the model provided in the custom strategy.  |  Wait for the model to be in a ready state. Refer to Bedrock documentation for more details. Then invoke the StartMemoryExtractionJobs API on the failed extraction’s jobID.  | 
|   `CUSTOM_MODEL_BEDROCK_SERVICE_UNAVAILABLE`   |  The service received Service Unavailable from Bedrock when attempting to invoke the model provided in the custom strategy.  |  This is usually a temporary service error from Bedrock. Try again later by invoking the StartMemoryExtractionJobs API on the failed extraction’s jobID.  | 
|   `CUSTOM_MODEL_BEDROCK_VALIDATION_EXCEPTION`   |  The service received Validation Exception from Bedrock when attempting to invoke the model provided in the custom strategy.  |  Ensure that the modelID provided in any custom strategies associated with the memory is correct. Call UpdateMemory to update those values if necessary. Then invoke the StartMemoryExtractionJobs API on the failed extraction’s jobID.  | 