[Update] I tried the newly added long-term memory strategy "Episodic memory" in Amazon Bedrock AgentCore Memory

[Update] I tried the newly added long-term memory strategy "Episodic memory" in Amazon Bedrock AgentCore Memory

2025.12.03

This page has been translated by machine translation. View original

Introduction

Hello, I'm Kamino from the Consulting Department!

A new long-term memory strategy called "Episodic memory" has been added to Amazon Bedrock AgentCore!

https://aws.amazon.com/jp/blogs/aws/amazon-bedrock-agentcore-adds-quality-evaluations-and-policy-controls-for-deploying-trusted-ai-agents/

This feature allows AI agents to learn from past experiences and apply those lessons to future interactions. You might be wondering how this differs from existing long-term memory strategies.

For example, let's consider a travel booking agent mentioned in the AWS official blog.
Over time, the agent learns the user's booking patterns. It can recognize patterns like "when traveling for business, the user often changes flights to later times due to client meetings," and during the next business trip booking, the agent can proactively suggest flexible return options based on these learned patterns.

The image is that AI agents can extract insights from experiences and utilize them. Let's try it out!

About This Update

Previous Long-Term Memory Strategies

Until this update, AgentCore Memory had the following three built-in long-term memory strategies:

  • Semantic Memory

    • Extracts and stores facts and knowledge
  • User Preference

    • Extracts user preferences
  • Summary

    • Generates and maintains conversation summaries

The new built-in long-term memory strategy has been added to these.

Episodic Memory

The newly added Episodic memory is slightly different from previous long-term memory strategies.
It structures interactions with users as "episodes" and further analyzes multiple episodes to generate reflections.

https://docs.aws.amazon.com/ja_jp/bedrock-agentcore/latest/devguide/episodic-memory-strategy.html

Let's look at the mechanism in more detail.

How Episodic Memory Works

The Episodic memory strategy automatically operates in three steps to extract long-term memories.
I'll quote the operational flow diagram from the official documentation.

episodic-memory-strategy

Extraction

It analyzes ongoing interactions and determines whether an episode is complete.
Unlike other strategies, Episodic memory only generates records when it detects that an episode is complete.

Consolidation

When an episode is complete, it consolidates related events into a single structured episode record. Each episode includes the following information:

  • Situation
    • Background/context of the episode
  • Intent
    • User's or agent's intention
  • Assessment
    • Evaluation of the result
  • Justification
    • Basis for judgment
  • Episode-level Reflection
    • Reflection at the episode level

Reflection

Analyzes across multiple episodes to extract broader insights.

Examples of Information Extracted by Reflection

  • Combinations of tools that consistently succeed for specific task types
  • Patterns of failed approaches and how they were resolved
  • Best practices from multiple successful episodes in similar scenarios

This is a distinctive feature. With other long-term memory strategies, the process ends after extraction and structuring, so having this reflection step is unique to this strategy.

In What Situations Is It Effective

I think Episodic memory is likely to be effective in scenarios like these.
The specific examples are referenced from AWS official documentation examples.

deal use cases include customer support conversations, agent driven workflows, code assistants that rely on session history, personal productivity tools, troubleshooting or diagnostic flows, and applications that need context grounded in real prior events rather than static profiles.

Use Case Description
Customer Support Learning effective solutions from past response patterns
Agent-driven Workflows Applying experience from past task executions to future tasks
Code Assistants Understanding context based on session history
Troubleshooting Referring to past problem-solving patterns
Personal Productivity Tools Learning user work patterns

It seems suitable for cases where responses are based on stored experiences. It also seems good for operations that need reflection to improve proficiency.

Differentiating Between Strategies

Reconsidering all strategies together, each roughly fulfills the following roles:

  • Semantic memory
    • "What is known" (facts, knowledge)
  • User Preference
    • "What the user likes" (preferences)
  • Summary
    • "What was discussed in this session" (summary)
  • Episodic memory
    • What happened and why it succeeded/failed
      • Extracting knowledge from experience for success

Let's implement and test it right away.

Creating an Agent with Strands Agents

Now, let's create an agent using Episodic memory.

Environment Setup

# Create project directory
mkdir agentcore-episodic-demo
cd agentcore-episodic-demo

# Create and activate virtual environment
python -m venv .venv
source .venv/bin/activate  # For Windows: .venv\Scripts\activate

# Install dependencies
pip install bedrock-agentcore strands-agents strands-agents-tools bedrock-agentcore-starter-toolkit

Creating Episodic Memory Resource

We'll create it in the console. The values to set are as follows:

  • Memory name
    • Sample_episode_memory
  • Built-in strategy
    • Check Episodes
      • Strategy name
        • episodeStrategy
      • Namespace for extracted memories
        • /strategies/{memoryStrategyId}/actors/{actorId}/sessions/{sessionId}
          • Aggregated by Session ID
      • Namespace for reflection
        • /strategies/{memoryStrategyId}/actors/{actorId}
          • Aggregated by actor ID

CleanShot 2025-12-03 at 17.52.59@2x

After creation, note down the Memory ID from the following value:

CleanShot 2025-12-03 at 09.08.14@2x

We also need the Strategy ID, so note that down as well:

CleanShot 2025-12-03 at 17.55.47@2x

Now we're all set. Let's proceed with implementing the agent.

Implementing the Strands Agent

Create agent.py. This is a simple agent that performs calculations.
Let's test this agent by having it output calculation problems, give incorrect answers, and then analyze the responses.

"""
AgentCore Memory - Strands Agent utilizing Episodic Memory

Uses Strands Session Manager to automatically integrate short-term memory and Episodic Memory (long-term memory).

Usage:
    python agent.py --actor-id user123 --session-id session456
    python agent.py -a user123 -s session456
"""

import argparse
import logging
import os

os.environ["BYPASS_TOOL_CONSENT"] = "true"

def parse_args():
    """Parse command line arguments"""
    parser = argparse.ArgumentParser(
        description="AgentCore Episodic Memory Demo - Calculation Assistant"
    )
    parser.add_argument(
        "-a",
        "--actor-id",
        type=str,
        default="demo_user",
        help="User (Actor) ID (default: demo_user)",
    )
    parser.add_argument(
        "-s",
        "--session-id",
        type=str,
        default="calculation_session_001",
        help="Session ID (default: calculation_session_001)",
    )
    parser.add_argument(
        "-m",
        "--memory-id",
        type=str,
        default=None,
        help="Memory ID (default: uses environment variable MEMORY_ID)",
    )
    parser.add_argument("-v", "--verbose", action="store_true", help="Enable detailed logging")
    parser.add_argument(
        "--strategy-id",
        type=str,
        default=None,
        help="Memory Strategy ID (default: uses environment variable MEMORY_STRATEGY_ID)",
    )
    return parser.parse_args()

# Parse arguments
args = parse_args()

# Configure logging
log_level = logging.DEBUG if args.verbose else logging.INFO
logging.basicConfig(
    format="%(levelname)s | %(name)s | %(message)s",
    level=log_level,
    handlers=[logging.StreamHandler()],
)

# Enable AgentCore Memory related logs
logging.getLogger("bedrock_agentcore").setLevel(
    logging.DEBUG if args.verbose else logging.INFO
)
# Only important logs for Strands
logging.getLogger("strands").setLevel(logging.WARNING)

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_tools import calculator

# Get Memory ID, Strategy ID from arguments or environment variables
MEMORY_ID = args.memory_id or os.getenv("MEMORY_ID")
MEMORY_STRATEGY_ID = args.strategy_id or os.getenv("MEMORY_STRATEGY_ID")
ACTOR_ID = args.actor_id
SESSION_ID = args.session_id

if not MEMORY_ID:
    print("⚠️ MEMORY_ID is not set")
    print("Please run setup_memory.py first")
    exit(1)

if not MEMORY_STRATEGY_ID:
    print("⚠️ MEMORY_STRATEGY_ID is not set")
    print(
        "Please specify using environment variable MEMORY_STRATEGY_ID or the --strategy-id option"
    )
    exit(1)

print(f"✅ Memory ID: {MEMORY_ID}")
print(f"✅ Memory Strategy ID: {MEMORY_STRATEGY_ID}")
print(f"✅ Actor ID: {ACTOR_ID}")
print(f"✅ Session ID: {SESSION_ID}")

# AgentCore Memory configuration (with Episodic Memory)
config = AgentCoreMemoryConfig(
    memory_id=MEMORY_ID,
    session_id=SESSION_ID,
    actor_id=ACTOR_ID,
    retrieval_config={
        # Retrieve episodes (session-level experiences)
        f"/strategies/{MEMORY_STRATEGY_ID}/actors/{{actorId}}/sessions/{{sessionId}}": RetrievalConfig(
            top_k=5
        ),
        # Retrieve reflections (actor-wide insights)
        f"/strategies/{MEMORY_STRATEGY_ID}/actors/{{actorId}}": RetrievalConfig(
            top_k=3
        ),
    },
)

# Create Session Manager
session_manager = AgentCoreMemorySessionManager(
    agentcore_memory_config=config, region_name="us-west-2"
)

# Create Strands Agent (with Session Manager integration)
agent = Agent(
    model="us.anthropic.claude-haiku-4-5-20251001-v1:0",
    tools=[calculator],
    system_prompt="""You are a helpful calculation assistant.
Please provide accurate results for user calculation requests using the calculator tool.
Utilize insights learned from past episodes and reflections to provide analysis and advice.""",
    session_manager=session_manager,
)

print("✅ Strands Agent with Episodic Memory initialization complete")

def main():
    """Main function - interaction loop"""
    print("=" * 60)
    print("AgentCore Episodic Memory Demo - Calculation Assistant")
    print("=" * 60)
    print("\nPlease enter calculation requests.")
    print("Enter 'quit' to exit.\n")

    while True:
        try:
            user_input = input("\nInput> ").strip()

            if not user_input:
                continue

            if user_input.lower() == "quit":
                print("\nExiting.")
                break

            print(f"\n👤 User: {user_input}")
            response = agent(user_input)

            print(f"\n🤖 Assistant: {response.message}")

        except KeyboardInterrupt:
            print("\n\nExiting.")
            break

if __name__ == "__main__":
    main()

We use AgentCoreMemorySessionManager to manage memory. It's convenient as short-term memory is saved and long-term memory is referenced without requiring complex implementation.

Test

Now I'll set the ID I noted in the console to MEMORY_ID and MEMORY_STRATEGY_ID.
After configuring these, the code is ready to run. I'll quickly check the behavior locally for now.

# Set environment variables
export MEMORY_ID=mem_xxxxxxxxxxxxxxx
export MEMORY_STRATEGY_ID=xxx

# Run the agent
python agent.py -a demo_user -s demo_session

I'll have the agent generate calculation problems and provide information for analysis.
The Actor ID and Session ID are specified as arguments.

I'll deliberately give wrong answers. I'll include excerpts of the conversation and logs but will collapse them due to length.

Logs
python agent.py -a demo_user -s demo_session
✅ Memory ID: sample_episode_memory-XXXXXXXXXXXX
✅ Memory Strategy ID: episodeStratedgy-XXXXXXXXXXXX
✅ Actor ID: demo_user
✅ Session ID: demo_session
INFO | botocore.credentials | Found credentials in environment variables.
INFO | bedrock_agentcore.memory.client | Initialized MemoryClient for control plane: us-west-2, data plane: us-west-2
INFO | botocore.credentials | Found credentials in environment variables.
INFO | bedrock_agentcore.memory.client | Retrieved total of 1 events
INFO | botocore.credentials | Found credentials in environment variables.
INFO | bedrock_agentcore.memory.client | Retrieved total of 1 events
INFO | bedrock_agentcore.memory.client | Retrieved total of 0 events

✅ Strands Agent with Episodic Memory initialization complete
============================================================

AgentCore Episodic Memory Demo - Calculation Assistant
============================================================

Please input your calculation request.
Enter 'quit' to exit.

Input> Please create math problems without answers.

👤 User: Please create math problems without answers.
INFO | bedrock_agentcore.memory.client | Created event: 0000001764751005760#85588878
INFO | bedrock_agentcore.memory.client | Retrieved total of 1 events
INFO | bedrock_agentcore.memory.integrations.strands.session_manager | Created agent: default in session: demo_session with event 0000001764751006760#b25a885d
INFO | bedrock_agentcore.memory.client | Retrieved 0 memories from namespace: /strategies/episodeStratedgy-XXXXXXXXXXXX/actors/demo_user/sessions/demo_session
INFO | bedrock_agentcore.memory.client | Retrieved 0 memories from namespace: /strategies/episodeStratedgy-XXXXXXXXXXXX/actors/demo_user

# I'll give you 3 calculation problems!

**Problem 1:** 
Calculate $\frac{3}{4} + \frac{5}{8} - \frac{1}{2}$.

**Problem 2:** 
Find the values of $x$ that satisfy $x^2 + 5x + 6 = 0$.

**Problem 3:** 
Find the value of the derivative of $f(x) = 2x^3 - 3x^2 + 1$ at $x = 2$.

---

Think about these problems, and let me know your answers! If you get stuck, I can provide hints or we can solve them together.

Input> 1 21 2 4331 3 312

👤 User: 1 21 2 4331 3 312
INFO | bedrock_agentcore.memory.client | Created event: 0000001764751022116#f1d18ddd
INFO | bedrock_agentcore.memory.client | Retrieved total of 1 events
INFO | bedrock_agentcore.memory.integrations.strands.session_manager | Created agent: default in session: demo_session with event 0000001764751023116#f41cc292
INFO | bedrock_agentcore.memory.client | Retrieved 0 memories from namespace: /strategies/episodeStratedgy-XXXXXXXXXXXX/actors/demo_user/sessions/demo_session
INFO | bedrock_agentcore.memory.client | Retrieved 0 memories from namespace: /strategies/episodeStratedgy-XXXXXXXXXXXX/actors/demo_user
Let's check your answers!
Tool #1: calculator

Tool #2: calculator

Tool #3: calculator
INFO | bedrock_agentcore.memory.client | Created event: 0000001764751025881#cefb75e4
INFO | bedrock_agentcore.memory.client | Retrieved total of 1 events
INFO | bedrock_agentcore.memory.integrations.strands.session_manager | Created agent: default in session: demo_session with event 0000001764751026881#5556fe5a
INFO | bedrock_agentcore.memory.client | Created event: 0000001764751027881#4b9ebfc3
INFO | bedrock_agentcore.memory.client | Retrieved total of 1 events
INFO | bedrock_agentcore.memory.integrations.strands.session_manager | Created agent: default in session: demo_session with event 0000001764751028881#0360a170
Now let's evaluate the derivative at x=2:
Tool #4: calculator
INFO | bedrock_agentcore.memory.client | Created event: 0000001764751029881#5ef3457d
INFO | bedrock_agentcore.memory.client | Retrieved total of 1 events
INFO | bedrock_agentcore.memory.integrations.strands.session_manager | Created agent: default in session: demo_session with event 0000001764751030881#ec666552
INFO | bedrock_agentcore.memory.client | Created event: 0000001764751031881#c22d165d
INFO | bedrock_agentcore.memory.client | Retrieved total of 1 events

INFO | bedrock_agentcore.memory.integrations.strands.session_manager | Created agent: default in session: demo_session with event 0000001764751032881#447bc58c
---

## Results

| Problem   | Your Answer | Correct Answer | Result |
| --------- | ------------ | ---------- | ---- |
| **Problem 1** | 1.21         | **0.875**  | ❌    |
| **Problem 2** | 4331         | **-3, -2** | ❌    |
| **Problem 3** | 312          | **12**     | ❌    |

---

Unfortunately, all three answers were incorrect 😅

**Explanation:**

- **Problem 1:** The key is finding a common denominator. 3/4 + 5/8 - 1/2 = 6/8 + 5/8 - 4/8 = 7/8 = 0.875
- **Problem 2:** Factoring gives (x+3)(x+2) = 0, so x = -3 or x = -2
- **Problem 3:** The derivative is f'(x) = 6x² - 6x, and at x=2 we get 6(4) - 6(2) = 24 - 12 = 12

Would you like to try another problem? I'd be happy to explain any of these in more detail!

Input> Give me another problem

👤 User: Give me another problem
INFO | bedrock_agentcore.memory.client | Created event: 0000001764751048565#e8736b0b
INFO | bedrock_agentcore.memory.client | Retrieved total of 1 events
INFO | bedrock_agentcore.memory.integrations.strands.session_manager | Created agent: default in session: demo_session with event 0000001764751049565#7378b5ee
INFO | bedrock_agentcore.memory.client | Retrieved 0 memories from namespace: /strategies/episodeStratedgy-XXXXXXXXXXXX/actors/demo_user
INFO | bedrock_agentcore.memory.client | Retrieved 0 memories from namespace: /strategies/episodeStratedgy-XXXXXXXXXXXX/actors/demo_user/sessions/demo_session

# Here's a new problem!

**Problem 4:**
Calculate $\int (3x^2 + 2x - 1) dx$. (indefinite integral)

---

Try to find the answer!

Input> 21 + C!      

👤 User: 21 + C!
INFO | bedrock_agentcore.memory.client | Created event: 0000001764751064550#c34506ec
INFO | bedrock_agentcore.memory.client | Retrieved total of 1 events
INFO | bedrock_agentcore.memory.integrations.strands.session_manager | Created agent: default in session: demo_session with event 0000001764751065745#7b8b3796
INFO | bedrock_agentcore.memory.client | Retrieved 0 memories from namespace: /strategies/episodeStratedgy-XXXXXXXXXXXX/actors/demo_user/sessions/demo_session
INFO | bedrock_agentcore.memory.client | Retrieved 0 memories from namespace: /strategies/episodeStratedgy-XXXXXXXXXXXX/actors/demo_user
Let's check!
Tool #5: calculator
INFO | bedrock_agentcore.memory.client | Created event: 0000001764751067706#7bc01094
INFO | bedrock_agentcore.memory.client | Retrieved total of 1 events
INFO | bedrock_agentcore.memory.integrations.strands.session_manager | Created agent: default in session: demo_session with event 0000001764751068757#09ae2d99
INFO | bedrock_agentcore.memory.client | Created event: 0000001764751069757#db60da4a
INFO | bedrock_agentcore.memory.client | Retrieved total of 1 events
INFO | bedrock_agentcore.memory.integrations.strands.session_manager | Created agent: default in session: demo_session with event 0000001764751070757#e5a56751

## Results

| Problem   | Your Answer | Correct Answer        | Result |
| --------- | ------------ | ----------------------- | ---- |
| **Problem 4** | 21 + C       | **$x^3 + x^2 - x + C$** | ❌    |

---

Unfortunately, that's incorrect 😅

**Explanation:**

For indefinite integrals, we calculate each term separately.

$$\int (3x^2 + 2x - 1) dx$$

- Integrating $3x^2$ → $\frac{3x^3}{3} = x^3$
- Integrating $2x$ → $\frac{2x^2}{2} = x^2$
- Integrating $-1$ → $-x$

So the answer is: **$x^3 + x^2 - x + C$**

Including "+ C" is a good habit, but getting the form of the integral result is important!

Would you like to try another problem?

Input> Let's end for today!!

👤 User: Let's end for today!!
INFO | bedrock_agentcore.memory.client | Created event: 0000001764751083092#ae7d1d11
INFO | bedrock_agentcore.memory.client | Retrieved total of 1 events
INFO | bedrock_agentcore.memory.integrations.strands.session_manager | Created agent: default in session: demo_session with event 0000001764751084092#1c8b699a
INFO | bedrock_agentcore.memory.client | Retrieved 0 memories from namespace: /strategies/episodeStratedgy-XXXXXXXXXXXX/actors/demo_user/sessions/demo_session
INFO | bedrock_agentcore.memory.client | Retrieved 0 memories from namespace: /strategies/episodeStratedgy-XXXXXXXXXXXX/actors/demo_user
Understood! Great work today! 🎉

Thank you for taking on these calculation problems today!

**Today's summary:**

- Problems 1-3: Fractions, equations, and derivatives
- Problem 4: Integration

Next time you need help with calculations or math explanations, please feel free to ask anytime. Let's keep working on it together! 💪

See you tomorrow! 👋

After waiting a few minutes, I found logs in the Memory CloudWatch Logs showing the extraction process had been executed.

{
    "resource_arn": "arn:aws:bedrock-agentcore:us-west-2:XXXXXXXXXXXX:memory/sample_episode_memory-XXXXXXXXXXXX",
    "event_timestamp": 1764752065253,
    "memory_strategy_id": "episodeStratedgy-XXXXXXXXXXXX",
    "namespace": "/strategies/episodeStratedgy-XXXXXXXXXXXX/actors/demo_user/sessions/demo_session",
    "session_id": "demo_session",
    "body": {
        "log": "Starting episodic memory generation for requestId: XXXXXXXXXXXX-sample_episode_memory-XXXXXXXXXXXX-demo_user-demo_session-episodeStratedgy-XXXXXXXXXXXX-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, memoryId: sample_episode_memory-XXXXXXXXXXXX, episodeId: yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy",
        "requestId": "XXXXXXXXXXXX-sample_episode_memory-XXXXXXXXXXXX-demo_user-demo_session-episodeStratedgy-XXXXXXXXXXXX-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
        "isError": false
    },
    "resource": {
        "attributes": {
            "service.name": "sample_episode_memory-XXXXXXXXXXXX",
            "cloud.resource_id": "arn:aws:bedrock-agentcore:us-west-2:XXXXXXXXXXXX:memory/sample_episode_memory-XXXXXXXXXXXX",
            "cloud.platform": "aws_bedrock_agentcore"
        }
    },
    "attributes": {
        "aws.resource.type": "AWS::BedrockAgentCore::Memory",
        "aws.agentcore.memory.namespace": "/strategies/episodeStratedgy-XXXXXXXXXXXX/actors/demo_user/sessions/demo_session",
        "session.id": "demo_session"
    },
    "timeUnixNano": 1764752065253129800,
    "severityNumber": 9,
    "severityText": "INFO"
}
・・・
{
    "resource_arn": "arn:aws:bedrock-agentcore:us-west-2:XXXXXXXXXXXX:memory/sample_episode_memory-XXXXXXXXXXXX",
    "event_timestamp": 1764752072150,
    "memory_strategy_id": "episodeStratedgy-XXXXXXXXXXXX",
    "namespace": "/strategies/episodeStratedgy-XXXXXXXXXXXX/actors/demo_user/sessions/demo_session",
    "session_id": "demo_session",
    "body": {
        "log": "Starting reflection generation with episodic record for requestId: XXXXXXXXXXXX-sample_episode_memory-XXXXXXXXXXXX-demo_user-demo_session-episodeStratedgy-XXXXXXXXXXXX-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, memoryId: sample_episode_memory-XXXXXXXXXXXX, episodeId: yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy",
        "requestId": "XXXXXXXXXXXX-sample_episode_memory-XXXXXXXXXXXX-demo_user-demo_session-episodeStratedgy-XXXXXXXXXXXX-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
        "isError": false
    },
    "resource": {
        "attributes": {
            "service.name": "sample_episode_memory-XXXXXXXXXXXX",
            "cloud.resource_id": "arn:aws:bedrock-agentcore:us-west-2:XXXXXXXXXXXX:memory/sample_episode_memory-XXXXXXXXXXXX",
            "cloud.platform": "aws_bedrock_agentcore"
        }
    },
    "attributes": {
        "aws.resource.type": "AWS::BedrockAgentCore::Memory",
        "aws.agentcore.memory.namespace": "/strategies/episodeStratedgy-XXXXXXXXXXXX/actors/demo_user/sessions/demo_session",
        "session.id": "demo_session"
    },
    "timeUnixNano": 1764752072150010986,
    "severityNumber": 9,
    "severityText": "INFO"
}

Looking at the logs, it seems both Consolidation and Reflection were performed.
I'll ask the agent to analyze my calculation results again.

Full response
Input> Please analyze my past calculation results and provide trends and advice.

👤 User: Please analyze my past calculation results and provide trends and advice.
INFO | bedrock_agentcore.memory.client | Created event: 0000001764752293989#28d670d8
INFO | bedrock_agentcore.memory.client | Retrieved total of 1 events
INFO | bedrock_agentcore.memory.integrations.strands.session_manager | Created agent: default in session: demo_session with event 0000001764752294989#b56c8c04
INFO | bedrock_agentcore.memory.client | Retrieved 3 memories from namespace: /strategies/episodeStratedgy-XXXXXXXXXXXX/actors/demo_user
INFO | bedrock_agentcore.memory.client | Retrieved 2 memories from namespace: /strategies/episodeStratedgy-XXXXXXXXXXXX/actors/demo_user/sessions/demo_session
INFO | bedrock_agentcore.memory.integrations.strands.session_manager | Retrieved 5 customer context items

# 📊 Analysis of Your Calculation Results

I've analyzed all four of your answers from today:

---

## 📈 Trend Analysis

| Item         | Details                                 |
| ------------ | ------------------------------------ |
| **Accuracy Rate**   | 0/4 (0%)                             |
| **Trend**     | Significantly different answers submitted for all problems |
| **Pattern** | Randomness similar to combinations of numbers   |

---

## 🔍 Detailed Observations

### **Problem-specific characteristics:**

1. **Problem 1 (Fraction calculation)**
	- Your answer: 1.21
	- Correct answer: 0.875
	- **Difference:** 38% error

2. **Problem 2 (Quadratic equation)**
	- Your answer: 4331
	- Correct answer: -3, -2
	- **Difference:** Possible lack of understanding of equation-solving methods

3. **Problem 3 (Derivative value)**
	- Your answer: 312
	- Correct answer: 12
	- **Difference:** Answer 26 times larger

4. **Problem 4 (Indefinite integral)**
	- Your answer: 21 + C
	- Correct answer: x³ + x² - x + C
	- **Difference:** Possible lack of understanding of integral result format

---

## 💡 Improvement Advice

### **Your strengths:**

✅ **Willingness to actively engage in practice** - It's great that you continued to challenge yourself with new problems even after making mistakes!

### **Areas for improvement:**

1. **Understanding of basic concepts**
	- You may need to review fundamental skills such as finding common denominators and factorization

2. **Checking calculation steps**
	- It's important to calculate each step carefully rather than jumping straight to the answer

3. **Recognizing problem formats**
	- For differentiation and integration, the "form of the answer" is important (e.g., x³ + x² - x as terms)

4. **Approach for next time**
	- For problems you don't understand, it's OK to say "Can I have a hint?"
	- We can also solve problems step-by-step together

---

## 🎯 Suggestions for Next Time

Next time you practice:

1. **Start with simpler problems**
2. **Ask to see the calculation process** to identify where mistakes are happening
3. **Focus practice on specific areas** might be effective

Keep up the good work! 💪

Since it uses short-term memory too, it's hard to say definitively that long-term memory is working, but the logs show both types of long-term memories were retrieved:

INFO | bedrock_agentcore.memory.client | Retrieved 3 memories from namespace: /strategies/episodeStratedgy-XXXXXXXXXXXX/actors/demo_user
INFO | bedrock_agentcore.memory.client | Retrieved 2 memories from namespace: /strategies/episodeStratedgy-XXXXXXXXXXXX/actors/demo_user/sessions/demo_session

I'll now check what specific data structure is used to store them.
I'll run this test script to retrieve the long-term memories.

The Memory ID and Strategy ID are embedded in the code, so please modify them as needed when using this script.

Full code
"""
AgentCore Memory - Long-term Memory Query Script

Directly searches and displays episodes and reflections.
"""

import os
import sys

from bedrock_agentcore.memory import MemoryClient

MEMORY_ID = "sample_episode_memory-XXXXXXXXXXXX"
ACTOR_ID = "demo_user"
SESSION_ID = "demo_session"
STRATEGY_ID = "episodeStratedgy-XXXXXXXXXXXX"

if not MEMORY_ID:
    print("⚠️ MEMORY_ID is not set")
    print("Run export MEMORY_ID=mem_xxxxxxxx")
    sys.exit(1)

# Initialize Memory Client
memory_client = MemoryClient(region_name="us-west-2")

print("=" * 80)
print("🔍 AgentCore Memory - Long-term Memory Query Tool")
print("=" * 80)
print(f"Memory ID: {MEMORY_ID}")
print(f"Actor ID: {ACTOR_ID}")
print(f"Session ID: {SESSION_ID}")
print()

def query_episodes(search_query: str, top_k: int = 5):
    """Search episodes (session-level experiences)"""
    print("\n" + "=" * 80)
    print(f"📖 Episode search: '{search_query}'")
    print("=" * 80)

    namespace = f"/strategies/{STRATEGY_ID}/actors/{ACTOR_ID}/sessions/{SESSION_ID}"

    try:
        # Use retrieve_memories method (snake_case)
        records = memory_client.retrieve_memories(
            memory_id=MEMORY_ID,
            namespace=namespace,
            query=search_query,
            top_k=top_k,
        )

        if not records:
            print("✗ No episodes found")
            return

        print(f"✓ Found {len(records)} episodes\n")

        for i, record in enumerate(records, 1):
            content = record.get("content", {}).get("text", "")
            record_id = record.get("id", "unknown")

            print(f"【Episode {i}】")
            print(f"ID: {record_id}")
            print(f"Content:\n{content}\n")
            print("-" * 80)

    except Exception as e:
        print(f"⚠️ Error: {e}")

def query_reflections(search_query: str, top_k: int = 3):
    """Search reflections (actor-wide insights)"""
    print("\n" + "=" * 80)
    print(f"💡 Reflection search: '{search_query}'")
    print("=" * 80)

    namespace = f"/strategies/{STRATEGY_ID}/actors/{ACTOR_ID}"

    try:
        # Use retrieve_memories method (snake_case)
        records = memory_client.retrieve_memories(
            memory_id=MEMORY_ID,
            namespace=namespace,
            query=search_query,
            top_k=top_k,
        )

        if not records:
            print("✗ No reflections found")
            print("(These are automatically generated after multiple episodes are accumulated)")
            return

        print(f"✓ Found {len(records)} reflections\n")

        for i, record in enumerate(records, 1):
            content = record.get("content", {}).get("text", "")
            record_id = record.get("id", "unknown")

            print(f"【Reflection {i}】")
            print(f"ID: {record_id}")
            print(f"Content:\n{content}\n")
            print("-" * 80)

    except Exception as e:
        print(f"⚠️ Error: {e}")

def list_all_episodes(max_results: int = 10):
    """List all episodes"""
    print("\n" + "=" * 80)
    print(f"📋 All episodes (max {max_results})")
    print("=" * 80)

    namespace = f"/strategies/episodeStratedgy-XXXXXXXXXXXX/actors/{ACTOR_ID}/sessions/{SESSION_ID}"

    try:
        # Try to get all records with an empty query
        records = memory_client.retrieve_memories(
            memory_id=MEMORY_ID,
            namespace=namespace,
            query="",
            top_k=max_results,
        )

        if not records:
            print("✗ No episodes found")
            return

        print(f"✓ Found {len(records)} episodes\n")

        for i, record in enumerate(records, 1):
            content = record.get("content", {}).get("text", "")
            record_id = record.get("id", "unknown")

            print(f"{i}. [{record_id}]")
            print(f"   {content[:100]}{'...' if len(content) > 100 else ''}\n")

    except Exception as e:
        print(f"⚠️ Error: {e}")

def interactive_mode():
    """Interactive mode"""
    print("\n" + "=" * 80)
    print("🔍 Interactive Mode")
    print("=" * 80)
    print("Commands:")
    print("  e <search query>  - Search episodes")
    print("  r <search query>  - Search reflections")
    print("  list           - List all episodes")
    print("  quit           - Exit")
    print()

    while True:
        try:
            user_input = input("query> ").strip()

            if not user_input:
                continue

            if user_input.lower() == "quit":
                print("Exiting.")
                break

            if user_input.lower() == "list":
                list_all_episodes()
                continue

            parts = user_input.split(maxsplit=1)
            if len(parts) < 2:
                print("⚠️ Usage: e <search query> or r <search query>")
                continue

            command, query = parts

            if command.lower() == "e":
                query_episodes(query)
            elif command.lower() == "r":
                query_reflections(query)
            else:
                print(f"⚠️ Unknown command: {command}")

        except KeyboardInterrupt:
            print("\nExiting.")
            break

def main():
    """Main function"""
    if len(sys.argv) > 1:
        # Search from command line arguments
        query = " ".join(sys.argv[1:])
        print(f"\nSearch query: '{query}'\n")
        query_episodes(query)
        query_reflections(query)
    else:
        # Interactive mode
        interactive_mode()

if __name__ == "__main__":
    main()

I'll test the implementation now.
Since I want to ask about what kinds of episodes are remembered through conversation, I'll execute the query "Tell me about my calculation error tendencies".

================================================================================
🔍 AgentCore Memory - Long-term Memory Query Tool
================================================================================
Memory ID: sample_episode_memory-XXXXXXXXXXXX
Actor ID: demo_user
Session ID: demo_session

================================================================================
🔍 Conversation Mode
================================================================================
Commands:
  e <search query>  - Search episodes
  r <search query>  - Search reflections
  list           - List all episodes
  quit           - Exit

query> e Tell me about my calculation error tendencies

================================================================================
📖 Episode Search: 'Tell me about my calculation error tendencies'
================================================================================3 episodes found

Here are the results that were returned.

The content follows the five axes I mentioned at the beginning with thorough analysis. Since each result has quite a lot of volume, filtering by relevance or limiting to a certain number of top results seems important.

Now let's retrieve the reflections as well.

query> r Tell me about my calculation error tendencies

================================================================================
💡 Reflection Search: 'Tell me about my calculation error tendencies'
================================================================================
✓ 3 reflections found

After examining the data in detail, I found that episode memory and reflection memory differ in both structure and content.

Differences Between Episode Memory and Reflection Memory

Characteristics of Episode Memory

Episode memory is a detailed record of a specific conversation session. It stores "what happened" in concrete terms.
Looking at the data structure, it contains information on the aspects mentioned at the beginning:

  • situation
  • intent
  • assessment
  • justification
  • reflection
  • turns (details of each turn)

Within the turns, there are records of what actions the assistant took at each turn and the thought process behind why those actions were chosen.

For example, in the episode memory of a session where a user answered problems incorrectly, the following specific information was recorded:

  • The user responded with "1 21 2 4331 3 312"
  • The assistant used the calculator tool three times
  • The correct answers were 0.875, [-3, -2], and 12
  • All of the user's answers were incorrect

Characteristics of Reflection Memory

In contrast, reflection memory is "learnings" extracted from multiple episodes. It stores abstracted "what was learned."

There were two patterns of reflection memory:

The first is in a form similar to an episode summary, with a structure similar to episode memory.

The second has the following structure:

  • title (pattern title)
  • use_cases (applicable use cases)
  • hints (practical hints)
  • confidence (confidence score)

Looking at the actual data:

{
  "title": "Strategic Use of Calculator Tool for Math Verification",
  "hints": "Match the calculator function to the specific mathematical operation: 
            use 'evaluate' for arithmetic expressions, 
            'solve' for equations, 
            'derive' for derivatives, 
            'integrate' for integrals...",
  "confidence": "0.9"
}

It has extracted the learning that the calculator tool should be used strategically for math verification. Additionally, it includes specific hints that arithmetic expressions should use "evaluate," equations should use "solve," derivatives should use "derive," and integrals should use "integrate." This seems to be knowledge abstracted from the AI agent's experiences rather than human insight. It's interesting, and I get the impression that if there were actual use cases, the agent could operate more efficiently by leveraging its experience.

Relationship Between the Two Types of Memory

If episode memory is a record of specific experiences, reflection memory represents insights gained from multiple experiences.

I understand that reflection memory is extracted as generalized patterns and best practices from analyzing episode memory.

This allows the AI agent not only to reference past specific experiences but also to apply lessons learned from them to future interactions. I learned a lot by looking at the actual log structure.

Conclusion

I tried out AgentCore Memory's new long-term memory strategy "Episodic memory"!
The reflection process is interestingly different from other long-term memory strategies. I feel that as knowledge accumulates, the agent can provide better advice, but I wonder if it's suitable for production use.

I think this would be good for use cases where experience matters, but I don't have a clear enough image to declare specific use cases confidently at this point. If I find concrete use case examples, I'll share them in another blog post!

I hope this article was helpful. Thank you for reading to the end!

Supplement: Best Practices

Here's a translation of the best practices for handling this episodic memory strategy from the official documentation. There are also examples of how to use it, which would be good to reference when using this strategy.

https://docs.aws.amazon.com/ja_jp/bedrock-agentcore/latest/devguide/episodic-memory-strategy.html

There are several ways to use episodic memory.

When using in agent code:

When starting a new task, configure your agent to query the most similar episodes and reflections. Also, query related episodes or reflections subsequently based on some logic.

When creating short-term memory with CreateEvent, including TOOL results yields optimal results.

For similar successful episodes, linearize the turns within the episode and provide only this to the agent to focus it on key steps.

When using manually:

Look at reflections and failed episodes to see if there are any issues that could be resolved by updating your agent code.

When executing searches, note that memory records are indexed based on "intent" for episodes and "use cases" for reflections.

In other memory strategies, memory records are generated regularly throughout the interaction. In contrast, episodic memory records are only generated when AgentCore Memory detects a completed episode. If an episode is not complete, generation may take time as the system waits to see whether the conversation continues.

Share this article

FacebookHatena blogX

Related articles