Skip to main content

Persistent memory for LLMs - Give your AI conversations long-term memory with intelligent context retrieval

Project description

Memory Mori

Persistent memory for LLMs - Give your AI conversations long-term memory with intelligent context retrieval.

Memory Mori is a Python library that provides persistent, searchable memory for Large Language Models (LLMs). It remembers past conversations, user preferences, and important context, then intelligently retrieves relevant information when needed.

Perfect for building chatbots, AI assistants, and conversational agents that need to remember user interactions across sessions.

Key capabilities:

  • ๐Ÿง  Persistent Memory: Store and retrieve conversation history across sessions
  • ๐Ÿ” Smart Retrieval: Hybrid search combines semantic understanding with keyword matching
  • ๐Ÿ‘ค User Profiles: Automatically learns and remembers user preferences, skills, and context
  • โฐ Time Awareness: Recent memories are prioritized, old ones fade naturally
  • ๐Ÿท๏ธ Entity Tracking: Remembers people, organizations, tools, and technologies mentioned
  • ๐Ÿš€ Easy Integration: Works with OpenAI, Claude, Ollama, and any LLM

Features

๐Ÿ” Hybrid Search (Layer 1)

  • Semantic Search: all-mpnet-base-v2 embeddings for meaning-based retrieval
  • Keyword Search: BM25 algorithm for exact term matching
  • Optimized Weighting: 80% semantic, 20% keyword (tuned for precision)
  • ChromaDB Backend: Efficient vector storage and retrieval

๐Ÿท๏ธ Entity Extraction (Layer 2)

  • Named Entity Recognition: Using spaCy en_core_web_lg with custom tech patterns
  • 50+ Tech Patterns: Python, React, Docker, Kubernetes, GPT-4, etc.
  • 5 Core Types: PERSON, ORG, DATE, PRODUCT, EVENT
  • Entity Filtering: Search within specific entity types

๐Ÿ‘ค Profile Learning (Layer 3)

  • SQLite Backend: Persistent user profile storage
  • 5 Categories: role, preference, project, skill, context
  • Confidence-Based: Higher confidence facts override lower ones
  • Auto-Extraction: Profile facts learned from conversations

โฐ Time-Based Decay (Layer 4)

  • Exponential Decay: score = base ร— e^(-ฮป ร— time)
  • Smart Aging: Recent memories prioritized over old ones
  • Access Tracking: Documents track created_at, last_accessed
  • Auto Cleanup: Remove stale documents below threshold

โœจ Recent Improvements

  • GPU Acceleration: Automatic GPU detection and support (2-3x faster with CUDA)
  • Score Thresholding: Filter low-confidence results (min_score=0.3)
  • Focused Results: Default max_items=3 for higher precision
  • Custom Tech Patterns: Better detection of programming languages, frameworks, tools

Installation

# Install Memory Mori from PyPI
pip install memory-mori

# Download spaCy language model (required)
python -m spacy download en_core_web_lg

That's it! Memory Mori will automatically install all dependencies (ChromaDB, sentence-transformers, spaCy, etc.).

Quick Start

from memory_mori import MemoryMori, MemoryConfig

# Initialize with defaults (recommended)
mm = MemoryMori()

# Store information
mm.store("I'm working on a Python project using Django and PostgreSQL")
mm.store("Our deployment uses Docker containers on AWS")

# Retrieve relevant memories
results = mm.retrieve("Tell me about my tech stack")

for result in results:
    print(f"[{result.score:.2f}] {result.text}")

# Get formatted context for AI prompts
context = mm.get_context("What's my deployment setup?")
print(context)

Configuration

from memory_mori import MemoryConfig

# Custom configuration
config = MemoryConfig(
    alpha=0.8,                    # 80% semantic, 20% keyword
    lambda_decay=0.05,            # Slow decay rate
    entity_model="en_core_web_md", # Entity extraction model
    enable_entities=True,         # Enable entity extraction
    enable_profile=True,          # Enable profile learning
    device="auto"                 # Device: "auto", "cpu", or "cuda"
)

mm = MemoryMori(config)

# Or use presets
config = MemoryConfig.from_preset('standard')     # Balanced
config = MemoryConfig.from_preset('high_accuracy') # Uses larger model
config = MemoryConfig.from_preset('minimal')      # Lightweight

GPU Acceleration

Memory Mori automatically detects and uses GPU when available for 2-3x performance improvement:

# Auto-detect GPU (default)
config = MemoryConfig(device="auto")

# Force CPU usage
config = MemoryConfig(device="cpu")

# Force GPU usage (with CPU fallback)
config = MemoryConfig(device="cuda")

Requirements for GPU:

  • NVIDIA GPU with CUDA support
  • PyTorch with CUDA: pip install torch --index-url https://download.pytorch.org/whl/cu118

API Reference

MemoryMori

store(text, metadata=None) -> str

Store a memory.

doc_id = mm.store(
    "Python is great for data science",
    metadata={"source": "conversation"}
)

retrieve(query, filters=None, max_items=3, min_score=0.3) -> List[Memory]

Retrieve relevant memories.

# Basic retrieval
results = mm.retrieve("Python programming")

# With filters and thresholds
results = mm.retrieve(
    "web development",
    max_items=5,
    min_score=0.5,
    filters={"entity_type": "PRODUCT"}
)

get_context(query, max_items=3, include_profile=True) -> str

Get formatted context for LLM prompts.

context = mm.get_context("What technologies do I use?")
# Returns formatted string with relevant memories and profile

update_profile(facts: Dict)

Manually update profile facts.

mm.update_profile({
    "job_title": ("Software Engineer", "role", 0.9),
    "likes_coffee": ("true", "preference", 0.8)
})

get_profile(category=None) -> Dict

Get profile facts.

profile = mm.get_profile()
# Or filter by category
preferences = mm.get_profile(category="preference")

cleanup(threshold=0.01) -> int

Clean up stale memories.

removed_count = mm.cleanup(threshold=0.01)

Examples

See the examples/ folder for minimal integration examples:

All examples are interactive and simple to run.

Project Structure

memory_mori/
โ”œโ”€โ”€ api.py                      # Main MemoryMori class
โ”œโ”€โ”€ config.py                   # Configuration and data classes
โ”œโ”€โ”€ core/
โ”‚   โ”œโ”€โ”€ search.py              # Hybrid search
โ”‚   โ”œโ”€โ”€ entities.py            # Entity extraction with tech patterns
โ”‚   โ”œโ”€โ”€ profile.py             # Profile management
โ”‚   โ”œโ”€โ”€ decay.py               # Time-based decay
โ”‚   โ””โ”€โ”€ device.py              # GPU/CPU device management
โ”œโ”€โ”€ stores/
โ”‚   โ”œโ”€โ”€ vector_store.py        # ChromaDB wrapper
โ”‚   โ””โ”€โ”€ profile_store.py       # SQLite profile storage
โ”œโ”€โ”€ examples/
โ”‚   โ”œโ”€โ”€ example_openai.py      # Minimal OpenAI integration
โ”‚   โ”œโ”€โ”€ example_claude.py      # Minimal Claude integration
โ”‚   โ””โ”€โ”€ example_ollama.py      # Minimal Ollama integration
โ”œโ”€โ”€ tests/                      # Testing and benchmarking tools
โ””โ”€โ”€ utils/                      # Utility functions

Performance

Based on benchmarks:

  • Storage: ~19 docs/sec
  • Retrieval: ~25ms per query (40 queries/sec)
  • Context Generation: ~22ms per query

Advanced Features

Entity-Based Filtering

# Only retrieve memories about products/tools
results = mm.retrieve(
    "programming tools",
    filters={"entity_type": "PRODUCT"}
)

Score Thresholding

# Only high-confidence results
results = mm.retrieve(query, min_score=0.6)

# All results (no threshold)
results = mm.retrieve(query, min_score=0.0)

Profile-Enhanced Context

# Get context with user profile
context = mm.get_context(query, include_profile=True)

# Without profile
context = mm.get_context(query, include_profile=False)

Custom Decay Rates

config = MemoryConfig(
    lambda_decay=0.01,      # Very slow decay
    decay_mode="combined"   # Use both creation and access time
)

Requirements

  • Python 3.8+
  • chromadb
  • sentence-transformers
  • spacy (with en_core_web_md)
  • rank_bm25

Contributing

This is a personal project, but suggestions and feedback are welcome!

License

MIT License

Author

David Halvarson


Note: For production use, consider:

  • Using environment variables for API keys
  • Implementing proper error handling
  • Adding logging
  • Setting up proper data persistence paths
  • Monitoring memory usage and performance

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

memory_mori-0.1.2.tar.gz (42.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

memory_mori-0.1.2-py3-none-any.whl (29.7 kB view details)

Uploaded Python 3

File details

Details for the file memory_mori-0.1.2.tar.gz.

File metadata

  • Download URL: memory_mori-0.1.2.tar.gz
  • Upload date:
  • Size: 42.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for memory_mori-0.1.2.tar.gz
Algorithm Hash digest
SHA256 71f9e05b8e396af6a8ce86581447c79d4aab021c239f2cbd00f2ed05717b0d9f
MD5 2dd44156fb8e5232891a3a16ba5f74ca
BLAKE2b-256 0b1f56fbe1eb712b36b6e5fa2fa03891c00fa8f263bd1ba7ee68ce8a676c5723

See more details on using hashes here.

File details

Details for the file memory_mori-0.1.2-py3-none-any.whl.

File metadata

  • Download URL: memory_mori-0.1.2-py3-none-any.whl
  • Upload date:
  • Size: 29.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for memory_mori-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 67451c9a3be224383ed26fe44e26e8fc62f9d8a47a42106133e671e435aa059d
MD5 038574229dc8526ad60c9937736bb9f9
BLAKE2b-256 5a0850db931b5aab6383f6bac7efa682bbc6d2bf4f7b72a897ecefa6f3f711db

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page