Skip to content

Commit 49d8029

Browse files
committed
readme and update update
1 parent e946ab5 commit 49d8029

File tree

4 files changed

+164
-67
lines changed

4 files changed

+164
-67
lines changed

examples/memory/README.md

Lines changed: 22 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -1,82 +1,41 @@
1-
# Memory Tool Examples
1+
# Memory Examples
22

3-
This directory contains examples demonstrating PicoAgents' MemoryTool for cross-conversation learning.
3+
This directory demonstrates two distinct approaches to agent memory in PicoAgents: **agent-managed memory** (agents actively control their knowledge base) and **application-managed memory** (developers control storage, framework injects context).
44

5-
## Files
5+
## Agent-Managed Memory (MemoryTool)
66

7-
- **`memory_tool_example.py`** - Complete examples showing:
8-
- Code review with cross-session learning
9-
- All memory operations (view, create, edit, delete, rename)
10-
- Memory organization patterns
7+
**File:** [`memory_tool_example.py`](memory_tool_example.py)
118

12-
## Running the Examples
9+
Agents explicitly read, write, and organize persistent knowledge through file operations. The agent decides when to check memory, what to store, and how to organize information—enabling cross-session learning where patterns discovered in one conversation can be applied in future sessions.
1310

14-
```bash
15-
# Navigate to examples directory
16-
cd /path/to/designing-multiagent-systems/examples/memory
11+
Memory tools utilize ideas from [Anthropic's context management work](https://www.anthropic.com/news/context-management), particularly their file-based memory system.
1712

18-
# Run all demos
19-
python memory_tool_example.py
20-
```
13+
**Book reference:** Chapter 4, Section 4.10 "Agent-Managed Memory"
2114

22-
## Requirements
23-
24-
Ensure you have your API key configured:
25-
26-
```bash
27-
# Set environment variable
28-
export OPENAI_API_KEY="your-key-here"
29-
30-
# Or create .env file in project root
31-
echo "OPENAI_API_KEY=your-key-here" > ../../.env
32-
```
15+
## Application-Managed Memory (ListMemory)
3316

34-
## What You'll See
17+
**File:** [`list_memory_example.py`](list_memory_example.py)
3518

36-
### Demo 1: Code Review with Cross-Session Learning
19+
Developers call `memory.add()` to store information (user preferences, facts, conversation summaries), and the framework automatically retrieves and injects relevant context into prompts via `memory.get_context()`. The agent receives this context but does not control storage or retrieval.
3720

38-
- **Session 1**: Agent reviews code with a race condition, stores the pattern in memory
39-
- **Session 2**: Agent reviews similar async code, applies the learned pattern immediately
21+
**Book reference:** Chapter 4, Section 4.9 "Adding Memory"
4022

41-
### Demo 2: Memory Operations
23+
## Running the Examples
4224

43-
Demonstrates all 6 memory operations:
44-
- `view` - Show directory or file contents
45-
- `create` - Create new files
46-
- `str_replace` - Edit file contents
47-
- `insert` - Insert text at specific line
48-
- `delete` - Remove files
49-
- `rename` - Rename or move files
25+
```bash
26+
# Navigate to examples directory
27+
cd /path/to/designing-multiagent-systems/examples/memory
5028

51-
### Demo 3: Memory Organization
29+
# Run agent-managed memory example
30+
python memory_tool_example.py
5231

53-
Shows how to organize memory into directories:
32+
# Run application-managed memory example
33+
python list_memory_example.py
5434
```
55-
/memories/
56-
├── patterns/ # Code patterns
57-
├── bugs/ # Known bugs
58-
├── projects/ # Project notes
59-
└── users/ # User preferences
60-
```
61-
62-
## Key Concepts Demonstrated
6335

64-
1. **Cross-Session Learning**: Memory persists between agent conversations
65-
2. **Agent Autonomy**: Agents actively manage their own knowledge
66-
3. **File Organization**: Structured memory with directories
67-
4. **Pattern Recognition**: Applying learned patterns to new problems
36+
Both examples require `AZURE_OPENAI_API_KEY` and `AZURE_OPENAI_ENDPOINT` environment variables.
6837

6938
## Related Documentation
7039

71-
- [Memory Tool Documentation](../../picoagents/docs/memory_tool.md)
72-
- [PicoAgents README](../../picoagents/README.md)
73-
- [Book Chapter on Memory](../../../../chapters/) (coming soon)
74-
75-
## Comparison with Anthropic
76-
77-
This implementation mirrors Anthropic's memory tool:
78-
- Same 6 operations
79-
- Same file-based approach
80-
- Same agent-driven memory management
81-
82-
See [Memory Comparison](../../../../misc/memory_comparison_summary.md) for detailed comparison.
40+
- [PicoAgents Memory Documentation](../../picoagents/docs/memory.md)
41+
- [Book Chapter 4: Building Your First Agent](../../../../chapters/ch04-building-first-agent.qmd)
Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
"""
2+
Example: Application-managed memory with ListMemory.
3+
4+
Demonstrates how applications control memory storage and retrieval,
5+
automatically injecting relevant context into agent prompts.
6+
7+
The developer calls memory.add() to store information, and the framework
8+
automatically retrieves and injects context via memory.get_context().
9+
The agent receives this context but does not control what gets stored.
10+
"""
11+
12+
import asyncio
13+
14+
from picoagents import Agent
15+
from picoagents.llm import AzureOpenAIChatCompletionClient
16+
from picoagents.memory import ListMemory, MemoryContent
17+
18+
19+
async def demo_list_memory():
20+
"""
21+
Demonstrate application-managed memory.
22+
23+
The application stores user preferences in memory, and the framework
24+
automatically injects this context into the agent's prompts.
25+
"""
26+
# Initialize model client
27+
client = AzureOpenAIChatCompletionClient(model="gpt-4.1-mini")
28+
29+
# Create memory - application manages storage
30+
memory = ListMemory(max_memories=100)
31+
32+
# Application stores user preferences
33+
await memory.add(
34+
MemoryContent(
35+
content="User prefers concise responses without verbose explanations",
36+
mime_type="text/plain",
37+
)
38+
)
39+
await memory.add(
40+
MemoryContent(
41+
content="User works as a Python developer, familiar with async/await",
42+
mime_type="text/plain",
43+
)
44+
)
45+
await memory.add(
46+
MemoryContent(
47+
content="User's timezone is PST (UTC-8)",
48+
mime_type="text/plain",
49+
)
50+
)
51+
52+
# Create agent with memory - framework handles context injection
53+
agent = Agent(
54+
name="assistant",
55+
description="Helpful programming assistant",
56+
instructions="""You are a helpful programming assistant.
57+
Use any relevant context from memory to personalize your responses.""",
58+
model_client=client,
59+
memory=memory,
60+
)
61+
62+
print("=" * 60)
63+
print("APPLICATION-MANAGED MEMORY DEMO")
64+
print("=" * 60)
65+
print()
66+
print(f"Stored {len(memory.memories)} preferences in memory")
67+
print()
68+
69+
# Agent automatically receives memory context
70+
task = "Explain how to use asyncio.gather()"
71+
72+
print(f"User: {task}")
73+
print()
74+
75+
response = await agent.run(task)
76+
77+
print(f"{agent.name}: {response.messages[-1].content}")
78+
print()
79+
80+
print("=" * 60)
81+
print("Notice how the agent's response reflects the stored preferences:")
82+
print("- Concise (no verbose explanations)")
83+
print("- Assumes Python/async knowledge")
84+
print("- The agent did NOT call any memory tools")
85+
print("- The framework automatically injected context")
86+
print("=" * 60)
87+
88+
89+
async def demo_memory_query():
90+
"""Demonstrate querying memory for relevant context."""
91+
print("\n" + "=" * 60)
92+
print("MEMORY QUERY DEMO")
93+
print("=" * 60)
94+
print()
95+
96+
client = AzureOpenAIChatCompletionClient(model="gpt-4.1-mini")
97+
memory = ListMemory(max_memories=100)
98+
99+
# Store various facts
100+
facts = [
101+
"Project deadline is March 15th",
102+
"Team meeting every Monday at 10am PST",
103+
"Code review checklist: tests, docs, type hints",
104+
"Production deployment happens on Fridays",
105+
"Database backup runs at 2am daily",
106+
]
107+
108+
for fact in facts:
109+
await memory.add(MemoryContent(content=fact))
110+
111+
print(f"Stored {len(memory.memories)} facts in memory")
112+
print()
113+
114+
# Query for relevant memories
115+
query = "when is the deadline"
116+
results = await memory.query(query, limit=2)
117+
118+
print(f"Query: '{query}'")
119+
print(f"Found {len(results.results)} relevant memories:")
120+
for i, result in enumerate(results.results, 1):
121+
print(f" {i}. {result.content}")
122+
print()
123+
124+
# The framework uses similar logic internally when preparing prompts
125+
print("(The framework uses similar querying when injecting context)")
126+
127+
128+
if __name__ == "__main__":
129+
print("📝 PicoAgents Application-Managed Memory Examples\n")
130+
131+
asyncio.run(demo_list_memory())
132+
asyncio.run(demo_memory_query())
133+
134+
print("\n✨ Examples completed!")
135+
print("\nNext: Try ChromaDB for semantic search with vector embeddings")
136+
print("Install: pip install 'picoagents[rag]'")

examples/memory/memory_tool.py

Whitespace-only changes.

examples/memory/memory_tool_example.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
"""
2-
Example: Using MemoryTool for cross-conversation learning.
2+
Example: Agent-managed memory using MemoryTool for cross-session learning.
33
4-
Demonstrates how agents can store and retrieve information across sessions,
5-
similar to Anthropic's memory tool functionality.
4+
Demonstrates how agents explicitly control their own persistent knowledge
5+
through file operations—storing patterns, organizing information, and
6+
retrieving learned insights across conversation sessions.
67
7-
Modelled around ideas from Anthropic's Memory Tool:
8+
Memory tools utilize ideas from Anthropic's context management work:
9+
https://www.anthropic.com/news/context-management
810
"""
911

1012
import asyncio

0 commit comments

Comments
 (0)