Skip to content

Commit 4e50d5a

Browse files
author
Mike Wrighton
committed
Update documentation
1 parent 30b711f commit 4e50d5a

File tree

2 files changed

+18
-146
lines changed

2 files changed

+18
-146
lines changed

documentation/docs/examples/semantic_search.md

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,33 +3,31 @@
33
This example demonstrates the complete workflow for creating a memory resource with semantic strategy, writing events, and retrieving memory records.
44

55
```python
6+
# Semantic Search Memory Example
7+
8+
from bedrock_agentcore_starter_toolkit.operations.memory.manager import MemoryManager
9+
from bedrock_agentcore.memory.session import MemorySessionManager
10+
from bedrock_agentcore.memory.constants import StrategyType, ConversationalMessage, MessageRole
11+
from bedrock_agentcore_starter_toolkit.operations.memory.models.strategies import SemanticStrategy
612
import time
7-
from bedrock_agentcore.memory import MemoryManager
8-
from bedrock_agentcore.models.strategies.semantic import SemanticStrategy
9-
from bedrock_agentcore.session import MemorySessionManager
10-
from bedrock_agentcore.constants import ConversationalMessage, MessageRole
1113

1214
memory_manager = MemoryManager(region_name="us-west-2")
1315

1416
print("Creating memory resource...")
1517

1618
memory = memory_manager.get_or_create_memory(
17-
name="CustomerSupportSemantic5",
19+
name="CustomerSupportSemantic",
1820
description="Customer support memory store",
1921
strategies=[
2022
SemanticStrategy(
2123
name="semanticLongTermMemory",
24+
namespaces=['/strategies/{memoryStrategyId}/actors/{actorId}'],
2225
)
2326
]
2427
)
2528

2629
print(f"Memory ID: {memory.get('id')}")
2730

28-
# View all memories
29-
memories = memory_manager.list_memories()
30-
for memory in memories:
31-
print(f"Memory: {memory}")
32-
3331
# Create a session to store memory events
3432
session_manager = MemorySessionManager(
3533
memory_id=memory.get("id"),
@@ -73,8 +71,8 @@ for event in events:
7371
print(f"Event: {event}")
7472
print("--------------------------------------------------------------------")
7573

76-
print("Waiting 30 seconds for semantic processing...")
77-
time.sleep(30)
74+
print("Waiting 2 minutes for semantic processing...")
75+
time.sleep(120)
7876

7977
# List all memory records
8078
memory_records = session_manager.list_memory_records(
@@ -97,4 +95,5 @@ memory_records = session_manager.retrieve_memory_records(
9795
for record in memory_records.get("memoryRecordSummaries", []):
9896
print(f"retrieved memory: {record}")
9997
print("--------------------------------------------------------------------")
98+
10099
```

documentation/docs/user-guide/memory/quickstart.md

Lines changed: 7 additions & 134 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ The steps are as follows
77
1. Create a memory resource containing a semantic strategy
88
2. Write events (conversation history) to the memory resource.
99
3. Retrieve memory records from long term memory
10-
4. Integrate with an agent
1110

1211
## Prerequisites
1312

@@ -25,6 +24,7 @@ cd agentcore-memory-quickstart
2524
python -m venv .venv
2625
source .venv/bin/activate
2726
pip install bedrock-agentcore
27+
pip install bedrock-agentcore-starter-toolkit
2828
```
2929

3030

@@ -38,10 +38,11 @@ A memory resource is needed to start storing information for your agent. By defa
3838
We are going to create a memory resource with a semantic strategy so that both short term and long term memory can be utilized. This will take 1-2 minutes. Memory resources can also be created in the AWS console.
3939

4040
```python
41-
from bedrock_agentcore.memory import MemoryManager
42-
from bedrock_agentcore.session import MemorySessionManager
43-
from bedrock_agentcore.constants import StrategyType
44-
from bedrock_agentcore.models.strategies.semantic import SemanticStrategy
41+
from bedrock_agentcore_starter_toolkit.operations.memory.manager import MemoryManager
42+
from bedrock_agentcore.memory.session import MemorySessionManager
43+
from bedrock_agentcore.memory.constants import StrategyType
44+
from bedrock_agentcore_starter_toolkit.operations.memory.models.strategies import (
45+
SemanticStrategy)
4546

4647
memory_manager = MemoryManager(region_name="us-west-2")
4748

@@ -58,6 +59,7 @@ memory = memory_manager.get_or_create_memory(
5859
)
5960

6061
print(f"Memory ID: {memory.get('id')}")
62+
6163
```
6264

6365

@@ -157,135 +159,6 @@ Important information about the user is likely stored is long term memory. Agent
157159

158160
The full example source file showing steps 1 - 3 is available [here](../../examples/semantic_search.md).
159161

160-
## Step Four: Putting it all together
161-
162-
Now that the concepts are clear, let’s incorporate this in an agent. The following example shows a conversational AI agent built using the Strands SDK that automatically extracts and remembers user preferences from conversations.
163-
164-
Install dependencies for the strands SDK.
165-
166-
```bash
167-
pip install strands
168-
pip install flask
169-
```
170-
171-
Create a new file called `preference_saver.py` and add the following code.
172-
173-
```python
174-
from bedrock_agentcore.memory import MemoryManager
175-
from bedrock_agentcore.session import MemorySessionManager
176-
from bedrock_agentcore.constants import StrategyType, ConversationalMessage, MessageRole
177-
from strands import Agent
178-
from flask import Flask, request, jsonify
179-
import uuid
180-
181-
# Initialize memory storage for the agent
182-
# This creates a persistent memory that can store user preferences and conversation history
183-
memory_manager = MemoryManager(region_name="us-west-2")
184-
memory = memory_manager.create_memory_and_wait(
185-
name=f"PreferenceSaverMemory",
186-
strategies=[
187-
{
188-
# User preference strategy stores personalized information about each user
189-
StrategyType.USER_PREFERENCE.value: {
190-
"name": "UserPreference",
191-
"namespaces": ["/users/{actorId}"], # Separate memory space per user
192-
}
193-
}
194-
],
195-
)
196-
memory_id = memory["id"]
197-
print(f"✅ Memory created: {memory_id}")
198-
199-
# Session manager handles conversation turns and memory retrieval
200-
session_manager = MemorySessionManager(memory_id=memory_id, region_name="us-west-2")
201-
202-
# Initialize the conversational AI agent
203-
agent = Agent()
204-
205-
# Create Flask web server to handle HTTP requests
206-
app = Flask(__name__)
207-
208-
@app.route('/invoke', methods=['POST'])
209-
def invoke():
210-
"""
211-
Main endpoint for processing user messages.
212-
Retrieves relevant memories, generates a response, and saves the conversation.
213-
"""
214-
payload = request.get_json()
215-
message = payload.get("message", "Hello!")
216-
user_id = payload.get("user_id", "user1")
217-
session_id = f"session_{user_id}"
218-
219-
# Retrieve relevant memories for context
220-
# This searches the user's memory for information related to their current message
221-
try:
222-
memories = session_manager.retrieve_memory_records(
223-
memoryId=memory_id,
224-
namespace=f"/users/{user_id}",
225-
searchCriteria={"searchQuery": message, "topK": 3}
226-
)
227-
# Extract content from memory records to provide context
228-
context = "\n".join([m.get("content", "") for m in memories.get("memoryRecordSummaries", [])])
229-
if context:
230-
# Prepend relevant memories to the current message for better responses
231-
message = f"Previous: {context}\n\n{message}"
232-
except:
233-
# Continue without memory context if retrieval fails
234-
pass
235-
236-
# Generate response using the AI agent
237-
response = agent(message)
238-
239-
# Save the conversation turn to memory for future reference
240-
# This stores both the user's message and the agent's response
241-
try:
242-
session_manager.add_turns(
243-
actor_id=user_id,
244-
session_id=session_id,
245-
messages=[
246-
ConversationalMessage(payload.get('message'), MessageRole.USER),
247-
ConversationalMessage(response.message, MessageRole.ASSISTANT)
248-
]
249-
)
250-
except:
251-
# Continue even if memory saving fails
252-
pass
253-
254-
return jsonify({"response": response.message})
255-
256-
if __name__ == "__main__":
257-
print("🚀 Starting memory-enhanced conversational agent server on port 8080...")
258-
print("Send POST requests to http://localhost:8080/invoke with JSON: {'message': 'your message', 'user_id': 'user123'}")
259-
app.run(host='0.0.0.0', port=8080, debug=True)
260-
```
261-
262-
Execute the agent code with:
263-
264-
```bash
265-
python `preference_saver.py`
266-
```
267-
268-
and wait for the “Memory created” message. In another terminal, invoke the agent using the following commands:
269-
270-
#### Invocation 1:
271-
```bash
272-
curl -X POST http://localhost:8080/invoke -H "Content-Type: application/json" -d '{"message": "My name is Alice and I like pepperoni on pizza", "user_id": "alice"}'
273-
```
274-
275-
The preference is extracted asynchronously and can take up to a minute to be extracted. Please give it a minute before the next invocation.
276-
277-
#### Invocation 2:
278-
279-
```bash
280-
curl -X POST http://localhost:8080/invoke -H "Content-Type: application/json" -d '{"message": "What topping do I like on pizza?", "user_id": "alice"}'
281-
```
282-
283-
284-
The agent stores each conversation turn as a memory event, allowing the UserPreferenceMemoryStrategy to automatically extract and consolidate personal preferences over time. Before responding to new messages, it queries the
285-
memory store to retrieve relevant context, then saves the new user-bot exchange as another memory event.
286-
287-
The end result is a context-aware agent!
288-
289162
## What’s Next?
290163

291164
Consider the following as you continue your AgentCore journey

0 commit comments

Comments
 (0)