![[アップデート]Amazon Bedrock AgentCore Memoryに新しく追加された長期記憶戦略Episodic memoryを試してみた](https://images.ctfassets.net/ct0aopd36mqt/33a7q65plkoztFWVfWxPWl/a718447bea0d93a2d461000926d65428/reinvent2025_devio_update_w1200h630.png?w=3840&fm=webp)
[アップデート]Amazon Bedrock AgentCore Memoryに新しく追加された長期記憶戦略Episodic memoryを試してみた
はじめに
こんにちは、コンサルティング部の神野です!
Amazon Bedrock AgentCoreに新しい長期記憶戦略「Episodic memory(エピソード記憶)」が追加されました!
この機能により、AIエージェントが過去の経験から学習し、その教訓を将来のインタラクションに活用できるようになります。ただ今までの長期記憶戦略とは何が違うの?と気になるかと思います。
例えば、AWS公式ブログに記載があった旅行予約エージェントを例に考えてみます。
時間が経つにつれ、エージェントはユーザーの予約パターンを学習します。「出張時はクライアントミーティングのため、フライトを遅い時間に変更することが多い」といったパターンを認識し、次回の出張予約時には、学習したパターンに基づいて柔軟な帰路オプションを先回りして提案できるようになるといったことが可能になります。
経験から知見を抽出してAIエージェントが活かせるようになるイメージでしょうか。実際に動かしてみたいと思います!
今回のアップデートについて
今までの長期記憶戦略
本アップデートまではAgentCore Memoryには以下の3つのビルトインの長期記憶戦略がありました。
-
Semantic Memory
- 事実や知識を抽出・保存
-
User Preference
- ユーザーの好みを抽出
-
Summary(要約)
- 会話の要約を生成・保持
ここに新しいビルトインの長期記憶戦略が追加された形になります。
Episodic ,emory(エピソード記憶)
今回追加されたEpisodic memoryは、今までの長期記憶戦略とは少し異なります。
ユーザーとのやり取りを「エピソード」として構造化し、さらに複数のエピソードを分析してリフレクション(振り返り)を生成します。
もう少し具体的に仕組みを見ていきます。
Episodic memoryの仕組み
Episodic memory strategyは、3つのステップが自動で動作して長期記憶として抽出されます。
公式ドキュメントから動作フロー図を引用させていただきます。

Extraction(抽出)
進行中のインタラクションを分析し、エピソードが完了したかどうかを判定します。
他の戦略とは異なり、Episodic memoryはエピソードの完了を検出した時点でのみレコードを生成します。
Consolidation(統合)
エピソードが完了すると、関連するイベントを1つの構造化されたエピソードレコードに統合します。各エピソードには以下の情報が含まれます。
- Situation
- エピソードの背景・状況
- Intent
- ユーザーまたはエージェントの意図
- Assessment
- 結果の評価
- Justification
- 判断の根拠
- Episode-level Reflection
- エピソードレベルの振り返り
Reflection(振り返り)
複数のエピソードを横断して分析し、より広範な洞察を抽出します。
Reflectionが抽出する情報の例
- 特定のタスクタイプで一貫して成功するツールの組み合わせ
- 失敗したアプローチと、それを解決した方法のパターン
- 類似シナリオの複数の成功エピソードからのベストプラクティス
ここが特徴的ですよね。その他の長期記憶の戦略だと、抽出して構造化して終わっていたので、振り返りまであるのがこの戦略の特徴ですね。
どういったシチュエーションで有効か
Episodic memoryは、以下のようなシナリオで効果を発揮しやすいのかなと思います。
具体的な例はAWS公式ドキュメントの例を参考にしています。
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.
| ユースケース | 説明 |
|---|---|
| カスタマーサポート | 過去の対応パターンから効果的な解決策を学習 |
| エージェント駆動ワークフロー | 過去のタスク実行経験を次のタスクに活用 |
| コードアシスタント | セッション履歴に基づいたコンテキスト理解 |
| トラブルシューティング | 過去の問題解決パターンを参照 |
| パーソナル生産性ツール | ユーザーの作業パターンを学習 |
経験などを記憶させて回答させるケースには向いている印象ですね。あとは振り返ってより練度を高めたいといったオペレーションにも良さそうです。
他の戦略との使い分け
改めて他の戦略も含めて振り返ってみると、それぞれざっくりと下記の役割を果たします。
- Semantic memory
- 「何を知っているか」(事実・知識)
- User Preference
- 「ユーザーは何が好きか」(好み)
- Summary
- 「このセッションで何が話されたか」(要約)
- Episodic memory
- 何が起きて、なぜ成功/失敗したか
- 経験から成功へのナレッジを抽出
- 何が起きて、なぜ成功/失敗したか
早速実装して試してみます。
Strands Agentsでエージェントを作成
では、実際にEpisodic memoryを使ったエージェントを作成してみましょう。
環境セットアップ
# プロジェクトディレクトリの作成
mkdir agentcore-episodic-demo
cd agentcore-episodic-demo
# 仮想環境の作成・有効化
python -m venv .venv
source .venv/bin/activate # Windowsの場合: .venv\Scripts\activate
# 依存関係のインストール
pip install bedrock-agentcore strands-agents strands-agents-tools bedrock-agentcore-starter-toolkit
Episodic Memoryリソースの作成
コンソール上で作成します。設定する値は下記とします。
- Memory name
- Sample_episode_memory
- Built-in strategy
- Episodesにチェック
- Strategy name
- episodeStrategy
- Namespace for extracted memories
- /strategies/{memoryStrategyId}/actors/{actorId}/sessions/{sessionId}
- Session ID毎に集約
- /strategies/{memoryStrategyId}/actors/{actorId}/sessions/{sessionId}
- Namespace for reflection
- /strategies/{memoryStrategyId}/actors/{actorId}
- actor ID毎に集約
- /strategies/{memoryStrategyId}/actors/{actorId}
- Strategy name
- Episodesにチェック

作成したら下記値からMemory IDを控えておきます。

またStrategy IDも必要なので下記から控えておきます。

ここまで出来たら準備万端です。エージェントの実装を進めていきます。
Strands Agentの実装
agent.pyを作成します。シンプルに計算を行うエージェントです。
このエージェントに計算問題を出力させて、間違って回答して回答を分析するようなテストをしてみます。
"""
AgentCore Memory - Episodic Memory を活用したStrands Agent
Strandsの Session Manager を使用して、短期記憶とEpisodic Memory(長期記憶)を自動統合します。
使用方法:
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():
"""コマンドライン引数をパース"""
parser = argparse.ArgumentParser(
description="AgentCore Episodic Memory デモ - 計算アシスタント"
)
parser.add_argument(
"-a",
"--actor-id",
type=str,
default="demo_user",
help="ユーザー(アクター)ID (デフォルト: demo_user)",
)
parser.add_argument(
"-s",
"--session-id",
type=str,
default="calculation_session_001",
help="セッションID (デフォルト: calculation_session_001)",
)
parser.add_argument(
"-m",
"--memory-id",
type=str,
default=None,
help="Memory ID (デフォルト: 環境変数 MEMORY_ID を使用)",
)
parser.add_argument("-v", "--verbose", action="store_true", help="詳細ログを有効化")
parser.add_argument(
"--strategy-id",
type=str,
default=None,
help="Memory Strategy ID (デフォルト: 環境変数 MEMORY_STRATEGY_ID を使用)",
)
return parser.parse_args()
# 引数をパース
args = parse_args()
# ロギングの設定
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()],
)
# AgentCore Memory関連のログを有効化
logging.getLogger("bedrock_agentcore").setLevel(
logging.DEBUG if args.verbose else logging.INFO
)
# 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
# Memory ID, Strategy IDを引数または環境変数から取得
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が設定されていません")
print("先に setup_memory.py を実行してください")
exit(1)
if not MEMORY_STRATEGY_ID:
print("⚠️ MEMORY_STRATEGY_IDが設定されていません")
print(
"環境変数 MEMORY_STRATEGY_ID または --strategy-id オプションで指定してください"
)
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設定(Episodic Memory付き)
config = AgentCoreMemoryConfig(
memory_id=MEMORY_ID,
session_id=SESSION_ID,
actor_id=ACTOR_ID,
retrieval_config={
# エピソード(セッション単位の経験)を取得
f"/strategies/{MEMORY_STRATEGY_ID}/actors/{{actorId}}/sessions/{{sessionId}}": RetrievalConfig(
top_k=5
),
# リフレクション(アクター全体の洞察)を取得
f"/strategies/{MEMORY_STRATEGY_ID}/actors/{{actorId}}": RetrievalConfig(
top_k=3
),
},
)
# Session Managerの作成
session_manager = AgentCoreMemorySessionManager(
agentcore_memory_config=config, region_name="us-west-2"
)
# Strands Agentの作成(Session Manager統合)
agent = Agent(
model="us.anthropic.claude-haiku-4-5-20251001-v1:0",
tools=[calculator],
system_prompt="""あなたは親切な計算アシスタントです。
ユーザーの計算リクエストに対して、calculatorツールを使用して正確な結果を提供してください。
過去のエピソードやリフレクションから学習した内容を活用して分析やアドバイスも伝えてください。""",
session_manager=session_manager,
)
print("✅ Strands Agent with Episodic Memory 初期化完了")
def main():
"""メイン関数 - 対話ループ"""
print("=" * 60)
print("AgentCore Episodic Memory デモ - 計算アシスタント")
print("=" * 60)
print("\n計算のリクエストを入力してください。")
print("'quit' で終了します。\n")
while True:
try:
user_input = input("\n入力> ").strip()
if not user_input:
continue
if user_input.lower() == "quit":
print("\n終了します。")
break
print(f"\n👤 ユーザー: {user_input}")
response = agent(user_input)
print(f"\n🤖 アシスタント: {response.message}")
except KeyboardInterrupt:
print("\n\n終了します。")
break
if __name__ == "__main__":
main()
AgentCoreMemorySessionManagerを使ってメモリの管理を行います。難しい実装をしなくとも、短期記憶は保存および長期記憶は参照されるので便利ですね。
テスト
先ほどコンソールで控えたIDをMEMORY_ID、MEMORY_STRATEGY_IDに設定します。
設定したら実行可能です。今回はサクッとローカルで挙動を確認することにします。
# 環境変数を設定
export MEMORY_ID=mem_xxxxxxxxxxxxxxx
export MEMORY_STRATEGY_ID=xxx
# エージェントを実行
python agent.py -a demo_user -s demo_session
エージェントに計算問題を出力させて、分析のための情報を与えます。
Actor IDとSession IDは引数で指定します。
回答は誤って回答させます。やり取りやログは抜粋して載せますが長いので折りたたみます。
ログ
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 初期化完了
============================================================
AgentCore Episodic Memory デモ - 計算アシスタント
============================================================
計算のリクエストを入力してください。
'quit' で終了します。
入力> 答えなしで計算問題出して。
👤 ユーザー: 答えなしで計算問題出して。
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
# 計算問題を3つ出題します!
**問題1:**
$\frac{3}{4} + \frac{5}{8} - \frac{1}{2}$ を計算してください。
**問題2:**
$x^2 + 5x + 6 = 0$ を満たす $x$ の値を求めてください。
**問題3:**
$f(x) = 2x^3 - 3x^2 + 1$ の $x = 2$ における導関数の値を求めてください。
---
考えてみて、解INFO | bedrock_agentcore.memory.client | Created event: 0000001764751010726#99f264bd
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 0000001764751011726#5e156fae
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 0000001764751012726#ecb4fb0b
けたら答えを教えてください!わからない場合はヒントをあげたり、一緒に解くこともできますよ。
入力> 1 21 2 4331 3 312です
👤 ユーザー: 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
答えを確認してみましょう!
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
では、導関数の値を 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
---
## 採点結果
| 問題 | あなたの答え | 正解 | 判定 |
| --------- | ------------ | ---------- | ---- |
| **問題1** | 1.21 | **0.875** | ❌ |
| **問題2** | 4331 | **-3, -2** | ❌ |
| **問題3** | 312 | **12** | ❌ |
---
残念ながら3問とも不正解でした😅
**解説:**
- **問題1:** 分数の通分がキーポイント。3/4 + 5/8 - 1/2 = 6/8 + 5/8 - 4/8 = 7/8 = 0.875
- **問題2:** 因数分解すると (x+3)(x+2) = 0 となり、x = -3 または x = -2
- **問題3:** 導関数は f'(x) = 6x² - 6x で、x=2 を代入すると 6(4) - 6(2) = 24 - 12 = 12
もINFO | bedrock_agentcore.memory.client | Created event: 0000001764751035249#0fe5365c
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 0000001764751036249#2c6bb589
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 0000001764751037249#ab621293
う一度チャレンジしたい問題があれば、解き方を一緒に確認することもできますよ!
入力> もう一問出して
👤 ユーザー: もう一問出して
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
# 新しい問題を出題します!
**問題4:**
$\int (3x^2 + 2x - 1) dx$ を計算してください。(不定積分)
---
答えを求INFO | bedrock_agentcore.memory.client | Created event: 0000001764751051718#90930fa4
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 0000001764751052718#2b3c1cc2
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 0000001764751053718#20f50098
めてみてください!
入力> 21 + Cです!
👤 ユーザー: 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
確認してみましょう!
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
## 採点結果
| 問題 | あなたの答え | 正解 | 判定 |
| --------- | ------------ | ----------------------- | ---- |
| **問題4** | 21 + C | **$x^3 + x^2 - x + C$** | ❌ |
---
残念ながら不正解です😅
**解説:**
不定積分は各項ごとに計算します。
$$\int (3x^2 + 2x - 1) dx$$
- $3x^2$ を積分 → $\frac{3x^3}{3} = x^3$
- $2x$ を積分 → $\frac{2x^2}{2} = x^2$
- $-1$ を積分 → $-x$
したがって答えは:**$x^3 + x^2 - x + C$**
「+ C」を付けるのは正しい習慣ですが、積分結果の式の形が大事なポイントです!
次INFO | bedrock_agentcore.memory.client | Created event: 0000001764751074048#f81afc61
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 0000001764751075048#e5c3e581
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 0000001764751076048#b65ad49e
の問題にチャレンジしますか?
入力> 今日はこれで終わりにしましょう!!
👤 ユーザー: 今日はこれで終わりにしましょう!!
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
了解です!お疲れ様でした!🎉
今日の計算問題、チャレンジしてくれてありがとうございました!
**今日のまとめ:**
- 問題1~3:分数計算、方程式、微分
- 問題4:積分
次回また計算問題や数学の解説が必要な時は、いつでも気軽に声をかけてくださいね。一緒に頑張りましょう!💪
またINFO | bedrock_agentcore.memory.client | Created event: 0000001764751087112#e0773891
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 0000001764751088112#6544a1e8
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 0000001764751089112#d895836f
明日!👋
数分まつと、MemoryのCloudWatch Logsに抽出実行されたログを見つけました。
{
"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"
}
ログを見るとConsolidationとReflectionどちらも実施されていそうですね。
計算の回答結果を分析してと再度エージェントに聞いてみます。
回答全文
入力> 私の過去の計算結果から傾向やアドバイスを分析してください。
👤 ユーザー: 私の過去の計算結果から傾向やアドバイスを分析してください。
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
# 📊 あなたの計算結果の傾向分析
今日の4問すべてのあなたの回答を分析してみました:
---
## 📈 傾向の分析
| 項目 | 詳細 |
| ------------ | ------------------------------------ |
| **正解率** | 0/4 (0%) |
| **傾向** | すべての問題で大きく異なる答えを提出 |
| **パターン** | 数字の組み合わせのようなランダム性 |
---
## 🔍 詳細な観察
### **問題別の特徴:**
1. **問題1(分数計算)**
- あなたの答え: 1.21
- 正解: 0.875
- **ズレ:** 38% の誤差
2. **問題2(二次方程式)**
- あなたの答え: 4331
- 正解: -3, -2
- **ズレ:** 方程式を解く方法の理解不足の可能性
3. **問題3(微分の値)**
- あなたの答え: 312
- 正解: 12
- **ズレ:** 26倍大きい答え
4. **問題4(不定積分)**
- あなたの答え: 21 + C
- 正解: x³ + x² - x + C
- **ズレ:** 積分結果の形式を理解していない可能性
---
## 💡 改善アドバイス
### **強みは:**
✅ **積極的に練習に取り組もうとする姿勢** - 間違えても新しい問題にチャレンジし続けた点は素晴らしいです!
### **改善点:**
1. **基礎概念の理解**
- 分数の通分、因数分解など基本スキルの復習が必要かもしれません
2. **計算ステップの確認**
- 一度に答えを出すのではなく、各ステップを丁寧に計算することが重要です
3. **問題形式の認識**
- 微分・積分は「答えの形式」が重要です(例:x³ + x² - x のように項の形)
4. **次回のアプローチ**
- わからない問題は、まず「ヒントをください」と言うのもOKです
- 一緒にステップバイステップで解くことも可能です
---
## 🎯 次回のご提案
次回練習する時は:
1. **簡単な問題から始める** こともお勧めします
2. **計算過程を見せてもらう** ことで、どこで間違っているか特定できます
3. **特定の分野を集中練習** するのも効果的かもしれません
頑張INFO | bedrock_agentcore.memory.client | Created event: 0000001764752307293#ebacaabf
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 0000001764752308293#4b8ffcd2
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 0000001764752309293#8462a34a
ってください!💪
短期記憶も使っているので、一概に長期記憶が効いていると言いづらいですが、下記ログを見ると長期記憶を両方とも取得できていそうです。
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
具体的にどんなデータ構造で保存されているのか確認してみます。
下記テスト用のスクリプトを実行して、長期記憶を取得してみます。
MemoryIDやStrategy IDは埋め込んでいるので、使用される場合は適宜修正ください。
コード全量
"""
AgentCore Memory - 長期記憶クエリスクリプト
エピソードとリフレクションを直接検索して表示します。
"""
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が設定されていません")
print("export MEMORY_ID=mem_xxxxxxxx を実行してください")
sys.exit(1)
# Memory Clientの初期化
memory_client = MemoryClient(region_name="us-west-2")
print("=" * 80)
print("🔍 AgentCore Memory - 長期記憶クエリツール")
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):
"""エピソード(セッション単位の経験)を検索"""
print("\n" + "=" * 80)
print(f"📖 エピソード検索: '{search_query}'")
print("=" * 80)
namespace = f"/strategies/{STRATEGY_ID}/actors/{ACTOR_ID}/sessions/{SESSION_ID}"
try:
# retrieve_memories メソッドを使用(スネークケース)
records = memory_client.retrieve_memories(
memory_id=MEMORY_ID,
namespace=namespace,
query=search_query,
top_k=top_k,
)
if not records:
print("✗ エピソードが見つかりませんでした")
return
print(f"✓ {len(records)}件のエピソードが見つかりました\n")
for i, record in enumerate(records, 1):
content = record.get("content", {}).get("text", "")
record_id = record.get("id", "unknown")
print(f"【エピソード {i}】")
print(f"ID: {record_id}")
print(f"内容:\n{content}\n")
print("-" * 80)
except Exception as e:
print(f"⚠️ エラー: {e}")
def query_reflections(search_query: str, top_k: int = 3):
"""リフレクション(アクター全体の洞察)を検索"""
print("\n" + "=" * 80)
print(f"💡 リフレクション検索: '{search_query}'")
print("=" * 80)
namespace = f"/strategies/{STRATEGY_ID}/actors/{ACTOR_ID}"
try:
# retrieve_memories メソッドを使用(スネークケース)
records = memory_client.retrieve_memories(
memory_id=MEMORY_ID,
namespace=namespace,
query=search_query,
top_k=top_k,
)
if not records:
print("✗ リフレクションが見つかりませんでした")
print("(複数のエピソードが蓄積されると自動生成されます)")
return
print(f"✓ {len(records)}件のリフレクションが見つかりました\n")
for i, record in enumerate(records, 1):
content = record.get("content", {}).get("text", "")
record_id = record.get("id", "unknown")
print(f"【リフレクション {i}】")
print(f"ID: {record_id}")
print(f"内容:\n{content}\n")
print("-" * 80)
except Exception as e:
print(f"⚠️ エラー: {e}")
def list_all_episodes(max_results: int = 10):
"""全エピソードをリスト表示"""
print("\n" + "=" * 80)
print(f"📋 全エピソード一覧(最大{max_results}件)")
print("=" * 80)
namespace = f"/strategies/episodeStratedgy-XXXXXXXXXXXX/actors/{ACTOR_ID}/sessions/{SESSION_ID}"
try:
# 空のクエリで全件取得を試みる
records = memory_client.retrieve_memories(
memory_id=MEMORY_ID,
namespace=namespace,
query="",
top_k=max_results,
)
if not records:
print("✗ エピソードが見つかりませんでした")
return
print(f"✓ {len(records)}件のエピソードが見つかりました\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"⚠️ エラー: {e}")
def interactive_mode():
"""対話モード"""
print("\n" + "=" * 80)
print("🔍 対話モード")
print("=" * 80)
print("コマンド:")
print(" e <検索クエリ> - エピソードを検索")
print(" r <検索クエリ> - リフレクションを検索")
print(" list - 全エピソードをリスト表示")
print(" quit - 終了")
print()
while True:
try:
user_input = input("query> ").strip()
if not user_input:
continue
if user_input.lower() == "quit":
print("終了します。")
break
if user_input.lower() == "list":
list_all_episodes()
continue
parts = user_input.split(maxsplit=1)
if len(parts) < 2:
print("⚠️ 使用方法: e <検索クエリ> または r <検索クエリ>")
continue
command, query = parts
if command.lower() == "e":
query_episodes(query)
elif command.lower() == "r":
query_reflections(query)
else:
print(f"⚠️ 不明なコマンド: {command}")
except KeyboardInterrupt:
print("\n終了します。")
break
def main():
"""メイン関数"""
if len(sys.argv) > 1:
# コマンドライン引数から検索
query = " ".join(sys.argv[1:])
print(f"\n検索クエリ: '{query}'\n")
query_episodes(query)
query_reflections(query)
else:
# 対話モード
interactive_mode()
if __name__ == "__main__":
main()
作成したので実行してみます。
対話でどういったエピソードの記憶があるか聞きたいので「私の計算の失敗傾向について教えて」とクエリを実行してみます。
================================================================================
🔍 AgentCore Memory - 長期記憶クエリツール
================================================================================
Memory ID: sample_episode_memory-XXXXXXXXXXXX
Actor ID: demo_user
Session ID: demo_session
================================================================================
🔍 対話モード
================================================================================
コマンド:
e <検索クエリ> - エピソードを検索
r <検索クエリ> - リフレクションを検索
list - 全エピソードをリスト表示
quit - 終了
query> e 私の計算の失敗傾向について教えて
================================================================================
📖 エピソード検索: '私の計算の失敗傾向について教えて'
================================================================================
✓ 3件のエピソードが見つかりました
するとこんな感じで結果が返却されました。
ログ
【エピソード 1】
ID: unknown
内容:
{"situation":"Based on the limited information provided, it appears the user has submitted their math calculation results to the AI assistant, requesting analysis of these results and seeking feedback on their mathematical performance in Japanese. The user likely has a history of solving mathematical problems and wanted expert evaluation of their work.","intent":"The user's primary goal was to receive a comprehensive analysis of their math calculation results, understand patterns in their performance, identify their strengths and weaknesses, and obtain specific recommendations for improving their mathematical skills.","assessment":"Yes","justification":"The assistant provided a thorough analysis of the user's math performance, including specific numerical data showing 0% accuracy, detailed error analysis for each problem type, identified performance patterns, and offered targeted advice for improvement. The comprehensive structure of the response addressing all aspects of the user's request indicates successful fulfillment of the user's goal.","reflection":"The assistant effectively structured their analysis into multiple clearly defined sections (trend analysis, problem-specific observations, improvement advice, and next steps), which created a comprehensive and organized response. This methodical approach allowed the assistant to thoroughly address different aspects of mathematical performance evaluation. The assistant demonstrated strong analytical capabilities by providing specific numerical assessments (0% accuracy rate) and detailed error analysis for each of four different math problems, suggesting they effectively processed and interpreted the user's prior work. The response balanced identifying weaknesses with constructive suggestions, maintaining a supportive tone that encouraged continued effort. The assistant did not need to use external tools for this analysis, relying instead on careful organization of information presumably available from previous interactions. For similar situations involving performance analysis, this approach of segmenting feedback into clear categories (trends, specific observations, strengths/weaknesses, and actionable next steps) represents an effective pattern that could be applied to various educational assessment contexts.","turns":[{"situation":"The user has requested analysis of their past calculation results, asking for trend analysis and advice in Japanese. The user appears to be seeking feedback on their math performance.","intent":"The assistant aims to analyze the user's math calculation results, identify patterns in their performance, and provide constructive feedback and recommendations for improvement.","action":"The assistant provided a comprehensive analysis without using external tools, organizing the response with detailed sections including trend analysis, observations per problem, improvement advice highlighting strengths and weaknesses, and suggestions for next steps.","thought":"The assistant chose to structure the analysis with multiple sections because the task required evaluation of mathematical work across different problem types. The response includes specific numerical data about the user's accuracy (0% correct), detailed error analysis for each problem, and targeted advice, suggesting the assistant inferred this information from previous interactions not shown in this conversation sample.","assessmentAssistant":"Yes, the assistant successfully achieved its goal by providing a detailed analysis of the user's math performance with specific feedback on four different math problems, identifying trends in errors, and offering constructive advice for improvement with a supportive tone.","assessmentUser":"Yes, this turn represents the END OF THE CONVERSATION EPISODE as there is no next turn showing the user's response or follow-up questions, and the assistant's comprehensive analysis and recommendations provide a natural conclusion to the inquiry about past calculation results."}]}
--------------------------------------------------------------------------------
【エピソード 2】
ID: unknown
内容:
{"situation":"The conversation appears to be ending after a math practice session where the user and AI assistant worked through various mathematical problems. The user has explicitly indicated in Japanese (\"今日はこれで終わりにしましょう!!\") that they want to conclude the session for the day.","intent":"The user's intent was to formally end the current math practice session and receive appropriate closure from the assistant.","assessment":"Yes","justification":"Based on the summary provided, the assistant successfully recognized the user's request to end the session, acknowledged it appropriately, provided a summary of the topics covered during their practice (fractions, equations, differentiation, and integration), and closed with an encouraging tone that welcomed future interactions.","reflection":"The assistant demonstrated effective communication by properly recognizing the multilingual cue from the user (Japanese text indicating session end) and responding appropriately to this social signal rather than continuing with more math content. The assistant successfully employed a closure pattern that included acknowledgment, summary of accomplishments, and forward-looking encouragement. This pattern helps provide a sense of completion and progress to the user while maintaining engagement for future sessions. For educational interactions like this math tutoring session, such structured closures are particularly valuable as they reinforce learning by recapping covered material. The assistant avoided the common mistake of ignoring closure requests or responding with unnecessary additional educational content when the user has clearly signaled they are finished for the day.","turns":[{"situation":"The user has indicated they want to end the math practice session for today with the message \"今日はこれで終わりにしましょう!!\" (Let's finish for today!). After multiple math problems and feedback sessions, the user is ready to conclude the conversation.","intent":"To acknowledge the user's request to end the session, provide a friendly closure, and summarize what was covered during the math practice session.","action":"The assistant provided a polite closing message acknowledging the end of the session, summarizing the types of math problems covered (fractions, equations, differentiation, and integration), and encouraging the user to return for future practice.","thought":"The assistant recognized the user's desire to conclude the session and responded with an appropriate closing message. The summary of covered topics helps reinforce the learning experience, while the encouraging tone aims to maintain engagement for future interactions.","assessmentAssistant":"Yes, the assistant successfully acknowledged the user's request to end the session and provided a friendly closing message that appropriately summarized the math practice session and left the door open for future interactions.","assessmentUser":"Yes, this is clearly the end of the conversation episode as the user explicitly stated they wanted to finish for today, and there are no further messages indicating continuation of the conversation."}]}
--------------------------------------------------------------------------------
【エピソード 3】
ID: unknown
内容:
・・・
冒頭に触れた5つの軸に従ってしっかり分析されていますね。1つ1つ結構なボリュームなので、関連度や上位何件を取るかなどのフィルタリングは大事になってきそうな印象です。
あとはリフレクションも取得してみます。
query> r 私の計算の失敗傾向について教えて
================================================================================
💡 リフレクション検索: '私の計算の失敗傾向について教えて'
================================================================================
✓ 3件のリフレクションが見つかりました
リフレクション結果も添付します。こちらも長いので折りたたんでいます。
ログ
【リフレクション 1】
ID: unknown
内容:
{"situation":"Based on the limited information provided, it appears the user has submitted their math calculation results to the AI assistant, requesting analysis of these results and seeking feedback on their mathematical performance in Japanese. The user likely has a history of solving mathematical problems and wanted expert evaluation of their work.","intent":"The user's primary goal was to receive a comprehensive analysis of their math calculation results, understand patterns in their performance, identify their strengths and weaknesses, and obtain specific recommendations for improving their mathematical skills.","assessment":"Yes","justification":"The assistant provided a thorough analysis of the user's math performance, including specific numerical data showing 0% accuracy, detailed error analysis for each problem type, identified performance patterns, and offered targeted advice for improvement. The comprehensive structure of the response addressing all aspects of the user's request indicates successful fulfillment of the user's goal.","reflection":"The assistant effectively structured their analysis into multiple clearly defined sections (trend analysis, problem-specific observations, improvement advice, and next steps), which created a comprehensive and organized response. This methodical approach allowed the assistant to thoroughly address different aspects of mathematical performance evaluation. The assistant demonstrated strong analytical capabilities by providing specific numerical assessments (0% accuracy rate) and detailed error analysis for each of four different math problems, suggesting they effectively processed and interpreted the user's prior work. The response balanced identifying weaknesses with constructive suggestions, maintaining a supportive tone that encouraged continued effort. The assistant did not need to use external tools for this analysis, relying instead on careful organization of information presumably available from previous interactions. For similar situations involving performance analysis, this approach of segmenting feedback into clear categories (trends, specific observations, strengths/weaknesses, and actionable next steps) represents an effective pattern that could be applied to various educational assessment contexts.","turns":[{"situation":"The user has requested analysis of their past calculation results, asking for trend analysis and advice in Japanese. The user appears to be seeking feedback on their math performance.","intent":"The assistant aims to analyze the user's math calculation results, identify patterns in their performance, and provide constructive feedback and recommendations for improvement.","action":"The assistant provided a comprehensive analysis without using external tools, organizing the response with detailed sections including trend analysis, observations per problem, improvement advice highlighting strengths and weaknesses, and suggestions for next steps.","thought":"The assistant chose to structure the analysis with multiple sections because the task required evaluation of mathematical work across different problem types. The response includes specific numerical data about the user's accuracy (0% correct), detailed error analysis for each problem, and targeted advice, suggesting the assistant inferred this information from previous interactions not shown in this conversation sample.","assessmentAssistant":"Yes, the assistant successfully achieved its goal by providing a detailed analysis of the user's math performance with specific feedback on four different math problems, identifying trends in errors, and offering constructive advice for improvement with a supportive tone.","assessmentUser":"Yes, this turn represents the END OF THE CONVERSATION EPISODE as there is no next turn showing the user's response or follow-up questions, and the assistant's comprehensive analysis and recommendations provide a natural conclusion to the inquiry about past calculation results."}]}
--------------------------------------------------------------------------------
【リフレクション 2】
ID: unknown
内容:
{"title":"Strategic Use of Calculator Tool for Math Verification","use_cases":"Applies when users are practicing math problems and need verification of their work. This is particularly useful for educational scenarios where the assistant needs to check mathematical calculations, solutions to equations, derivatives, integrals, or other mathematical operations. The pattern helps maintain accuracy when providing feedback on user-submitted math solutions and demonstrates proper tool selection based on the mathematical operation being verified.","hints":"Match the calculator function to the specific mathematical operation: use \"evaluate\" for arithmetic expressions, \"solve\" for equations, \"derive\" for derivatives, and \"integrate\" for integrals. Format expressions properly using algebraic notation (e.g., 3*x^2 instead of 3x^2) for the calculator tool. For multi-step problems (like finding a derivative at a specific point), break the verification into sequential tool uses - first derive the expression, then substitute the value using \"evaluate\" with the variables parameter. Always double-check that the expression entered matches exactly what was in the original problem to ensure accurate verification.","confidence":"0.9"}
--------------------------------------------------------------------------------
【リフレクション 3】
ID: unknown
内容:
・・・
中身はほぼ一緒な気がしますが、微妙にデータ構造が違いますね。
より詳細に確認してみます。
エピソード記憶とリフレクション記憶の違いについて
実際に抽出されたデータを見てみると、エピソード記憶とリフレクション記憶では構造も中身も異なることがわかりました。
エピソード記憶の特徴
エピソード記憶は、特定の会話セッションの詳細な記録です。「何が起きたか」を具体的に保存しています。
データ構造を見てみると、冒頭に触れた観点の情報が含まれています。
- situation(状況)
- intent(意図)
- assessment(評価)
- justification(根拠)
- reflection(振り返り)
- turns(各ターンの詳細)
turnsの中には、各ターンでアシスタントがどんな行動を取ったか、なぜその行動を選んだかの思考プロセスまで記録されています。
例えば、問題に対して誤って回答しているセッションのエピソード記憶では以下のような具体的な情報が残っていました。
上から3つはカットしたストーリー3に記載がある情報です。(文字数が多すぎて添付できませんでした・・・)
イメージを掴んでもらうためにストーリー3は一部抜粋して添付します。
- ユーザーが「1 21 2 4331 3 312」と回答した
- アシスタントがcalculatorツールを3回使用した
- 正解は0.875、[-3, -2]、12だった
- ユーザーの回答はすべて不正解だった
ストーリー3の一部抜粋
{"situation":"The user has responded with what appears to be their answers to the three math problems: \"1 21 2 4331 3 312\". The user seems to be participating in the math problem exercise initiated in the previous turn.","intent":"To check the user's answers to the three math problems by using calculation tools to determine the correct solutions.","action":"The assistant used the calculator tool three times: (1) to evaluate 3/4 + 5/8 - 1/2, (2) to solve the quadratic equation x^2 + 5x + 6 = 0, and (3) to find the derivative of 2x^3 - 3x^2 + 1 with respect to x.","thought":"The assistant recognized that the user provided answers and decided to verify them using calculation tools to provide accurate feedback. For each problem, the assistant selected the appropriate calculator function (evaluate, solve, derive) with the exact expressions from the original problems.","assessmentAssistant":"Yes, the assistant successfully initiated the verification process by using the calculator tool with the appropriate functions and expressions for each problem. This allows the assistant to determine the correct answers to compare with the user's responses.","assessmentUser":"No, the next turn shows that the user is providing tool results for the calculations and there is additional calculation needed for problem 3, indicating the user is still engaged with solving the math problems."},{"situation":"The user's message・・・}}
詳細に書いていますよね。
リフレクション記憶の特徴
一方、リフレクション記憶は複数のエピソードから抽出された「学び」です。
「何を学んだか」を抽象化して保存しています。
リフレクション記憶には2つのパターンがありました。
1つ目はエピソードの要約のような形式で、エピソード記憶と似た構造を持っています。
2つ目が以下のような構造になっています。
- title(パターンのタイトル)
- use_cases(適用可能なユースケース)
- hints(実践的なヒント)
- confidence(信頼度スコア)
実際のデータを見てみると、こんな感じでした。
{
"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"
}
数学の検証にはcalculatorツールを戦略的に使うべき、という学びが抽出されていますね。さらに、算術式にはevaluate、方程式にはsolve、微分にはderive、積分にはintegrateを使うべきという具体的なヒントまで含まれています。これは人間がと言うよりは、AIエージェントがこの問題に対してどう対応するかの知見が抽象化されてたまっているのですね。面白いですし、実際に使えるケースがあったら経験が活きてエージェントがより効率的に動けるようになる印象を受けました。
2つの記憶の関係性
エピソード記憶が具体的な経験の記録だとすると、リフレクション記憶は複数の経験から得られた知見となっています。
エピソード記憶を分析して、そこから一般化されたパターンやベストプラクティスをリフレクション記憶として抽出していると理解しました。
これにより、AIエージェントは過去の具体的な経験を参照できるだけでなく、そこから学んだ教訓を将来のインタラクションに活かせるような作りになっていたんですね。実際にログの構造を見て勉強になりました。
おわりに
AgentCore Memoryの新しい長期記憶戦略「Episodic memory」を試してみました!
Reflectionの工程が他の長期記憶戦略と違って面白いですよね。ナレッジを溜めていけばより良いアドバイスがエージェントが出来そうになる予感がしたのですが、本番運用で使えるものか気になるところです。
経験が物を言うユースケースが向いていると思うのですが、現時点ではこれ!と明言できるほど私もイメージが湧いていないので、具体的なユースケース例が見つかりましたらまたブログで共有させてください!
本記事が少しでも役に立ちましたら幸いです。最後までご覧いただきありがとうございましたー!
補足:ベストプラクティスについて
このエピソード記憶戦略を扱う上でのベストプラクティスについて公式ドキュメントに記載があるので、翻訳して引用します。どう活用するかの例もあるのでこの戦略を使うときは参考にしたいですね。
エピソード記憶の活用方法はいくつかあります。
エージェントのコード内で利用する場合:
新しいタスクを開始する際、最も類似したエピソードと考察を問い合わせるようにエージェントを設定します。 また、何らかのロジックに基づいて、関連するエピソードや考察を後続で問い合わせます。
短期記憶をCreateEventで作成する際、TOOLの結果を含めると最適な結果が得られます。
類似した成功エピソードについては、エピソード内のターンを線形化し、エージェントに主要なステップのみを集中させるために、これだけをエージェントに与えます。
手動で利用する場合:
考察や失敗したエピソードを見て、エージェントのコードを更新することで解決できる問題がないか検討します。
検索を実行する際、メモリーレコードはエピソードでは「意図」、考察では「ユースケース」に基づいてインデックスが付けられていることに注意してください。
他の記憶戦略では、インタラクション全体を通して定期的にメモリーレコードが生成されます。 対照的に、エピソード記憶レコードは、AgentCore Memoryが完了したエピソードを検出した場合にのみ生成されます。 エピソードが完了していない場合、会話が継続されるかどうかをシステムが待機するため、生成に時間がかかります。










