Skip to main content

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 sessions
  • session_memory: Temporary notes for current session

Memory Notes

Individual memory items with metadata:

  • text: The memory content
  • keywords: Tags for categorization
  • confidence: 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

Release files for agent-memory-state 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for agent-memory-state 0.1.0
File Size Uploaded
agent_memory_state-0.1.0.tar.gz 19.2 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for agent-memory-state 0.1.0
File Interpreter ABI Platform
agent_memory_state-0.1.0-py3-none-any.whl Python 3 none any Details

Total release size: 41.7 kB

Release files / agent_memory_state-0.1.0.tar.gz

Download URL agent_memory_state-0.1.0.tar.gz
Size 19.2 kB
Tags Source
SHA-256 checksum
How to use checksums
8e7d4691f953fc824cc5b821c128d77954165978d02b9b21ba4fdc7ec61ac6ba
BLAKE2b-256 checksum
How to use checksums
6f0ececc201687b0f8e4d72444435cd00dd15ace84e777131c95c0754d85c24b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.6

Release files / agent_memory_state-0.1.0-py3-none-any.whl

Download URL agent_memory_state-0.1.0-py3-none-any.whl
Size 22.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3e0e7bcd4a8658d81120bc3a6a7a0442ec0c8ce6a0a89b3631502e2b816ef314
BLAKE2b-256 checksum
How to use checksums
ed985b862a035e66b74618c0479f48a4f7499102e51c58ea9434880ee867acb3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.6

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page