-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path06_memory_enabled_agent.py
More file actions
271 lines (225 loc) · 9.1 KB
/
Copy path06_memory_enabled_agent.py
File metadata and controls
271 lines (225 loc) · 9.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
"""
Standalone Strands Agent: returns_agent_with_memory
Generated by AgentCore MCP Server
Integrations:
- Memory: Enabled
- Gateway: Disabled
- Knowledge Base: Enabled
"""
import os
import json
from strands import Agent, tool
from strands.models import BedrockModel
from strands_tools import retrieve
from strands_tools import current_time
from bedrock_agentcore.memory.integrations.strands.config import AgentCoreMemoryConfig, RetrievalConfig
from bedrock_agentcore.memory.integrations.strands.session_manager import AgentCoreMemorySessionManager
from datetime import datetime
# Constants
MODEL_ID = "us.anthropic.claude-sonnet-4-5-20250929-v1:0"
REGION = "us-west-2"
SESSION_ID = "default-session"
ACTOR_ID = "default-actor"
# Model configuration
bedrock_model = BedrockModel(model_id=MODEL_ID, temperature=0.3)
# ============================================================================
# LOAD CONFIGURATION FROM FILES
# ============================================================================
# Load memory configuration
try:
with open('memory_config.json') as f:
memory_config = json.load(f)
MEMORY_ID = memory_config['memory_id']
print(f"✓ Memory ID loaded: {MEMORY_ID}")
except FileNotFoundError:
print("⚠️ memory_config.json not found - set MEMORY_ID environment variable")
MEMORY_ID = os.environ.get("MEMORY_ID")
# Load knowledge base configuration
try:
with open('kb_config.json') as f:
kb_config = json.load(f)
KB_ID = kb_config['knowledge_base_id']
print(f"✓ Knowledge Base ID loaded: {KB_ID}")
except FileNotFoundError:
print("⚠️ kb_config.json not found - set KNOWLEDGE_BASE_ID environment variable")
KB_ID = os.environ.get("KNOWLEDGE_BASE_ID", "YOUR_KB_ID_HERE")
# ============================================================================
# MEMORY CONFIGURATION
# ============================================================================
def create_memory_session_manager(memory_id: str, session_id: str = SESSION_ID, actor_id: str = ACTOR_ID):
"""Create AgentCore Memory session manager with all three namespaces"""
agentcore_memory_config = AgentCoreMemoryConfig(
memory_id=memory_id,
session_id=session_id,
actor_id=actor_id,
retrieval_config={
f"app/{actor_id}/semantic": RetrievalConfig(top_k=3),
f"app/{actor_id}/preferences": RetrievalConfig(top_k=3),
f"app/{actor_id}/{session_id}/summary": RetrievalConfig(top_k=2),
}
)
return AgentCoreMemorySessionManager(
agentcore_memory_config=agentcore_memory_config,
region_name=REGION
)
# System prompt
system_prompt = f"""You are a personalized returns assistant who remembers customer preferences and history. Use the retrieve tool to access Amazon return policy documents for accurate information.
When using the retrieve tool, always pass these parameters:
- knowledgeBaseId: {KB_ID}
- region: {REGION}
- text: the search query
You have access to customer conversation history and preferences through memory. Use this to provide personalized service."""
# ============================================================================
# CUSTOM TOOLS
# ============================================================================
@tool
def check_return_eligibility(purchase_date: str, category: str) -> dict:
"""Check if an item is eligible for return.
Args:
purchase_date: Purchase date in YYYY-MM-DD format
category: Product category (e.g., 'electronics', 'clothing', 'books')
Returns:
dict with 'eligible' (bool), 'reason' (str), 'days_remaining' (int)
"""
try:
purchase = datetime.strptime(purchase_date, '%Y-%m-%d')
except ValueError:
return {'eligible': False, 'reason': 'Invalid date format', 'days_remaining': 0}
return_windows = {
'electronics': 30,
'clothing': 30,
'books': 30,
'jewelry': 30,
'software': 30,
'default': 30
}
window_days = return_windows.get(category.lower(), return_windows['default'])
days_since_purchase = (datetime.now() - purchase).days
days_remaining = window_days - days_since_purchase
if days_remaining > 0:
return {
'eligible': True,
'reason': f'Within {window_days}-day return window',
'days_remaining': days_remaining
}
else:
return {
'eligible': False,
'reason': f'Return window ({window_days} days) has expired',
'days_remaining': 0
}
@tool
def calculate_refund_amount(original_price: float, condition: str, return_reason: str) -> dict:
"""Calculate refund amount based on price, condition, and reason.
Args:
original_price: Original purchase price
condition: Item condition ('new', 'opened', 'used', 'damaged')
return_reason: Reason for return ('defective', 'wrong_item', 'changed_mind', 'other')
Returns:
dict with 'refund_amount' (float), 'refund_percentage' (int), 'explanation' (str)
"""
condition_rates = {
'new': 100,
'opened': 100,
'used': 80,
'damaged': 50
}
reason_adjustments = {
'defective': 0,
'wrong_item': 0,
'changed_mind': -15,
'other': -10
}
base_rate = condition_rates.get(condition.lower(), 80)
adjustment = reason_adjustments.get(return_reason.lower(), -10)
if return_reason.lower() in ['defective', 'wrong_item']:
final_rate = 100
explanation = f'Full refund - {return_reason.replace("_", " ")}'
else:
final_rate = max(0, min(100, base_rate + adjustment))
explanation = f'{final_rate}% refund based on {condition} condition'
if adjustment < 0:
explanation += f' with {abs(adjustment)}% restocking fee'
refund_amount = round(original_price * (final_rate / 100), 2)
return {
'refund_amount': refund_amount,
'refund_percentage': final_rate,
'explanation': explanation
}
@tool
def format_policy_response(policy_text: str, customer_question: str = '') -> str:
"""Format policy information in a customer-friendly way.
Args:
policy_text: Raw policy text from knowledge base
customer_question: Optional customer question for context
Returns:
Formatted, customer-friendly policy explanation
"""
formatted = '📋 Return Policy Information\n'
formatted += '=' * 50 + '\n\n'
if customer_question:
formatted += f'Regarding your question: "{customer_question}"\n\n'
lines = policy_text.strip().split('\n')
formatted += 'Here\'s what you need to know:\n\n'
for line in lines:
line = line.strip()
if line:
if any(keyword in line.lower() for keyword in ['must', 'should', 'within', 'eligible', 'required']):
formatted += f' • {line}\n'
else:
formatted += f'{line}\n'
formatted += '\n' + '-' * 50 + '\n'
formatted += '💡 Tip: If you have questions, I\'m here to help clarify!\n'
return formatted
def run_agent(user_input: str, session_id: str = SESSION_ID, actor_id: str = ACTOR_ID):
"""Run the agent with user input"""
# Build tools list - includes all custom tools plus retrieve and current_time
custom_tools = [
retrieve,
current_time,
check_return_eligibility,
calculate_refund_amount,
format_policy_response
]
# Configure memory
if not MEMORY_ID:
print("⚠️ MEMORY_ID not configured - agent will run without memory")
session_manager = None
else:
session_manager = create_memory_session_manager(MEMORY_ID, session_id, actor_id)
print(f"✓ Memory configured with all three namespaces:")
print(f" - Semantic: app/{actor_id}/semantic")
print(f" - Preferences: app/{actor_id}/preferences")
print(f" - Summary: app/{actor_id}/{session_id}/summary")
# Create agent
agent = Agent(
model=bedrock_model,
tools=custom_tools,
system_prompt=system_prompt,
session_manager=session_manager
)
response = agent(user_input)
return response.message["content"][0]["text"]
if __name__ == "__main__":
print("\n" + "="*80)
print("MEMORY-ENABLED RETURNS AGENT")
print("="*80)
print(f"Agent: returns_agent_with_memory")
print(f"Model: {MODEL_ID}")
print(f"Region: {REGION}")
print(f"Temperature: 0.3")
print("="*80)
print("\nIntegrations:")
print(f" ✓ Memory: Enabled (ID: {MEMORY_ID})")
print(f" ✓ Knowledge Base: Enabled (ID: {KB_ID})")
print(f" ✓ Custom Tools: 3 (check_return_eligibility, calculate_refund_amount, format_policy_response)")
print(f" ✓ Built-in Tools: 2 (retrieve, current_time)")
print("="*80)
# Example usage
user_query = "Hello, I need help with a return"
print(f"\nUser Query: {user_query}\n")
result = run_agent(user_query, actor_id="user_001")
print("\n" + "="*80)
print("AGENT RESPONSE:")
print("="*80)
print(result)