

# Get started with AgentCore Memory

Amazon Bedrock AgentCore Memory lets you create and manage AgentCore Memory resources that store conversation context for your AI agents. This getting started guides you through installing dependencies and implementing both short-term and long-term memory features. The instructions use the AgentCore CLI.

The steps are as follows:

1. Create an AgentCore Memory containing a semantic strategy

1. Write events (conversation history) to the memory resource

1. Retrieve memory records from long term memory

For other examples, see [Amazon Bedrock AgentCore Memory examples](memory-examples.md).

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

Before starting, make sure you have:
+  ** AWS Account** with credentials configured ( `aws configure` )
+  **Python 3.10\+** installed
+ Node.js 20.12 or later installed (for the AgentCore CLI)

To get started with Amazon Bedrock AgentCore Memory, install the dependencies, create an AgentCore CLI project, and set up a virtual environment. The following commands can be run directly in the terminal.

```bash
npm install -g @aws/agentcore

agentcore create --name MemoryQuickstart --template empty

cd MemoryQuickstart

python -m venv .venv

source .venv/bin/activate

pip install bedrock-agentcore
```

The AgentCore CLI provides commands for creating and inspecting memory resources. Use `agentcore add memory` to declare a memory, `agentcore deploy` to provision it, and `agentcore memory` to inspect deployed memories. Use the AgentCore Python SDK (`bedrock-agentcore`) to write events.

**Note**  
The AgentCore CLI helps you create, deploy, and inspect memory resources. For direct service API operations, see the Boto3 documentation: [bedrock-agentcore-control](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/bedrock-agentcore-control.html) and [bedrock-agentcore](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/bedrock-agentcore.html).

 **Full example:** See the [Amazon Bedrock AgentCore samples](https://github.com/awslabs/amazon-bedrock-agentcore-samples/tree/main/01-features/04-manage-context-of-your-agent/memory) that demonstrate steps 1-3.

## Step 1: Create an AgentCore Memory
<a name="memory-create-resource"></a>

You need an AgentCore Memory to start storing information for your agent. By default, memory events (which we refer to as short-term memory) can be written to an AgentCore Memory. For insights to be extracted and placed into long term memory records, the resource requires a *memory strategy* which is a configuration that defines how conversational data should be processed, and what information to extract (such as facts, preferences, or summaries).

In this step, you create an AgentCore Memory with a semantic strategy so that both short term and long term memory can be utilized. This will take 2-3 minutes. You can also create AgentCore Memory resources in the AWS console.

Create memory with semantic strategy:

**Example**  

1. 

   ```bash
   agentcore add memory --name CustomerSupportSemantic --strategies SEMANTIC
   
   agentcore deploy
   ```

1. Run `agentcore add memory` to open the Memory wizard.

1. Enter the memory name, such as `CustomerSupportSemantic`.

1. Use the arrow keys and Space to select `SEMANTIC`, then press Enter.

1. Keep the default event retention of 30 days, review the configuration, and press Enter to add the memory.  
![Choosing a Memory name, extraction strategies, and retention period, then reviewing the configuration.](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/images/tui/add-memory.gif)

1. Press Ctrl\+C to exit the TUI, then run `agentcore deploy` to provision the memory in AWS.

After deployment, run `agentcore status --json` and copy the memory `arn`. The memory ID is the part of the ARN after `memory/`. Then check that the memory status is `ACTIVE`:

```bash
agentcore status --json
agentcore memory get --id <memory-id>
```

## Step 2: Write events to memory
<a name="memory-write-events"></a>

You can write events to an AgentCore Memory as short-term memory and extracts insights for long-term memory.

Writing events to memory has multiple purposes. First, event contents (most commonly conversation history) are stored as short-term memory. Second, relevant insights are pulled from events and written into memory records as a part of long-term memory.

The memory resource id, actor id, and session id are required to create an event. In this step, you create three events, simulating messages between an end user and a chat bot. Replace `<your-memory-id>` with the memory ID from Step 1.

```python
from bedrock_agentcore.memory import MemorySessionManager
from bedrock_agentcore.memory.constants import ConversationalMessage, MessageRole

# The memory ID from Step 1
memory_id = "<your-memory-id>"

# Create a session to store memory events
session_manager = MemorySessionManager(
    memory_id=memory_id,
    region_name="us-west-2")

session = session_manager.create_memory_session(
    actor_id="User1",
    session_id="OrderSupportSession1"
)

# Write memory events (conversation turns)
session.add_turns(
    messages=[
        ConversationalMessage(
            "Hi, how can I help you today?",
            MessageRole.ASSISTANT)],
)

session.add_turns(
    messages=[
        ConversationalMessage(
            "Hi, I am a new customer. I just made an order, but it hasn't arrived. The Order number is #35476",
            MessageRole.USER)],
)

session.add_turns(
    messages=[
        ConversationalMessage(
            "I'm sorry to hear that. Let me look up your order.",
            MessageRole.ASSISTANT)],
)
```

You can get events (turns) for a specific actor after they’ve been written.

```python
# Get the last k turns in the session
turns = session.get_last_k_turns(k=5)

for turn in turns:
    print(f"Turn: {turn}")
```

In this case, you can see the last three events for the actor and session.

## Step 3: Retrieve records from long term memory
<a name="memory-retrieve-records"></a>

After the events were written to the memory resource, they were analyzed and useful information was sent to long term memory. Since the memory contains a semantic long term memory strategy, the system extracts and stores factual information.

You can list all memory records with:

```python
# List all memory records
memory_records = session.list_long_term_memory_records(
    namespace_path="/"
)

for record in memory_records:
    print(f"Memory record: {record}")
    print("--------------------------------------------------------------------")
```

Or ask for the most relevant information as part of a semantic search:

```python
# Perform a semantic search
memory_records = session.search_long_term_memories(
    query="can you summarize the support issue",
    namespace_path="/",
    top_k=3
)
```

Important information about the user is likely stored is long term memory. Agents can use long term memory rather than a full conversation history to make sure that LLMs are not overloaded with context.

## Adding memory to an existing agent
<a name="memory-add-to-existing-agent"></a>

A Python Strands project that you scaffold with `agentcore create --name MyProject --template agent-python-strands` includes `app/agent/memory/session.py`, and its `main.py` already uses it. The module reads the `MEMORY_AGENTMEMORY_ID` environment variable, which belongs to the `agentMemory` memory that the template adds. If the project has no memory with that name, for example because you removed it, add it with the strategies that the template uses by default, and deploy:

```bash
agentcore add memory --name agentMemory --strategies SEMANTIC,USER_PREFERENCE,SUMMARIZATION,EPISODIC
agentcore deploy
```

For a Strands agent that the AgentCore CLI did not scaffold with memory, follow these steps:

1. Add a memory resource to your project:

   ```bash
   agentcore add memory --name MyMemory --strategies SEMANTIC,SUMMARIZATION
   agentcore deploy
   ```

1. Create the `memory/` directory in your agent:

   ```bash
   mkdir -p app/MyAgent/memory
   ```

1. Create `app/MyAgent/memory/session.py` :

   ```python
   import os
   from typing import Optional
   from bedrock_agentcore.memory.integrations.strands.config import AgentCoreMemoryConfig, RetrievalConfig
   from bedrock_agentcore.memory.integrations.strands.session_manager import AgentCoreMemorySessionManager
   
   MEMORY_ID = os.getenv("MEMORY_MYMEMORY_ID")
   REGION = os.getenv("AWS_REGION")
   
   def get_memory_session_manager(session_id: str, actor_id: str) -> Optional[AgentCoreMemorySessionManager]:
       if not MEMORY_ID:
           return None
   
       retrieval_config = {
           f"/users/{actor_id}/facts": RetrievalConfig(top_k=3, relevance_score=0.5),
           f"/summaries/{actor_id}/{session_id}": RetrievalConfig(top_k=3, relevance_score=0.5)
       }
   
       return AgentCoreMemorySessionManager(
           AgentCoreMemoryConfig(
               memory_id=MEMORY_ID,
               session_id=session_id,
               actor_id=actor_id,
               retrieval_config=retrieval_config,
           ),
           REGION
       )
   ```

1. Update your `main.py` to use the session manager:

   ```python
   from memory.session import get_memory_session_manager
   
   @app.entrypoint
   async def invoke(payload, context):
       session_id = getattr(context, 'session_id', 'default-session')
       user_id = getattr(context, 'user_id', 'default-user')
   
       agent = Agent(
           model=load_model(),
           session_manager=get_memory_session_manager(session_id, user_id),
           system_prompt="You are a helpful assistant.",
       )
   
       response = agent(str(payload.get("prompt", "")))
       return response
   ```

1. Deploy the updated project:

   ```bash
   agentcore deploy
   ```

**Note**  
Each memory resource gets the environment variables `MEMORY_<NAME>_ID` and `MEMORY_<NAME>_ARN`, where `<NAME>` is the memory name in uppercase. They are available in your agent’s runtime environment after deployment.

## Cleanup
<a name="memory-cleanup"></a>

When you’re done with the memory resource, you can delete it:

```bash
agentcore remove memory --name CustomerSupportSemantic
agentcore deploy
```

## Next steps
<a name="memory-next-steps"></a>

Consider the following:
+  [Add another strategy](long-term-enabling-long-term-memory.md#long-term-adding-strategies-to-existing-memory) to your memory resource.
+  [Enable observability](memory-observability.md) for more visibility into how memory is working
+ Look at further [examples](memory-examples.md).