Useful ToolsMemory
DocsMemory

Memory System

Give your agents persistent memory using markdown-based storage.

Quick Start

quickstart.py
from connectonion import Agent, Memory memory = Memory() agent = Agent( name="assistant", system_prompt="You are a helpful assistant with memory.", tools=[memory] ) # Agent can now remember things agent.input("Remember that Alice prefers email communication") agent.input("What do I know about Alice?")

What is Memory?

Memory is a simple, file-based storage system that lets your agents:

Persistent Storage

Save information across sessions

Key-Value Retrieval

Retrieve information by specific keys

Regex Search

Search across all memories with patterns

Markdown Format

Organize knowledge in human-readable format

Storage Strategy

Memories start in a single memory.md file. When the file exceeds 3000 lines, it automatically splits into a directory structure with separate .md files per memory key.

Installation

Memory is included in ConnectOnion:

Terminalbash
$pip install connectonion

Basic Usage

Creating a Memory Instance

init_memory.py
from connectonion import Memory # Default (creates memory.md) memory = Memory() # Custom file path memory = Memory(memory_file="agent_knowledge.md") # Legacy: directory structure (creates directory immediately) memory = Memory(memory_dir="agent_knowledge")

Adding Memory to an Agent

agent_with_memory.py
from connectonion import Agent, Memory memory = Memory() agent = Agent("assistant", tools=[memory])

Now your agent has access to 4 memory methods:

  • write_memory(key, content)- Save or update information
  • read_memory(key)- Retrieve information
  • list_memories()- Show all stored memories
  • search_memory(pattern)- Search with regex

Memory Methods

write_memory

Save information to memory:

write.py
memory.write_memory("alice-notes", "Alice prefers email\nAlice works at TechCorp") # Returns: "Memory saved: alice-notes"
Keys are sanitized: Only alphanumeric, hyphens, and underscores allowed. Converted to lowercase.

read_memory

Retrieve saved information:

read.py
memory.read_memory("alice-notes") # Returns: # Memory: alice-notes # # Alice prefers email # Alice works at TechCorp

list_memories

Show all stored memories:

list.py
memory.list_memories() # Returns: # Stored Memories (3): # 1. alice-notes (85 bytes) # 2. bob-notes (62 bytes) # 3. project-x (120 bytes)

search_memory

Search across all memories using regex:

search.py
# Simple text search (case-sensitive by default) memory.search_memory("email") # Case-insensitive search with (?i) flag memory.search_memory("(?i)email") # Regex patterns memory.search_memory(r"\w+@\w+\.\w+") # Find email addresses memory.search_memory(r"Project [A-Z]") # Find project names

Examples

Example 1: Customer Notes

customer_notes.py
from connectonion import Agent, Memory memory = Memory(memory_dir="customer_notes") agent = Agent( name="sales-assistant", system_prompt="You help track customer information.", tools=[memory] ) # Save customer info agent.input("Remember that Alice from TechCorp is interested in our API product and prefers email contact") # Later, recall the information agent.input("What do I know about Alice?") # Agent will use read_memory() to retrieve Alice's info

Example 2: Project Tracker

project_tracker.py
from connectonion import Agent, Memory memory = Memory(memory_dir="projects") agent = Agent( name="project-manager", system_prompt="You track project status and notes.", tools=[memory] ) # Save project updates agent.input("Remember: Project Alpha is 80% complete, needs final testing") agent.input("Remember: Project Beta is blocked, waiting on API keys") # Search for blocked projects agent.input("Which projects are blocked?") # Agent will use search_memory("blocked") to find relevant projects

Example 3: Research Assistant

research_assistant.py
from connectonion import Agent, Memory def web_search(query: str) -> str: """Search the web for information.""" # Your search implementation return f"Results for {query}" memory = Memory(memory_dir="research") agent = Agent( name="researcher", system_prompt="You research topics and save key findings.", tools=[web_search, memory] ) # Research and save agent.input("Research the history of Python programming and save key points") # Agent will search, then use write_memory() to save findings # Later, recall research agent.input("What did I learn about Python's history?")

Example 4: Multi-Agent Shared Memory

Pass the same Memory instance to multiple agents so they share knowledge:

multi_agent_memory.py
from connectonion import Agent, Memory # Shared memory between agents shared_memory = Memory(memory_dir="shared_knowledge") researcher = Agent( name="researcher", system_prompt="You research and document findings.", tools=[shared_memory] ) writer = Agent( name="writer", system_prompt="You write articles based on research.", tools=[shared_memory] ) # Researcher saves findings researcher.input("Research AI trends and save the findings") # Writer uses the same memory writer.input("Write an article based on AI trends research")

Advanced Patterns

Memory with Different Tools

Memory works alongside any other tools:

multi_tool.py
from connectonion import Agent, Memory def calculate(expression: str) -> float: """Calculate math expressions.""" return eval(expression) def send_email(to: str, subject: str, body: str) -> str: """Send an email.""" # Implementation return "Email sent" memory = Memory() agent = Agent( name="multi-tool-agent", tools=[calculate, send_email, memory] )

Custom File Organization

Use separate Memory files for different purposes:

organized.py
# Separate memory files for different purposes customer_memory = Memory(memory_file="data/customers.md") project_memory = Memory(memory_file="data/projects.md") research_memory = Memory(memory_file="data/research.md") agent = Agent( name="organized-agent", tools=[customer_memory, project_memory, research_memory] )

Regex Search Patterns

Powerful pattern matching across all stored memories:

regex_patterns.py
# Find email addresses memory.search_memory(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b") # Find phone numbers memory.search_memory(r"\d{3}-\d{3}-\d{4}") # Find dates (YYYY-MM-DD) memory.search_memory(r"\d{4}-\d{2}-\d{2}") # Find URLs memory.search_memory(r"https?://[^\s]+") # Case-insensitive keyword with word boundaries memory.search_memory(r"(?i)\bproject\b")

File Format

Single File (Default)

Memories start in a single memory.md file using section headers:

## alice-notes
Alice prefers email communication
Works at TechCorp
## bob-notes
Bob from Marketing
Prefers phone calls

Auto-Split to Directory

When memory.md exceeds 3000 lines, it automatically migrates:

memory/
├── alice-notes.md
├── bob-notes.md
└── project-x.md

Best Practices

1. Use Descriptive Keys

keys.py
# Good memory.write_memory("alice-techcorp-contact-info", content) # Bad memory.write_memory("note1", content)

2. Structure Your Content

Use markdown formatting for better organization:

structure.py
content = """# Alice - TechCorp ## Contact Info - Email: alice@techcorp.com ## Projects - Interested in API product """ memory.write_memory("alice-techcorp", content)

3. Keep Memories Updated

Periodically prune or refresh stale notes:

updates.py
# Update or overwrite outdated memories agent.input("Review and update any memories older than 6 months")

4. Search Before Creating

Avoid duplicates by checking first:

search_first.py
# Check if similar memory exists agent.input("Do we have any notes about Alice?") # Agent will search before creating duplicate memory

5. Use Consistent Naming

Pick a key prefix convention and stick to it:

naming.py
memory.write_memory("customer-alice-techcorp", ...) memory.write_memory("customer-bob-acmecorp", ...) memory.write_memory("project-alpha", ...) memory.write_memory("project-beta", ...)

Limitations

Storage

All memories are loaded during search. For very large stores (>1000 files or >100MB), consider a database backend.

Concurrency

File-based storage isn't optimized for high concurrency. Multiple agents writing to the same memory may race.

Search Performance

Regex search scans linearly. For large-scale search, consider Elasticsearch or similar.

Troubleshooting

“Memory not found”

Keys are sanitized — list all stored memories to see actual keys:

check_keys.py
print(memory.list_memories())

“Invalid key name”

Use only alphanumeric characters, hyphens, and underscores:

key_format.py
# Good memory.write_memory("alice-notes", content) # Bad — will be rejected or sanitized memory.write_memory("alice@notes!", content)

Memory file not created

The file is created on first write, not on construction:

creation.py
import os memory = Memory() memory.write_memory("test", "content") print(os.path.exists("memory.md")) # True

Customizing

Need to modify Memory's behavior? Copy the source into your project and import from there:

Terminalbash
$co copy memory
custom_import.py
# from connectonion import Memory # Before from tools.memory import Memory # After — customize freely

Related Documentation

Star us on GitHub

If ConnectOnion saves you time, a ⭐ goes a long way — and earns you a coffee chat with our founder.