forked from strands-agents/samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpersonal_agent_with_memory.py
More file actions
131 lines (103 loc) · 4.34 KB
/
Copy pathpersonal_agent_with_memory.py
File metadata and controls
131 lines (103 loc) · 4.34 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
#!/usr/bin/env python3
"""
# 🧠 Personal Agent
A specialized Strands agent that personalizes the answers based on websearch and memory.
## What This Example Shows
This example demonstrates:
- Creating a specialized Strands agent with memory capabilities
- Storing information across conversations and sessions
- Retrieving relevant memories based on context
- Using memory to create more personalized and contextual AI interactions
## Key Memory Operations
- **store**: Save important information for later retrieval
- **retrieve**: Access relevant memories based on queries
- **list**: View all stored memories
## Usage Examples
Storing memories: `Remember that I prefer tea over coffee`
Retrieving memories: `What do I prefer to drink?`
Listing all memories: `Show me everything you remember about me`
"""
import os
from ddgs import DDGS
from ddgs.exceptions import DDGSException, RatelimitException
from strands import Agent, tool
from strands_tools import http_request, mem0_memory
# Set up environment variables for AWS credentials and OpenSearch
# Define AWS credentials:
# os.environ["AWS_REGION"] = "<your-region>" # Replace with your region name e.g. 'us-west-2'
# os.environ['AWS_ACCESS_KEY_ID'] = "<your-aws-access-key-id>"
# os.environ['AWS_SECRET_ACCESS_KEY'] = "<your-aws-secret-access-key>"
# Make sure you have the Opensearch host setup:
# If not sure, run `sh prereqs/deploy_OSS.sh` to deploy OpenSearch Service in your CLI.
# If you manually created an Opensearch Collection, setup the environment variable here:
# os.environ["OPENSEARCH_HOST"] = "<your-opensearch-hostname>.<your-region>.aoss.amazonaws.com"
# User identifier
USER_ID = "new_user" # In the real app, this would be set based on user authentication.
# System prompt
SYSTEM_PROMPT = """You are a helpful personal assistant that provides personalized responses based on user history.
Capabilities:
- Store information with mem0_memory (action="store")
- Retrieve memories with mem0_memory (action="retrieve")
- Search the web with duckduckgo_search
Key Rules:
- Be conversational and natural
- Retrieve memories before responding
- Store new user information and preferences
- Share only relevant information
- Politely indicate when information is unavailable
"""
@tool
def websearch(keywords: str, region: str = "us-en", max_results: int = 5) -> str:
"""Search the web for updated information.
Args:
keywords (str): The search query keywords.
region (str): The search region: wt-wt, us-en, uk-en, ru-ru, etc..
max_results (int | None): The maximum number of results to return.
Returns:
List of dictionaries with search results.
"""
try:
results = DDGS().text(keywords, region=region, max_results=max_results)
return results if results else "No results found."
except RatelimitException:
return "Rate limit reached. Please try again later."
except DDGSException as e:
return f"Search error: {e}"
# Initialize agent
memory_agent = Agent(
system_prompt=SYSTEM_PROMPT,
tools=[mem0_memory, websearch, http_request],
)
if __name__ == "__main__":
"""Run the personal agent interactive session."""
print("\n🧠 Personal Agent 🧠\n")
print("This agent uses memory and websearch capabilities in Strands Agents.")
print("You can ask me to remember things, retrieve memories, or search the web.")
# Initialize user memory
memory_agent.tool.mem0_memory(
action="store", content=f"The user's name is {USER_ID}.", user_id=USER_ID
)
# Interactive loop
while True:
try:
print(
"\nWrite your question below or 'exit' to quit, or 'memory' to list all memories:"
)
user_input = input("\n> ").strip().lower()
if user_input.lower() == "exit":
print("\nGoodbye! 👋")
break
if user_input.lower() == "memory":
all_memories = memory_agent.tool.mem0_memory(
action="list",
user_id=USER_ID,
)
continue
else:
memory_agent(user_input)
except KeyboardInterrupt:
print("\n\nExecution interrupted. Exiting...")
break
except Exception as e:
print(f"\nAn error occurred: {str(e)}")
print("Please try a different request.")