Understanding How Amazon Bedrock AgentCore Memory Works by Running Short-Term and Long-Term Memory with Strands Agents

Understanding How Amazon Bedrock AgentCore Memory Works by Running Short-Term and Long-Term Memory with Strands Agents

How to let AI agents remember past conversations with Amazon Bedrock AgentCore Memory, with implementation examples. We cover the roles of short-term and long-term memory and tried integrating with Strands Agents.
2026.12.04

This page has been translated by machine translation. View original

Introduction

Hello! I'm Kosuke from the AI Business Division.

When developing agents, requests like "I want it to remember what I told it before" and "I want it to get smarter as I keep using it" come up often. Context within the same chat is retained as conversation history, but when you open a different chat, what you told it earlier is not carried over. To remember only the necessary points and keep updating them, you need a mechanism that extracts key points from the chat history and reflects them in later responses. Building this yourself involves many considerations, such as where to store the history, the summarization prompt, and vectorization for search.

Amazon Bedrock AgentCore Memory is a service that provides both this "short-term conversation history" and "long-term memory across sessions" as a managed service. It looks very convenient and useful, but I found it hard to grasp how terms such as events, strategies, and namespaces relate to each other just by reading the official documentation.

In this article, I create AgentCore Memory with CDK and connect it to a minimal Strands Agents agent. Then, by actually running it, I check what is stored where as short-term and long-term memory, and how each is retrieved.

What is AgentCore Memory

AgentCore Memory is a fully managed service that lets AI agents retain past interactions. Agents are inherently stateless, and unless state is stored externally, they cannot refer to past interactions. AgentCore Memory takes care of this state management.

There are two kinds of memory: short-term memory and long-term memory.

Figure 1: Relationship between short-term and long-term memory

Short-term memory stores the interactions within a single session without processing, so that the agent can keep the context of that session. Each user utterance and agent response is stored as an "event" and tied to a session ID. If you read the events with the same session ID again, you can restore the conversation in the order it occurred.

Long-term memory retains information extracted from interactions across multiple sessions. Only key points such as conversation summaries, facts and knowledge, and user preferences are stored, and each is recorded as a "memory record". Extraction runs asynchronously in the background after events are stored in short-term memory.

Correspondence of terms:

Term Meaning
Memory (memory resource) The resource that stores memory. Strategies and the retention period of short-term memory are configured here
Actor (actorId) The owner of the memory. Usually the end user
Session (sessionId) A single unit of conversation
Event A unit of short-term memory. Holds an utterance (USER / ASSISTANT) or structured data
Strategy A definition of what to extract as long-term memory. Built-in strategies include user preferences (User Preference), facts (Semantic), and summaries (Summary)
Namespace Where long-term memory records are stored. Hierarchical, separated by /, like /preferences/{actorId}/
Memory record A unit of long-term memory. Text of an extracted key point

Architecture we'll build

Figure 2: Architecture of the test environment and the flow of memory

  • AgentCore Memory: The retention period of short-term memory is 7 days, and only one long-term memory strategy, "User Preference", is configured
  • Strands Agents: A minimal agent with no tools
  • AgentCoreMemorySessionManager: A session manager for Strands Agents included in the bedrock-agentcore SDK. It stores utterances as events, and on every user utterance it searches long-term memory and inserts the results into the utterance
  • Amazon Bedrock: The LLM (Claude) used by the agent. I use Claude Haiku 5.5

Prerequisites

  • Environment: WSL2 Ubuntu 24.04 / Python 3.13 / uv / Node.js 22 (the CDK CLI is run with npx aws-cdk@latest; 2.1149.0)
  • Libraries: aws-cdk-lib 2.277.0, bedrock-agentcore 1.26.1 (with the strands-agents extra; Strands Agents itself is 1.65.0)
  • Region: ap-northeast-1 (Tokyo)
  • Model: Claude Haiku 5.5 (the Japan cross-region inference profile jp.anthropic.claude-haiku-5-5)
  • Required permissions: CloudFormation, bedrock-agentcore:* (creating Memory, and event and record operations), and bedrock:InvokeModel*
  • Preparation: AWS CLI credentials (this article uses AWS_PROFILE) and an account that has been bootstrapped for CDK

Step 1: Create Memory with CDK

The Memory resource can be created as AWS::BedrockAgentCore::Memory in CloudFormation, so I use the CDK L1 construct CfnMemory.

First, create the project.

mkdir agentcore-memory-basics && cd agentcore-memory-basics
mkdir cdk scripts
cd cdk
uv venv .venv
uv pip install --python .venv/bin/python "aws-cdk-lib>=2.277.0" "constructs>=10.0"

cdk/cdk.json:

{
  "app": ".venv/bin/python app.py",
  "context": {}
}

cdk/stack.py:

import aws_cdk as cdk
from aws_cdk import aws_bedrockagentcore as agentcore
from constructs import Construct

class VerificationStack(cdk.Stack):
    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        memory = agentcore.CfnMemory(
            self,
            "PersonalAssistantMemory",
            name="PersonalAssistantMemory",
            description="short-term events + user preference long-term memory",
            # Retention period (in days) for short-term memory (events)
            event_expiry_duration=7,
            memory_strategies=[
                agentcore.CfnMemory.MemoryStrategyProperty(
                    user_preference_memory_strategy=agentcore.CfnMemory.UserPreferenceMemoryStrategyProperty(
                        name="PreferenceLearner",
                        description="Extracts user preferences across sessions",
                        # Where long-term memory records are stored. Separated per actorId and shared across sessions
                        namespaces=["/preferences/{actorId}/"],
                    )
                ),
            ],
        )

        cdk.CfnOutput(self, "MemoryId", value=memory.attr_memory_id)
        cdk.CfnOutput(self, "MemoryArn", value=memory.attr_memory_arn)
        cdk.CfnOutput(self, "MemoryStatus", value=memory.attr_status)

The points to note in this definition are as follows.

  • event_expiry_duration is the retention period of short-term memory in days. Events are deleted once this number of days has passed
  • {actorId} in namespaces is a variable replaced at runtime. When you specify /preferences/{actorId}/, the namespace is separated per user, and the same user refers to the same namespace even across different sessions. The leading and trailing / are added to prevent namespace collisions caused by prefix matching

cdk/app.py:

#!/usr/bin/env python3
import os

import aws_cdk as cdk

from stack import VerificationStack

app = cdk.App()
VerificationStack(
    app,
    "BlogAgentCoreMemoryBasics",
    env=cdk.Environment(
        account=os.environ.get("CDK_DEFAULT_ACCOUNT"),
        region=os.environ.get("CDK_DEFAULT_REGION", "ap-northeast-1"),
    ),
)
app.synth()

Next, deploy.

export AWS_PROFILE=<your-profile> AWS_REGION=ap-northeast-1
npx --yes aws-cdk@latest bootstrap   # First time only
npx --yes aws-cdk@latest deploy
✅  BlogAgentCoreMemoryBasics

✨  Deployment time: 17.15s

Outputs:
BlogAgentCoreMemoryBasics.MemoryId = PersonalAssistantMemory-XXXXXXXXXX
BlogAgentCoreMemoryBasics.MemoryStatus = ACTIVE

The deployment completed in about 17 seconds. Make a note of the output MemoryId, since it is used in the following scripts.

Step 2: Connect Memory to Strands Agents

Create an environment for the scripts. Installing bedrock-agentcore with the strands-agents extra installs Strands Agents itself and the Memory integration together.

cd ../scripts
uv venv .venv
uv pip install --python .venv/bin/python "bedrock-agentcore[strands-agents]>=1.26.1" "boto3>=1.40"
export MEMORY_ID=<ステップ 1 の MemoryId>

Common settings, scripts/common.py:

import os

REGION = os.environ.get("AWS_REGION", "ap-northeast-1")
MEMORY_ID = os.environ["MEMORY_ID"]
ACTOR_ID = os.environ.get("ACTOR_ID", "user-kosuke")
MODEL_ID = os.environ.get("MODEL_ID", "jp.anthropic.claude-haiku-5-5")
SYSTEM_PROMPT = (
    "あなたは個人アシスタントです。ユーザーについて知っていることがあれば、それを踏まえて日本語で簡潔に答えてください。"
)

This is the script for session A, scripts/01_session_a.py. I tell it two preferences.

from bedrock_agentcore.memory.integrations.strands.config import AgentCoreMemoryConfig
from bedrock_agentcore.memory.integrations.strands.session_manager import AgentCoreMemorySessionManager
from strands import Agent
from strands.models import BedrockModel

from common import ACTOR_ID, MEMORY_ID, MODEL_ID, REGION, SYSTEM_PROMPT

config = AgentCoreMemoryConfig(memory_id=MEMORY_ID, actor_id=ACTOR_ID, session_id="session-a")

with AgentCoreMemorySessionManager(config, region_name=REGION) as session_manager:
    agent = Agent(
        model=BedrockModel(model_id=MODEL_ID, region_name=REGION),
        system_prompt=SYSTEM_PROMPT,
        session_manager=session_manager,
    )
    agent("コーヒーは浅煎りが好きです。酸味があるほうがうれしいです。")
    agent("あと、返事はいつも 3 文以内で短くしてください。")
    agent("今週末に試すおすすめのコーヒーを 1 つ教えてください。")

No special implementation is needed on the Strands Agents side. Just passing session_manager to Agent automatically performs the following.

  • When the agent is initialized, it loads the events with the same session_id and restores the conversation history
  • For every user utterance and assistant response, it stores an event with CreateEvent
  • When leaving the with block, it sends any unsent events (this applies when batch_size is greater than 1; the default is 1, so events are sent for every utterance)

Run the script.

.venv/bin/python 01_session_a.py

Strands Agents streams responses to standard output by default. Separated by turn, the output is as follows.

(1 ターン目)
承知しました。浅煎りで酸味のあるコーヒーがお好みなんですね。

たとえば次のようなものが合いそうです。
- **エチオピア(イルガチェフェなど)**:フルーティーで華やかな酸味
- **ケニア**:はっきりしたベリー系の酸味とジューシーな口当たり
- **コロンビアの浅煎り**:バランスの良い酸味と甘み

豆を選ぶときは、パッケージの「ライトロースト」「シティロースト」といった焙煎度や、「フルーティー」「柑橘系」などの風味表現を目安にしてみてください。

(2 ターン目)
承知しました。今後は3文以内で簡潔にお答えします。

(3 ターン目)
今週末は、エチオピア・イルガチェフェの浅煎りがおすすめです。ベルガモットや紅茶のような華やかな酸味が楽しめ、ハンドドリップで淹れると香りがより引き立ちます。豆は焙煎日が新しいものを選ぶと、酸味と香りをよりおいしく味わえます。

The response in the third turn satisfies both the light-roast and acidity preference and the "within 3 sentences" request.

Step 3: Check the contents of short-term memory

In Step 2, the user sent three utterances in order. Each time, the session manager stores the utterance and the response in short-term memory.

Therefore, at the time of the third utterance, the first one ("I like light roast with some acidity") and the second one ("keep replies within 3 sentences") were already stored in short-term memory. Based on these two, the agent seems to have suggested a light-roast Ethiopia Yirgacheffe in three sentences.

Figure 3: Utterances in session A and the events in short-term memory

Let's check the events that were actually stored with ListEvents. scripts/02_list_events.py:

import json

import boto3

from common import ACTOR_ID, MEMORY_ID, REGION

client = boto3.client("bedrock-agentcore", region_name=REGION)
resp = client.list_events(memoryId=MEMORY_ID, actorId=ACTOR_ID, sessionId="session-a", maxResults=50)

# ListEvents returns the newest first, so sort from oldest to newest before displaying
for ev in sorted(resp["events"], key=lambda e: e["eventTimestamp"]):
    state_type = ev.get("metadata", {}).get("stateType", {}).get("stringValue")
    for p in ev.get("payload", []):
        if "conversational" in p:
            conv = p["conversational"]
            # The Strands message is stored as-is as a JSON string in content.text
            message = json.loads(conv["content"]["text"])["message"]
            text = " ".join(c["text"] for c in message["content"] if "text" in c).replace("\n", " ")
            print(f"{ev['eventTimestamp']:%H:%M:%S} [{conv['role']}] {text[:50]}")
        elif "blob" in p:
            print(f"{ev['eventTimestamp']:%H:%M:%S} [blob: {state_type}]")
.venv/bin/python 02_list_events.py
14:14:02 [blob: SESSION]
14:14:02 [blob: AGENT]
14:14:03 [USER] コーヒーは浅煎りが好きです。酸味があるほうがうれしいです。
14:14:03 [blob: AGENT]
14:14:05 [ASSISTANT] 承知しました。浅煎りで酸味のあるコーヒーがお好みなんですね。  たとえば次のようなものが合いそうです
14:14:05 [USER] あと、返事はいつも 3 文以内で短くしてください。
14:14:07 [ASSISTANT] 承知しました。今後は3文以内で簡潔にお答えします。
14:14:07 [USER] 今週末に試すおすすめのコーヒーを 1 つ教えてください。
14:14:09 [ASSISTANT] 今週末は、エチオピア・イルガチェフェの浅煎りがおすすめです。ベルガモットや紅茶のような華やかな酸味が

Nine events were stored.

  • One utterance corresponds to one event. USER and ASSISTANT are stored as separate events, giving 6 events for 3 round trips
  • The remaining 3 (blob) are state data that the session manager stored for restoring the conversation
  • Utterances are stored as-is, without summarization

Step 4: Wait for long-term memory extraction and retrieve it

The User Preference strategy runs extraction in the background after events are stored. Extraction takes time to complete, so I wait a little and then search with RetrieveMemoryRecords. scripts/03_retrieve_records.py:

import boto3

from common import ACTOR_ID, MEMORY_ID, REGION

client = boto3.client("bedrock-agentcore", region_name=REGION)
resp = client.retrieve_memory_records(
    memoryId=MEMORY_ID,
    namespace=f"/preferences/{ACTOR_ID}/",
    searchCriteria={"searchQuery": "コーヒーの好みと返答スタイル", "topK": 5},
)
records = resp.get("memoryRecordSummaries", [])
print(f"{len(records)} records")
for r in records:
    print(f"- score={r.get('score'):.3f} created={r['createdAt']}")
    print(f"  {r['content']['text']}")
.venv/bin/python 03_retrieve_records.py

When run right after session A, there are 0 records.

0 records

When I waited a while and ran it again, 2 records were retrieved.

2 records
- score=0.498 created=2026-11-19 14:15:13.588000+09:00
  {"context":"コーヒーを選ぶとき","preference":"コーヒーは浅煎りが好きで、酸味があるほうがうれしい","categories":["コーヒー","焙煎度","味わい"]}
- score=0.395 created=2026-11-19 14:15:13.588000+09:00
  {"context":"アシスタントへの返答スタイルを設定するとき","preference":"返事はいつも3文以内で短くしてほしい","categories":["コミュニケーション","返答スタイル"]}

Some time after the conversation ended, long-term memory records had been created. Extraction runs asynchronously after the conversation, so long-term memory is not reflected in the immediately following utterance.

Contents of the extracted records

The characteristics of long-term memory extraction that can be read from the extracted records are as follows.

  • Records are created in the same language as the conversation. This time, Japanese records were created from a Japanese conversation, and they were not translated into English
  • Records from the User Preference strategy are in JSON format, with context (the situation the preference applies to), preference (the content of the preference), and categories (classification)
  • Extraction is processed by an LLM, and the results are not deterministic. Even with the same conversation as input, the number of records, how they are split, and their wording may change from run to run. This time as well, when I ran the same conversation two more times with other actors (user-trial-2 / user-trial-3), one run produced 2 records and another produced 3. You should avoid implementations that assume the number of records or the wording will match
  • Extraction seems to be limited to preferences stated by the user themselves. Information contained in the assistant's responses (in this case, the names of coffee beans) was not included in the records

The following figure shows the relationship between the short-term memory of session A and the long-term memory created from it.

Figure 4: Correspondence between short-term memory events and long-term memory records

Step 5: Check whether the preferences are reflected in a different session

In session B, I ask a question without stating preferences, and compare the cases where long-term memory is and isn't referenced. To reference it, specify retrieval_config. On every user utterance, the session manager searches the namespace and inserts the retrieved records at the beginning of the utterance in a <user_context> tag. To not reference it, run with NO_RETRIEVAL=1 and no retrieval_config. scripts/04_session_b.py:

"""セッション B: 別セッション(同じ actor)。好みを言わずに質問し、長期記憶の内容が反映されるかを見る。

NO_RETRIEVAL=1 を付けると retrieval_config なし・別セッション(session-c)で実行する(対照)。
"""
import os

from bedrock_agentcore.memory.integrations.strands.config import AgentCoreMemoryConfig, RetrievalConfig
from bedrock_agentcore.memory.integrations.strands.session_manager import AgentCoreMemorySessionManager
from strands import Agent
from strands.models import BedrockModel

from common import ACTOR_ID, MEMORY_ID, MODEL_ID, REGION, SYSTEM_PROMPT

if os.environ.get("NO_RETRIEVAL"):
    # Control: do not retrieve long-term memory. Use a separate session so session-b's history is not restored
    config = AgentCoreMemoryConfig(memory_id=MEMORY_ID, actor_id=ACTOR_ID, session_id="session-c")
else:
    config = AgentCoreMemoryConfig(
        memory_id=MEMORY_ID,
        actor_id=ACTOR_ID,
        session_id="session-b",
        # On every user utterance, semantically search this namespace and insert the results at the beginning of the utterance
        retrieval_config={"/preferences/{actorId}/": RetrievalConfig(top_k=5, relevance_score=0.3)},
    )

with AgentCoreMemorySessionManager(config, region_name=REGION) as session_manager:
    agent = Agent(
        model=BedrockModel(model_id=MODEL_ID, region_name=REGION),
        system_prompt=SYSTEM_PROMPT,
        session_manager=session_manager,
        callback_handler=None,
    )
    result = agent("おすすめのコーヒー豆を教えてください。")

    # The user utterance actually passed to the model (if long-term memory was inserted, it appears here)
    print("=== モデルに渡ったユーザー発話")
    for block in agent.messages[0]["content"]:
        print(block.get("text"))
    print("=== 応答")
    print(result)
.venv/bin/python 04_session_b.py                  # with retrieval_config (session-b)
NO_RETRIEVAL=1 .venv/bin/python 04_session_b.py   # without retrieval_config (session-c, control)

This is the result with retrieval_config.

=== モデルに渡ったユーザー発話
<user_context>{"context":"コーヒーを選ぶとき","preference":"コーヒーは浅煎りが好きで、酸味があるほうがうれしい","categories":["コーヒー","焙煎度","味わい"]}
{"context":"アシスタントへの返答スタイルを設定するとき","preference":"返事はいつも3文以内で短くしてほしい","categories":["コミュニケーション","返答スタイル"]}</user_context>
おすすめのコーヒー豆を教えてください。
=== 応答
浅煎りで酸味のあるコーヒー豆なら、エチオピア産のイルガチェフェや、ケニア産のAA系がおすすめです。フルーティーで華やかな酸味を楽しめます。購入時は「浅煎り」「酸味」と表記された商品を選ぶと失敗しにくいです。

This is the result without retrieval_config (control).

=== モデルに渡ったユーザー発話
おすすめのコーヒー豆を教えてください。
=== 応答
いくつかおすすめをご紹介します。

- **ブラジル・サントス**:ナッツやチョコレートのような香りで、酸味が少なく苦味がまろやか。初心者にも飲みやすいです。
- **コロンビア**:バランスのよい甘みと程よい酸味があり、毎日の一杯に向いています。
- **エチオピア・イルガチェフェ**:フルーツや花のような華やかな香りとさわやかな酸味があり、浅煎りでお楽しみいただけます。
- **グアテマラ**:チョコレートのような甘みとコクがあり、中煎りから深煎りまで幅広く合います。

お好みを教えていただければ、さらに絞り込めます。たとえば、酸味と苦味のどちらが好きか、普段はドリップ・エスプレッソ・ミルクを使うかどうか、などです。

Comparing the two results, I found the following differences.

Figure 5: Comparison of responses with and without long-term memory retrieval

  • With retrieval_config, the 2 records from Step 4 were inserted at the beginning of the user's utterance in a <user_context> tag. They appear to be added to the utterance itself, not to the system prompt
  • The response was narrowed down to light-roast, acidic beans and consisted of 3 sentences. Since the preferences were not stated in session B, this means the contents of long-term memory were reflected in the answer
  • In contrast, the chat that did not reference long-term memory listed 4 kinds of beans, including those leaning toward dark roast, and ended by asking about preferences. This is the response when preferences are not known

So far, I have confirmed that short-term memory (events) and long-term memory (records) are stored as separate data, and that long-term memory is reused across sessions.

Pricing

AgentCore Memory is pay-as-you-go.

Item Price (as of 2026-11-19)
Short-term memory ingestion $1.00 / GB
Short-term memory retrieval $0.20 / GB
Short-term memory storage $0.10 / GB-month
Long-term memory storage (built-in strategy) $0.75 / 1,000 records-month
Long-term memory retrieval $0.50 / 1,000 calls

Short-term memory ingestion and retrieval are calculated with a minimum of 12 KB and a maximum of 64 KB per event. Even for short utterances like these, one event is counted as 12 KB.

At the scale of this test (a dozen or so events and a few records), the cost is expected to be a few yen.

Cleanup

When the test is finished, delete the following so that charges do not continue.

  1. Delete the CDK stack (the Memory resource is deleted along with it, and the events and records are deleted at the same time)
cd ../cdk
npx --yes aws-cdk@latest destroy
  1. In the console, under Bedrock AgentCore → Memory, confirm that PersonalAssistantMemory has been deleted

Conclusion

In this article, I created AgentCore Memory with CDK, connected it from Strands Agents, and checked the difference between short-term and long-term memory using actual events and records.

Short-term memory retains utterances as-is per session, while long-term memory stores the key points that strategies extract asynchronously into namespaces. Understanding this division of roles made the terms in the official documentation easier to understand. The integration with Strands Agents is complete just by passing session_manager, and inserting long-term memory is enabled just by specifying retrieval_config, so I felt the implementation burden is small.

Next time, I will split namespaces into per-user and all-user shared ones, register shared knowledge into long-term memory without going through a conversation, and check whether it is reflected in another user's responses.

References

Share this article

AWSのお困り事はクラスメソッドへ