Long-term memory management for AI agents
Project description
agent-memory
Long-term memory management for AI agents. Based on OpenAI Cookbook's state-based memory pattern.
Features
- State-based memory: Profile + notes architecture
- Session vs Global memory: Temporary session notes that consolidate into persistent global memory
- LLM-powered consolidation: Intelligent deduplication and conflict resolution
- Multiple storage backends: In-memory (testing) and SQLite (production)
- Safety guardrails: PII blocking, instruction injection prevention, limits
Installation
pip install -e .
# With OpenAI support (for consolidation)
pip install -e ".[openai]"
Quick Start
from agent_memory import MemoryManager, MemoryState
from agent_memory.storage import SQLiteStorage
# Initialize
manager = MemoryManager(storage=SQLiteStorage("./memory.db"))
state = manager.load_user("user_123")
# Set profile data
state.profile["name"] = "Alice"
state.profile["loyalty_status"] = "gold"
# Inject into system prompt
system_prompt = state.to_system_prompt()
print(system_prompt)
# ---
# name: Alice
# loyalty_status: gold
# ---
#
# ## User Memory
# - [dietary] Prefers vegetarian meals (updated: 2024-01-15)
# During conversation - capture memories
state.add_session_note(
text="User prefers vegetarian meals",
keywords=["dietary"],
confidence=0.9
)
# After conversation - consolidate session → global
# (requires OpenAI client)
from openai import AsyncOpenAI
client = AsyncOpenAI()
await manager.consolidate(state, client)
# Save
manager.save(state)
Core Concepts
MemoryState
The central state object containing:
profile: Hard facts (name, loyalty status, preferences)global_memory: Persistent notes that survive across sessionssession_memory: Temporary notes for current session
Memory Notes
Individual memory items with metadata:
text: The memory contentkeywords: Tags for categorizationconfidence: How confident we are (0.0-1.0)ttl: Days until expiry (optional)
Injection
Convert state to system prompt format:
- Profile as YAML frontmatter
- Notes as Markdown list
- Session notes marked with
[SESSION]
Consolidation
LLM-powered merge of session → global memory:
- Deduplicates similar notes
- Resolves conflicts (recent wins)
- Filters session-specific notes
Guardrails
Safety checks for memory content:
- Block PII (SSN, credit cards, phone)
- Block instruction-like content
- Enforce limits (max notes, max length)
Storage Backends
InMemoryStorage
For testing and development:
from agent_memory.storage import InMemoryStorage
storage = InMemoryStorage()
SQLiteStorage
For production:
from agent_memory.storage import SQLiteStorage
storage = SQLiteStorage("./memory.db")
API Reference
MemoryManager
manager = MemoryManager(storage=storage)
# Load/create user state
state = manager.load_user("user_123")
# Save state
manager.save(state)
# Delete user
manager.delete_user("user_123")
# Consolidate with LLM
await manager.consolidate(state, llm_client)
MemoryState
state = MemoryState(user_id="user_123")
# Profile
state.profile["name"] = "Alice"
# Add notes
state.add_session_note("Prefers vegetarian", keywords=["dietary"])
state.add_global_note("VIP customer", keywords=["status"])
# Inject to prompt
prompt = state.to_system_prompt()
prompt = state.to_memory_block() # With <memory> tags
# Cleanup
state.clear_session()
state.cleanup_expired()
Guardrails
from agent_memory.guardrails import (
GuardrailConfig,
GuardedMemoryState,
validate_note_content,
sanitize_note,
)
# Validate content
result = validate_note_content("User SSN is 123-45-6789")
# result.is_valid = False
# result.violations = ["Contains SSN pattern"]
# Sanitize instead of reject
clean = sanitize_note("Call me at 555-123-4567")
# "Call me at [PHONE REDACTED]"
# Guarded state wrapper
config = GuardrailConfig(max_note_length=200)
guarded = GuardedMemoryState(state, config)
guarded.add_session_note("Safe content") # Raises on violation
Agent Tool Integration
Use as a tool in your agent:
from agent_memory import create_save_memory_tool, SAVE_MEMORY_TOOL_SCHEMA
# Create tool function bound to state
save_memory = create_save_memory_tool(state)
# Use SAVE_MEMORY_TOOL_SCHEMA for OpenAI function calling
tools = [SAVE_MEMORY_TOOL_SCHEMA]
License
MIT
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file agent_memory_state-0.1.0.tar.gz.
File metadata
- Download URL: agent_memory_state-0.1.0.tar.gz
- Upload date:
- Size: 19.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.9.6
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
8e7d4691f953fc824cc5b821c128d77954165978d02b9b21ba4fdc7ec61ac6ba
|
|
| MD5 |
b6be3d7ab5bf4aca1c3ed91d078a1552
|
|
| BLAKE2b-256 |
6f0ececc201687b0f8e4d72444435cd00dd15ace84e777131c95c0754d85c24b
|
File details
Details for the file agent_memory_state-0.1.0-py3-none-any.whl.
File metadata
- Download URL: agent_memory_state-0.1.0-py3-none-any.whl
- Upload date:
- Size: 22.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.9.6
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3e0e7bcd4a8658d81120bc3a6a7a0442ec0c8ce6a0a89b3631502e2b816ef314
|
|
| MD5 |
2f163fae566faa1f5c28b2e5f9fc155f
|
|
| BLAKE2b-256 |
ed985b862a035e66b74618c0479f48a4f7499102e51c58ea9434880ee867acb3
|