Skip to content

dabit3/agent-memory

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

agent-memory

Portable memory backend for AI agents. Framework-agnostic, with multiple memory types, session management, import/export, and memory decay.

The Problem

Every AI agent framework implements its own memory system. This creates several issues:

  1. No portability: Memories are locked into specific frameworks
  2. No standardization: Different formats, different APIs
  3. No inspection tools: Hard to see what an agent "remembers"
  4. Reinventing the wheel: Every project builds memory from scratch

agent-memory provides a standalone memory backend that works with any agent framework, supports multiple memory types, and includes tools for inspection, export, and maintenance.

Installation

npm install -g agent-memory

Or use locally in your project:

npm install agent-memory

Quick Start

CLI

# Initialize with examples
agent-memory init

# Store a memory
agent-memory store -k "user.name" -c "Alice" -t semantic --importance 0.9

# Query memories
agent-memory query --type semantic

# Get a specific memory
agent-memory get user.name

# Export all memories
agent-memory export -o backup.json

# Import memories
agent-memory import backup.json

Programmatic API

const { createMemoryStore, MemoryType } = require('agent-memory');

async function main() {
  // Initialize store (async because of SQL.js WASM loading)
  const store = await createMemoryStore({
    namespace: 'my-agent',
  });

  // Store a semantic memory (facts/knowledge)
  store.store({
    type: MemoryType.SEMANTIC,
    key: 'user.preferences',
    content: { theme: 'dark', language: 'en' },
    importance: 0.8,
    tags: ['user', 'settings'],
  });

  // Store an episodic memory (events)
  const session = store.startSession('conversation-1');
  store.store({
    type: MemoryType.EPISODIC,
    key: 'conversation.summary',
    content: 'Discussed project requirements',
    sessionId: session.id,
  });

  // Query memories
  const userMemories = store.query({
    tags: ['user'],
    minImportance: 0.5,
  });

  // Get a specific memory
  const prefs = store.get('user.preferences');

  store.close();
}

main();

Memory Types

Type Purpose Example
short_term Session-scoped, ephemeral Current conversation context
long_term Persistent across sessions User preferences, learned behaviors
episodic Specific events with temporal context "User mentioned birthday on March 5th"
semantic Facts and knowledge "User's name is Alice"
procedural How-to knowledge, skills "To book a meeting, check calendar first"

Key Features

Session Management

Track memories by conversation session:

const session = store.startSession('support-chat', { agent: 'claude' });

store.store({
  type: MemoryType.SHORT_TERM,
  key: 'context',
  content: 'User asked about billing',
  sessionId: session.id,
});

// Query session memories
const sessionMemories = store.query({ sessionId: session.id });

store.endSession(session.id);

Memory Linking

Create relationships between memories:

const dog = store.store({ type: MemoryType.SEMANTIC, key: 'concept.dog', content: 'canine' });
const bark = store.store({ type: MemoryType.SEMANTIC, key: 'concept.bark', content: 'sound' });

store.link(dog.id, bark.id, 'related_to', 0.8);

const related = store.getLinked(dog.id);

TTL and Expiration

Set automatic expiration for temporary memories:

store.store({
  type: MemoryType.SHORT_TERM,
  key: 'temp.context',
  content: 'Working on task X',
  ttl: 3600,  // Expires in 1 hour
});

// Clean up expired memories
store.cleanup();

Memory Decay

Reduce importance of unused memories over time:

// Apply 5% decay to memories with 0 accesses
store.decay({ factor: 0.95, minAccesses: 0 });

Consolidation

Promote important short-term memories to long-term:

store.consolidate({
  sessionId: session.id,
  minImportance: 0.5,
});

Import/Export

Portable format for backup and migration:

// Export
const backup = store.export();
fs.writeFileSync('memories.json', backup);

// Import to another store/namespace
const newStore = await createMemoryStore({ namespace: 'restored' });
newStore.import(fs.readFileSync('memories.json', 'utf-8'));

CLI Reference

agent-memory [options] [command]

Options:
  -d, --db <path>         Database path
  -n, --namespace <name>  Memory namespace (default: "default")

Commands:
  store             Store a new memory
  get <key>         Get a memory by key
  query|list        Query memories with filters
  delete <id>       Delete a memory by ID
  stats             Show memory statistics
  export            Export memories to portable format
  import <file>     Import memories from file
  session           Session management
  link              Link two memories
  linked <id>       Show linked memories
  cleanup           Remove expired memories
  forget            Remove memories matching criteria
  consolidate       Consolidate short-term to long-term
  decay             Apply decay to reduce importance
  init              Initialize with examples

API Reference

createMemoryStore(options)

const store = await createMemoryStore({
  dbPath: '~/.agent-memory/memory.db',  // SQLite database path
  namespace: 'default',                  // Isolate memories
  ttlEnabled: true,                      // Enable TTL checking
});

store.store(options)

store.store({
  type: MemoryType.SEMANTIC,      // Memory type
  key: 'unique.key',              // Unique key within namespace
  content: 'string or object',    // Memory content
  metadata: {},                   // Additional metadata
  importance: 0.5,                // 0-1, affects decay/consolidation
  ttl: 3600,                      // Time-to-live in seconds
  sessionId: 'uuid',              // Associate with session
  source: 'conversation',         // Where memory came from
  tags: ['tag1', 'tag2'],         // Searchable tags
  embedding: [0.1, 0.2, ...],     // Optional vector embedding
});

store.query(options)

const memories = store.query({
  type: MemoryType.SEMANTIC,      // Filter by type
  types: [TYPE1, TYPE2],          // Or multiple types
  sessionId: 'uuid',              // Filter by session
  tags: ['tag1'],                 // Filter by tags (any match)
  source: 'conversation',         // Filter by source
  minImportance: 0.5,             // Minimum importance
  search: 'keyword',              // Search content/keys
  limit: 100,                     // Max results
  offset: 0,                      // Pagination offset
  orderBy: 'created_at',          // Sort field
  order: 'DESC',                  // Sort direction
  includeExpired: false,          // Include expired memories
});

store.stats()

const stats = store.stats();
// {
//   namespace: 'default',
//   total: 42,
//   byType: { semantic: 20, episodic: 15, ... },
//   sessions: 5,
//   links: 10,
//   avgImportance: 0.65,
//   oldestMemory: '2024-01-01T...',
//   newestMemory: '2024-02-01T...',
// }

Integration Examples

With LangChain

const { createMemoryStore, MemoryType } = require('agent-memory');

class AgentMemoryBackend {
  constructor() {
    this.storePromise = createMemoryStore({ namespace: 'langchain-agent' });
  }

  async loadMemoryVariables() {
    const store = await this.storePromise;
    const memories = store.query({
      types: [MemoryType.LONG_TERM, MemoryType.SEMANTIC],
      limit: 10,
      orderBy: 'importance',
    });
    return { history: memories.map(m => m.content) };
  }

  async saveContext(input, output) {
    const store = await this.storePromise;
    store.store({
      type: MemoryType.EPISODIC,
      key: `turn.${Date.now()}`,
      content: { input, output },
    });
  }
}

With Custom Agents

const { createMemoryStore, MemoryType } = require('agent-memory');

class Agent {
  async init() {
    this.memory = await createMemoryStore({ namespace: 'my-agent' });
    this.session = this.memory.startSession();
  }

  remember(key, content, type = MemoryType.SEMANTIC) {
    return this.memory.store({
      type,
      key,
      content,
      sessionId: this.session.id,
    });
  }

  recall(key) {
    return this.memory.get(key);
  }

  search(query) {
    return this.memory.query({ search: query });
  }
}

File Format

The export format is a portable JSON structure:

{
  "version": "1.0",
  "format": "agent-memory",
  "namespace": "my-agent",
  "exportedAt": "2024-02-01T12:00:00Z",
  "memories": [...],
  "links": [...],
  "sessions": [...]
}

This format can be used to:

  • Backup agent memories
  • Transfer memories between systems
  • Debug and inspect agent state
  • Migrate between frameworks

License

MIT

About

Portable memory backend for AI agents - framework-agnostic, with multiple memory types, session management, and import/export

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors