Building Custom Memory

Learn how to build custom memory implementations by extending BaseMemory for specialized storage and retrieval requirements.

This guide shows you how to create custom memory implementations for specialized requirements not covered by the built-in memory types. You'll learn to extend BaseMemory and implement the IAiMemory interface.

🏗️ Custom Memory Architecture


📋 Table of Contents


🎯 When to Build Custom Memory

Consider building custom memory when you need:

  • Custom Storage Backend: MongoDB, DynamoDB, Elasticsearch, etc.

  • Specialized Logic: Custom message filtering, transformation, or routing

  • Integration Requirements: Connect with existing systems or APIs

  • Performance Optimization: Specialized caching or indexing strategies

  • Domain-Specific Behavior: Industry-specific compliance or workflows

Use Built-in Memory If:

  • Standard storage needs (file, database, cache, session)

  • Common vector search requirements

  • No custom logic needed


📚 Understanding BaseMemory

BaseMemory provides the foundation for all memory implementations:

Provided Features

  • Message storage in variables.messages array

  • Unique key management with key() method

  • Metadata storage with metadata() method

  • Message validation and normalization

  • Export/import functionality

  • Event announcements

What You Implement

  • configure() - Initialize your custom storage

  • add() - Store messages (optional override)

  • getAll() - Retrieve messages

  • clear() - Remove all messages

  • Any custom methods specific to your needs

Key Properties


🔌 IAiMemory Interface

The IAiMemory interface defines the contract all memory implementations must follow:

Required Methods


Creating a Custom Memory

Example 1: Redis Memory

Store messages in Redis for distributed applications:

Usage:


Example 2: Priority Memory

Automatically prioritize and filter messages based on importance:

Usage:


Example 3: Rotating Memory

Implements time-based rotation with archiving:

Usage:


Advanced Examples

Example 4: Multi-Tenant Memory


Testing Your Memory

Unit Tests


Best Practices

1. Always Call super.configure()

2. Validate Configuration

3. Handle Errors Gracefully

4. Implement Export/Import

5. Add Event Announcements

6. Thread Safety


See Also


Next Steps: Explore Custom Vector Memory for building embedding-based memory providers.

Last updated