Skip to main content

Agent Memory

A memory management system for AI agents to store and retrieve user interactions and preferences.

PyPI version Python Support License: MIT

Features

  • 🧠 Persistent Memory Storage: Store conversations, user preferences, facts, and context
  • 🔍 Powerful Search: Find memories by content, tags, importance, date ranges, and more
  • 🏷️ Flexible Tagging: Organize memories with custom tags
  • ⏰ Expiration Support: Set automatic expiration for temporary memories
  • 📊 Importance Scoring: Rank memories by importance (0.0 to 1.0)
  • 📈 Access Tracking: Monitor memory usage with access counts and timestamps
  • 🗃️ Multiple Backends: SQLite (default), PostgreSQL, and other SQLAlchemy-supported databases
  • 🔧 Type Safety: Full type hints and Pydantic models
  • 🧪 Well Tested: Comprehensive test suite

Installation

pip install agent-memory

For development:

pip install agent-memory[dev]

Quick Start

from agent_memory import AgentMemory, MemoryType

# Initialize the memory system
memory = AgentMemory()

# Add a conversation memory
conversation = memory.add_conversation_memory(
    user_id="user123",
    user_message="I love Python programming",
    agent_response="That's great! Python is a versatile language.",
    importance=0.8,
    tags=["programming", "python"]
)

# Add a user preference
preference = memory.add_user_preference(
    user_id="user123",
    preference="programming_language",
    value="Python"
)

# Search for memories
memories = memory.search_memories(
    user_id="user123",
    content_search="Python",
    min_importance=0.5
)

# Get all user preferences
preferences = memory.get_user_preferences("user123")
print(preferences)  # {"programming_language": "Python"}

Core Concepts

Memory Types

Agent Memory supports different types of memories:

  • CONVERSATION: Dialog between user and agent
  • USER_PREFERENCE: User settings and preferences
  • FACT: Factual information about the user
  • CONTEXT: Contextual information for conversations
  • GOAL: User goals and objectives
  • FEEDBACK: User feedback on agent responses

Memory Properties

Each memory contains:

  • id: Unique identifier (UUID)
  • user_id: User identifier
  • agent_id: Optional agent identifier
  • content: The actual memory content
  • memory_type: Type of memory (see above)
  • importance: Importance score (0.0 to 1.0)
  • tags: List of tags for organization
  • metadata: Additional structured data
  • timestamp: When memory was created
  • expires_at: Optional expiration date

Advanced Usage

Custom Database

# Use PostgreSQL
memory = AgentMemory(
    database_url="postgresql://user:pass@localhost/memories"
)

# Use custom SQLite location
memory = AgentMemory(
    database_url="sqlite:///path/to/custom/memories.db"
)

Advanced Searching

from datetime import datetime, timedelta

# Complex search query
memories = memory.search_memories(
    user_id="user123",
    memory_type=MemoryType.CONVERSATION,
    tags=["important", "work"],
    min_importance=0.7,
    created_after=datetime.now() - timedelta(days=7),
    limit=20,
    offset=0
)

Memory Management

# Update memory
updated = memory.update_memory(
    memory_id=conversation.id,
    importance=0.9,
    tags=["programming", "python", "favorite"]
)

# Delete memory
memory.delete_memory(conversation.id)

# Cleanup expired memories
removed_count = memory.cleanup_expired()

Statistics and Analytics

# Get memory statistics
stats = memory.get_memory_stats(user_id="user123")
print(f"Total memories: {stats['total_memories']}")
print(f"By importance: {stats['by_importance']}")
print(f"By type: {stats['by_type']}")

API Reference

AgentMemory

Main class for memory management.

__init__(database_url=None, auto_cleanup=True)

Initialize the memory system.

  • database_url: Database connection string (defaults to local SQLite)
  • auto_cleanup: Whether to automatically clean expired memories

add_memory(user_id, content, memory_type=CONVERSATION, **kwargs)

Add a new memory.

Parameters:

  • user_id (str): User identifier
  • content (str): Memory content
  • memory_type (MemoryType): Type of memory
  • agent_id (str, optional): Agent identifier
  • importance (float): Importance score (0.0-1.0)
  • tags (List[str]): Tags for organization
  • metadata (dict): Additional metadata
  • expires_in_days (int): Days until expiration

search_memories(**filters)

Search for memories with flexible filtering.

Filters:

  • user_id, agent_id, memory_type
  • content_search: Search in content
  • tags: Filter by tags
  • min_importance, max_importance: Importance range
  • created_after, created_before: Date range
  • limit, offset: Pagination
  • include_expired: Include expired memories

Convenience Methods

  • add_conversation_memory(): Add user-agent conversation
  • add_user_preference(): Add user preference
  • get_user_preferences(): Get all preferences as dict
  • get_user_memories(): Get all memories for user
  • cleanup_expired(): Remove expired memories
  • get_memory_stats(): Get memory statistics

Development

Setup

git clone https://github.com/yourusername/agent-memory.git
cd agent-memory
pip install -e .[dev]

Running Tests

pytest

Code Quality

# Format code
black agent_memory tests

# Sort imports  
isort agent_memory tests

# Type checking
mypy agent_memory

# Linting
flake8 agent_memory tests

Building for PyPI

# Build package
python -m build

# Upload to PyPI (requires API token)
python -m twine upload dist/*

Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass (pytest)
  6. Format code (black . and isort .)
  7. Commit changes (git commit -m 'Add amazing feature')
  8. Push to branch (git push origin feature/amazing-feature)
  9. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Changelog

v0.1.0 (Initial Release)

  • Core memory management functionality
  • SQLite and PostgreSQL support
  • Memory types: conversation, preference, fact, context, goal, feedback
  • Search and filtering capabilities
  • Expiration and cleanup
  • Comprehensive test suite

Support

Metadata

Release files for humem 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 humem 0.1.0
File Size Uploaded Provenance Actions
humem-0.1.0.tar.gz 17.0 kB Without provenance Details for humem-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for humem 0.1.0
File Interpreter ABI Platform Actions
humem-0.1.0-py3-none-any.whl Python 3 none any Details for humem-0.1.0-py3-none-any.whl

Total release size: 30.0 kB

Release files / humem-0.1.0.tar.gz

Download URL humem-0.1.0.tar.gz
Size 17.0 kB
Tags Source
SHA-256 checksum
How to use checksums
7f0ac51c3abf5ee9c7b87015e2b152f2fb432d47674f9a3ce71094f28b0986fe
BLAKE2b-256 checksum
How to use checksums
27d6aaf7c96a280baab77c4180c7bf002d5b2cbdf6831265bfcb2cb0b5dd1aaf
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.9.22

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

Download URL humem-0.1.0-py3-none-any.whl
Size 12.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
5c2548ecc6574375d666f4130f27a9c92120a5f37e7ef09b033c5b552860199c
BLAKE2b-256 checksum
How to use checksums
9435ed592d07bb178699f3ddaf7887e16ff2ffeb2c9ed53ffec5a2f436dfe69d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.9.22

Security for humem 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

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