Sitemap
AWS Tip

Best AWS, DevOps, Serverless, and more from top Medium writers .

Getting Started with Amazon Bedrock AgentCore Memory

11 min readOct 5, 2026

--

Press enter or click to view image in full size

Introduction

AI agents are stateless by default. Every interaction starts from zero, with no knowledge of previous conversations. This creates a frustrating experience for users who have to repeat themselves, and the agent cannot learn preferences or track ongoing issues across sessions.

Amazon Bedrock AgentCore Memory solves this problem by providing a fully managed memory service for AI agents. It handles both short-term memory (conversation turns within a session) and long-term memory (insights extracted and persisted across sessions). You do not need to build or manage any infrastructure for this.

This article is part of a series I am writing about different aspects of Amazon Bedrock AgentCore. Here, we focus on how to use Memory to give agents the ability to remember information across conversations. For a broader understanding of AgentCore and its components, check out the other articles in this series:

In this article, we explore Memory from two perspectives:

  • First, we use Memory locally via Python scripts, demonstrating how to write conversation events and retrieve extracted insights programmatically.
  • Then, we enable Memory in the car dealership Harness introduced in the first article and show the agent remembering customer preferences across sessions.

What is AgentCore Memory?

AgentCore Memory is one of the modular services in Amazon Bedrock AgentCore. It provides two types of memory:

Short-term memory stores turn-by-turn interactions within a single session. This lets agents maintain immediate context. For example, when a customer asks “Do you have any red cars?” and follows up with “What about in the SUV category?”, the agent uses short-term memory to understand that the customer is still asking about red cars.

Long-term memory automatically extracts and stores key insights from conversations across multiple sessions. For example, if a customer mentions they have a budget of $25,000 and prefer SUVs, the agent stores these preferences and can use them proactively in future interactions without the customer needing to repeat themselves.

How It Works

  1. You create a memory resource with one or more strategies
  2. Your agent writes events (conversation turns) to the memory
  3. AgentCore automatically analyzes those events and extracts relevant insights into long-term memory
  4. Your agent can later retrieve those insights via listing or semantic search

Memory Strategies

Strategies define what information AgentCore extracts from conversations:

  • Semantic — Extracts factual information and stores it for semantic search retrieval
  • User Preferences — Identifies and stores user preferences, choices, and styles
  • Session Summaries — Creates condensed summaries of conversation sessions

Prerequisites

  • AWS account with credentials configured
  • IAM user or role with permissions to use Amazon Bedrock AgentCore Memory. For details, see the Memory getting started guide
  • Python 3.12 installed
  • AWS Region where AgentCore is available (us-east-1, us-west-2, ap-southeast-2, or eu-central-1)

Step 1: Clone the Repository and Install Dependencies

Clone the companion repository and set up the Python environment:

git clone https://github.com/biagolini/PythonAwsBedrockAgentCoreMemory.git
cd PythonAwsBedrockAgentCoreMemory
python3.12 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

On Windows, replace the activation command with .venv\Scripts\activate.

Step 2: Create a Memory Resource

A memory resource needs at least one strategy to extract long-term insights.

2.1 Navigate to Memory

2.1.1. Open the Amazon Bedrock AgentCore console

2.1.2. In the left navigation pane, under Build, click Memory

2.1.3. Click the Create memory button

Press enter or click to view image in full size
Memory console showing the navigation path and Create memory button
Memory console showing the navigation path and Create memory button

2.2 Configure the Memory

2.2.1. In the Memory name field, enter car_memory. Valid characters are a-z, A-Z, 0-9, and _ (underscore). Maximum 48 characters.

2.2.2. In the Short-term memory (raw event) expiration field, set the duration in days. This defines how long short-term memory events are retained before expiring. Set to 90 days for this tutorial (valid range: 3 to 365 days).

2.2.3. Under Long-term memory extraction strategies, click Add strategy in the Built-in strategies section. The available extraction strategies are:

  • Summarization — Condenses interactions into key insights. Recommended for retaining core points from lengthy conversations without storing every detail.
  • Semantic — Extracts general factual knowledge, concepts, and meanings from conversations. Recommended for building a knowledge base of facts and relationships mentioned by users.
  • User preferences — Extracts user behavior patterns and personal choices. Recommended for personalizing future interactions based on stated preferences (colors, budgets, styles).
  • Episodic — Transforms events into structured episodes to help agents learn from past actions. Recommended for action-oriented agents that need to improve based on operational experience.

For more details, see Memory strategies.

For this tutorial, select Semantic — it will extract facts like customer budget, preferred vehicle type, and other details from the conversation.

2.2.4. In the Strategy name field, enter CustomerFacts

2.2.5. For the Namespace template, keep the default value /strategies/{memoryStrategyId}/actors/{actorId}/. The namespace defines how long-term memories are organized. Variables in braces are resolved automatically: {memoryStrategyId} identifies which strategy extracted the memory, and {actorId} identifies who the memory belongs to. This means each customer's extracted facts are stored separately, preventing data from mixing between different users. For more details on namespace organization, see Memory organization in AgentCore Memory.

2.2.6. Click Create memory

The creation page also shows two additional strategy sections that we leave empty for this tutorial:

  • Built-in strategy with override — Allows you to override the default extraction logic by providing your own prompts and selecting a specific foundation model. The model invocation runs in your account. Useful when you need fine-grained control over what gets extracted (for example, extracting very specific flight preferences for a travel agent). For details, see Configure a custom strategy.
  • Self-managed strategy — Gives you complete control over the memory processing pipeline. AgentCore stores events and delivers batched payloads to your S3 bucket with SNS notifications, and you define the extraction logic in your own environment. Useful for complex pipelines that require custom ML models or business logic beyond what built-in strategies provide. For details, see Self-managed strategy.

For most use cases, built-in strategies (configured above) are sufficient.

Press enter or click to view image in full size
Create memory form showing name, expiration, and strategy options

Wait for the memory status to become Active (this typically takes 2–3 minutes).

2.3 Copy the Memory ID

After creation, the console displays the memory details page. Copy the Memory ID value. You will use this identifier in the next steps.

Get Carlos Biagolini’s stories in your inbox

Join Medium for free to get updates from this writer.

The details page also shows integration code snippets (Python, TypeScript, JavaScript), long-term memory strategies, and observability metrics.

Press enter or click to view image in full size
Memory details page showing Memory ID
Memory details page showing Memory ID

Step 3: Write Conversation Events

Now let’s simulate a conversation between a customer and our car dealership agent, and write it to memory.

3.1 Configure Environment Variables

Copy the example environment file and add your Memory ID:

cp .env.example .env

Edit .env:

AWS_REGION=us-east-1
MEMORY_ID=<your-memory-id>

Replace <your-memory-id> with the Memory ID you copied from the console in Step 2.3.

3.2 Run the Script

import os
import sys
from dotenv import load_dotenv

load_dotenv()

REGION = os.getenv("AWS_REGION", "us-east-1")
MEMORY_ID = os.getenv("MEMORY_ID")

if not MEMORY_ID:
print("Error: MEMORY_ID not set in .env file")
sys.exit(1)

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

session_manager = MemorySessionManager(
memory_id=MEMORY_ID,
region_name=REGION
)

session = session_manager.create_memory_session(
actor_id="customer-001",
session_id="visit-001"
)

print("Writing conversation to memory...")

session.add_turns(
messages=[
ConversationalMessage(
"Welcome to our dealership! How can I help you find your next car?",
MessageRole.ASSISTANT
)
]
)

session.add_turns(
messages=[
ConversationalMessage(
"I'm looking for a reliable SUV under $25,000. I prefer something "
"with low mileage, ideally in white or silver.",
MessageRole.USER
)
]
)

session.add_turns(
messages=[
ConversationalMessage(
"Based on your budget and color preferences, I'd recommend looking at "
"our Toyota RAV4 2022 in silver with 28,000 miles, or the Honda CR-V 2021 "
"in white with 32,000 miles. Both are well within your budget.",
MessageRole.ASSISTANT
)
]
)

print("Conversation written to memory.")

print("\n--- Short-term Memory (last turns) ---")
turns = session.get_last_k_turns(k=5)
for turn in turns:
for message in turn:
role = message["role"]
text = message["content"]["text"]
print(f" [{role}] {text}")

Run the script:

python write_events.py

This writes a conversation where a customer asks about SUVs and mentions their budget. AgentCore stores the turns as short-term memory and begins analyzing them to extract insights for long-term memory.

Expected output:

Writing conversation to memory...
Conversation written to memory.

--- Short-term Memory (last turns) ---
[ASSISTANT] Based on your budget and color preferences, I'd recommend looking at our Toyota RAV4 2022 in silver with 28,000 miles, or the Honda CR-V 2021 in white with 32,000 miles. Both are well within your budget.
[USER] I'm looking for a reliable SUV under $25,000. I prefer something with low mileage, ideally in white or silver.
[ASSISTANT] Welcome to our dealership! How can I help you find your next car?

Step 4: Retrieve Long-term Memory

After writing events, AgentCore processes them and extracts relevant facts into long-term memory. This happens asynchronously and typically takes 20–40 seconds.

import os
import sys
import time
from dotenv import load_dotenv

load_dotenv()

REGION = os.getenv("AWS_REGION", "us-east-1")
MEMORY_ID = os.getenv("MEMORY_ID")

if not MEMORY_ID:
print("Error: MEMORY_ID not set in .env file")
sys.exit(1)

from bedrock_agentcore.memory import MemorySessionManager

session_manager = MemorySessionManager(
memory_id=MEMORY_ID,
region_name=REGION
)

session = session_manager.create_memory_session(
actor_id="customer-001",
session_id="visit-001"
)

print("Waiting for long-term memory extraction (about 30 seconds)...")
time.sleep(30)

print("\n--- Long-term Memory Records ---")
memory_records = session.list_long_term_memory_records(
namespace_path="/"
)

for i, record in enumerate(memory_records, 1):
text = record["content"]["text"]
print(f" {i}. {text}")

print("\n--- Semantic Search: 'budget' ---")
search_results = session.search_long_term_memories(
query="budget",
namespace_path="/",
top_k=3
)

for i, result in enumerate(search_results, 1):
text = result["content"]["text"]
score = result.get("score", 0)
print(f" {i}. [score: {score:.2f}] {text}")

Run the script:

python retrieve_memory.py

Expected output:

Writing conversation to memory...
Conversation written to memory.

--- Short-term Memory (last turns) ---
[ASSISTANT] Based on your budget and color preferences, I'd recommend looking at our Toyota RAV4 2022 in silver with 28,000 miles, or the Honda CR-V 2021 in white with 32,000 miles. Both are well within your budget.
[USER] I'm looking for a reliable SUV under $25,000. I prefer something with low mileage, ideally in white or silver.
[ASSISTANT] Welcome to our dealership! How can I help you find your next car?
((.venv) ) biagolini@workstation code % python retrieve_memory.py
Waiting for long-term memory extraction (about 30 seconds)...
--- Long-term Memory Records ---
--- Semantic Search: 'budget' ---

Notice that we never explicitly told the system what to remember. The semantic strategy analyzed the conversation and identified the important facts on its own. In future interactions, the agent can retrieve these facts without replaying the entire conversation history.

Step 5: Integrate Memory with the Harness

Now we enable Memory in the car dealership Harness so the agent automatically remembers customer information across sessions.

5.1 Edit the Harness

5.1.1. Navigate to Amazon Bedrock AgentCore > Harness

5.1.2. Click on your Harness name (car_agent) to open its details page

5.1.3. Click Edit in the top-right area

5.1.4. In the Memory section, enable Memory and select your memory resource (e.g. car_memory)

5.1.5. Click Save Harness and wait for the status to return to Ready

Press enter or click to view image in full size
Harness edit panel showing Memory configuration
Harness edit panel showing Memory configuration

5.2 Test Memory Across Sessions

5.2.1. Once the Harness is Ready, click the Test Harness button

5.2.2. In the test interface, notice the Actor ID field below the Memory section. This field identifies which user the memory belongs to. Each actor gets isolated short-term and long-term memory, meaning different customers will not see each other’s data. For this test, enter customer-abc123 as the Actor ID.

5.2.3. In the first session, ask the agent for advice:

Hi, my name is Bob. I'm thinking about buying a used car but I'm not sure if I should go for an SUV or a Sedan. Can you explain the main differences between them and the strengths and weaknesses of each?
Press enter or click to view image in full size
Harness test showing the first session with memory
Harness test showing the first session with memory

5.2.4. Close this session. Start a new session (click New session > Stop current session and create new session). Keep the same Actor ID (customer-abc123) so the agent can retrieve the memories from the previous session.

5.2.5. In the new session, ask a question without repeating your preferences:

Do you have anything that might work for me?

5.2.6. Since we have not configured access to an inventory database, the agent will not be able to list specific cars. However, in the agent’s thinking blocks, you can observe that it retrieved information from the previous conversation (Bob’s interest in SUVs and Sedans). The agent will ask follow-up questions to refine the search, demonstrating that it remembers the context from the earlier session. To learn how to provide the agent with access to external tools like an inventory database, see the Gateway article.

Press enter or click to view image in full size
Harness test showing the second session with memory recall
Harness test showing the second session with memory recall

Step 6: Clean Up

If you do not plan to continue using the resources created in this tutorial, it is a good practice to remove them from your account. If you plan to use AgentCore Memory in production, check the AgentCore pricing page for current billing details.

To remove the resources:

  • Remove Memory from the Harness (edit the Harness, disable Memory, and save)
  • Navigate to Amazon Bedrock AgentCore > Memory, select your memory resource, and click Delete

Conclusion

In this article, you learned how to use Amazon Bedrock AgentCore Memory to give agents the ability to remember:

  • Short-term memory stores conversation turns within a session, maintaining immediate context.
  • Long-term memory automatically extracts facts and preferences from conversations and persists them across sessions.
  • Local invocation lets developers write events and retrieve insights programmatically using the MemorySessionManager.
  • Harness integration enables the agent to use Memory automatically, remembering customer preferences across sessions without any additional code.

The key insight is that you only write raw conversation turns. AgentCore handles the extraction of meaningful facts, preferences, and summaries into long-term memory automatically based on the strategies you configure. This is particularly powerful for the car dealership scenario: the agent can remember each customer’s budget, preferred vehicle type, color preferences, and past interactions, providing a personalized experience on every visit.

References

Stay Connected

If you found this article helpful and want to learn more about AWS, cloud architecture, AI, infrastructure as code, and cloud security, follow the author for future content and tutorials:

Stay tuned for more practical walkthroughs and solutions for cloud infrastructure and DevOps challenges.

Happy building on AWS! 🚀☁️

--

--

Carlos Biagolini
Carlos Biagolini

Written by Carlos Biagolini

Cloud Architect | Writing about AWS, AI/ML, and hands-on cloud solutions | AWS Community Builder

AWS Tip
AWS Tip

Published in AWS Tip

Best AWS, DevOps, Serverless, and more from top Medium writers .