Add intelligent memory capabilities to AI agents with Amazon Bedrock AgentCore Memory.
Amazon Bedrock AgentCore Memory is a fully managed service that gives your AI agents the ability to remember past interactions, enabling them to provide more intelligent, context-aware, and personalized conversations.
- AgentCore Runtime ⭐ - Serverless execution with auto-scaling and session management
- AgentCore Identity - Secure credential management for API keys and tokens
- AgentCore Memory ⭐ - State persistence and conversation history
- AgentCore Code Interpreter - Secure code execution sandbox
- AgentCore Browser - Cloud browser automation
- AgentCore Gateway - API management and tool discovery
- AgentCore Observability - Monitoring, tracing, and debugging
- AgentCore Policy - Deterministic control and security boundaries for agent-tool interactions
- AgentCore Evaluations - Automated assessment and performance measurement for agents
This project demonstrates AgentCore Memory with two types of memory:
Captures turn-by-turn interactions within a single session. Agents maintain immediate context without requiring users to repeat information.
Automatically extracts and stores key insights from conversations across multiple sessions, including user preferences, important facts, and session summaries.
- AWS Account with appropriate permissions
- Python 3.10+ installed
- AWS CLI configured
- Basic understanding of AI agents and AWS services
cd 02-agentcore-memorypip install -r deployment/requirements.txtNavigate to the deployment directory and configure the agent:
cd deploymentConfigure the agent with memory enabled:
agentcore configure -e my_agent_memory.py
# Select 'yes' for memory
# Select 'yes' for long-term memory extractionSelect YES in Request Header Allow list, and in Request Header Allow paste X-Amzn-Bedrock-AgentCore-Runtime-Custom-Actor-Id
At the end .bedrock_agentcore.yaml, must looks like this:
request_header_configuration:
requestHeaderAllowlist:
- X-Amzn-Bedrock-AgentCore-Runtime-Custom-Actor-IdThis header allows passing a user identifier from your application to the agent. The agent extracts it from context.request_headers (normalized to lowercase: x-amzn-bedrock-agentcore-runtime-custom-actor-id) and uses it to namespace memory per user.
Launch the agent to production:
agentcore launchUse the agentcore invoke CLI command to test memory capabilities. The CLI supports --session-id and --headers flags for testing different memory scenarios.
Important: Session IDs must be at least 33 characters long.
Store information in a session:
agentcore invoke '{"prompt": "My name is Laura and I love banana"}' \
--session-id session1-laura-test-12345678901234 Recall information in the same session:
agentcore invoke '{"prompt": "What is my name and what do I love?"}' \
--session-id session1-laura-test-12345678901234 Store preferences in session 1:
agentcore invoke '{"prompt": "I prefer vegetarian food and work as a teacher"}' \
--session-id session1-user456-test-1234567890123 \
--headers "X-Amzn-Bedrock-AgentCore-Runtime-Custom-Actor-Id:user456"Important: Long-term memory extraction is an asynchronous background process that can take a minute or more. Wait at least a few minutes before testing recall in a different session:
agentcore invoke '{"prompt": "What do you know about my food preferences and job?"}' \
--session-id session2-user456-test-9876543210987 \
--headers "X-Amzn-Bedrock-AgentCore-Runtime-Custom-Actor-Id:user456"Key Points:
- Session IDs must be at least 33 characters long
- Short-term memory works within a single session without needing the actor ID header
- Long-term memory requires the custom header to identify users across different sessions
- Long-term memory extraction is an asynchronous process that can take a minute or more
- Same custom header value enables cross-session memory for that user
The tests use the AWS SDK to call
bedrock-agentcore:InvokeAgentRuntime, requiring your agent ARN and appropriate permissions.
The agent uses AgentCore Memory SDK for integration with Strands Agents.
When you run agentcore configure and enable memory, the AgentCore CLI automatically creates the memory resource (if needed) and sets the BEDROCK_AGENTCORE_MEMORY_ID environment variable during agentcore launch. Your agent code reads this variable automatically - no manual configuration needed.
from bedrock_agentcore.memory import MemoryClient
from bedrock_agentcore.memory.integrations.strands.config import AgentCoreMemoryConfig, RetrievalConfig
# HTTP headers are normalized to lowercase
CUSTOM_HEADER_NAME = 'x-amzn-bedrock-agentcore-runtime-custom-actor-id'
# Create memory client
client = MemoryClient(region_name="us-west-2") #your region
# Create memory store
basic_memory = client.create_memory(
name="BasicTestMemory",
description="Basic memory for testing short-term functionality"
)
# Configure memory with retrieval settings
memory_config = AgentCoreMemoryConfig(
memory_id=basic_memory.get('id'),
session_id=session_id,
actor_id=actor_id,
retrieval_config={
f"/users/{actor_id}/facts": RetrievalConfig(top_k=3, relevance_score=0.5),
f"/users/{actor_id}/preferences": RetrievalConfig(top_k=3, relevance_score=0.5)
}
)from bedrock_agentcore.memory.integrations.strands.session_manager import AgentCoreMemorySessionManager
# Create agent with memory
agent = Agent(
session_manager=AgentCoreMemorySessionManager(memory_config, REGION),
system_prompt="You are a helpful assistant with memory. Remember user preferences and facts across conversations."
)The invoke function is the main entry point for your AgentCore agent. It:
- Receives user prompts and context from AgentCore Runtime
- Extracts the custom header for user identification (normalized to lowercase)
- Creates or retrieves the agent instance with memory configuration
- Processes the user message and returns the response
@app.entrypoint
def invoke(payload, context: RequestContext):
"""AgentCore Runtime entry point with lazy-loaded agent"""
if not MEMORY_ID:
return {"error": "Memory not configured. Set BEDROCK_AGENTCORE_MEMORY_ID environment variable."}
# Extract custom header and session information
actor_id = 'default-user'
if context and hasattr(context, 'request_headers') and context.request_headers:
# Headers are normalized to lowercase
actor_id = context.request_headers.get(CUSTOM_HEADER_NAME)
session_id = context.session_id
# Get or create agent (lazy loading)
agent = get_or_create_agent(actor_id, session_id)
prompt = payload.get("prompt", "Hello!")
result = agent(prompt)
return {
"response": result.message.get('content', [{}])[0].get('text', str(result))
}For more comprehensive testing, you can use the provided test applications that demonstrate both short-term and long-term memory capabilities.
Use the test_short_memory.py application to test memory within the same session:
# Set your agent ARN (get from agentcore status)
export AGENT_ARN="YOUR-ARN"
# Run the short-term memory test
python test_short_memory.pyThis script will test:
- Information storage within a session
- Memory recall in the same session
- Session-based context retention
Use the test_long_memory.py application to test memory persistence across different sessions:
# Set your agent ARN (get from agentcore status)
export AGENT_ARN="YOUR-ARN"
# Run the long-term memory test
python test_long_memory.pyThis script will test:
- Information storage in one session
- Memory extraction and persistence
- Cross-session memory recall
- User-specific memory isolation
Note: Long-term memory extraction is an asynchronous background process that can take a minute or more. The test waits 10 seconds between invocations, but for reliable long-term memory retrieval, you may need to wait longer or run the second session separately after a few minutes.
Key Points for Memory Testing:
- Agent ARN: Get this from
agentcore statusoutput - Session IDs: Must be 33+ characters for proper session management
- Custom Headers: Use boto3 event handlers with
X-Amzn-Bedrock-AgentCore-Runtime-Custom-Actor-Idfor user-specific memory - Long-term Memory Extraction: An asynchronous background process that can take a minute or more. For testing, wait a few minutes between storing and retrieving long-term memories
agentcore destroy