Skip to main content
Long-term memory in AG-Kit enables agents to remember information across conversations and sessions. It provides persistent storage with semantic search, automatic memory extraction, and intelligent consolidation capabilities.

Overview

Long-term memory stores:
  • Persistent facts - Information that should be remembered indefinitely
  • User preferences - Personal settings and choices
  • Historical context - Past interactions and decisions
  • Domain knowledge - Learned information and insights
  • Relationships - Connections between concepts and entities
Unlike short-term memory (conversation history), long-term memory focuses on extracting and storing meaningful information that transcends individual conversations.

Memory Implementations

AG-Kit provides multiple long-term memory implementations:

Mem0LongTermMemory

Official Mem0 SDK integration with advanced AI-powered memory management. Features:
  • Automatic memory extraction from conversations
  • Semantic search with vector embeddings
  • Graph-based memory relationships
  • Intelligent memory consolidation
  • Deduplication and merging
  • Memory decay and reinforcement
  • Multi-user and multi-agent support
Use Cases:
  • Production AI applications
  • Personalized user experiences
  • Knowledge management systems
  • Multi-session conversations

TDAILongTermMemory

TDAI cloud-based long-term memory with enterprise features. Features:
  • Cloud-based persistent storage
  • Semantic search capabilities
  • Strategy-based memory organization
  • Scalable infrastructure
  • Enterprise-grade reliability
Use Cases:
  • Enterprise deployments
  • Large-scale applications
  • Distributed systems

Quick Start

Using Mem0LongTermMemory

import { Mem0LongTermMemory } from '@ag-kit/agents';

// Initialize Mem0 memory
const memory = new Mem0LongTermMemory({
  apiKey: process.env.MEM0_API_KEY!,
  userId: 'user-123',
  agentId: 'assistant-v1',
  appId: 'my-app'
});

// Test connection
await memory.ping();

// Extract and record memories from conversation
const messages = [
  { role: 'user', content: 'My name is Alice and I love pizza' },
  { role: 'assistant', content: 'Nice to meet you, Alice! I\'ll remember that you love pizza.' }
];

const extractedMemories = await memory.extractAndRecord(messages, {
  userId: 'user-123'
});

console.log('Extracted memories:', extractedMemories);
// [
//   { id: 'mem-1', content: 'User name is Alice', strategy: 'general', ... },
//   { id: 'mem-2', content: 'User loves pizza', strategy: 'preferences', ... }
// ]

Manual Memory Recording

// Record a specific memory manually
await memory.record({
  id: memory.generateMemoryId(),
  strategy: 'preferences',
  role: 'user',
  content: 'User prefers dark mode interface',
  metadata: {
    category: 'ui_preferences',
    confidence: 0.95,
    source: 'explicit_statement'
  },
  createdAt: new Date()
});

// Record multiple memories in batch
await memory.recordBatch([
  {
    id: memory.generateMemoryId(),
    strategy: 'facts',
    content: 'User works as a software engineer',
    metadata: { category: 'professional' },
    createdAt: new Date()
  },
  {
    id: memory.generateMemoryId(),
    strategy: 'preferences',
    content: 'User prefers TypeScript over JavaScript',
    metadata: { category: 'technical' },
    createdAt: new Date()
  }
]);

Core Operations

Recording Memories

Store new memories in long-term storage.
// Record single memory
await memory.record({
  id: 'mem-001',
  strategy: 'facts',
  role: 'user',
  content: 'User birthday is March 15th',
  metadata: {
    type: 'personal_info',
    verified: true
  },
  createdAt: new Date()
});

// Record batch of memories
const memories = [
  {
    id: 'mem-002',
    strategy: 'preferences',
    content: 'User likes morning meetings',
    metadata: {},
    createdAt: new Date()
  },
  {
    id: 'mem-003',
    strategy: 'facts',
    content: 'User lives in San Francisco',
    metadata: {},
    createdAt: new Date()
  }
];

await memory.recordBatch(memories);

Retrieving Memories

Query memories with various filters and search options.
// Retrieve all memories
const allMemories = await memory.retrieve({});

// Retrieve with limit
const recentMemories = await memory.retrieve({ limit: 10 });

// Retrieve by strategy
const preferences = await memory.retrieve({
  strategy: 'preferences',
  limit: 20
});

// Retrieve with pagination
const page1 = await memory.retrieve({ limit: 10, offset: 0 });
const page2 = await memory.retrieve({ limit: 10, offset: 10 });

// Retrieve with custom filters
const verifiedMemories = await memory.retrieve({
  filters: { verified: true },
  limit: 50
});
Find memories using natural language queries with semantic understanding.
// Search for memories about user preferences
const results = await memory.semanticSearch('What does the user like?', {
  limit: 5,
  threshold: 0.7 // Minimum similarity score
});

// Search within specific strategy
const foodPreferences = await memory.semanticSearch('favorite foods', {
  strategy: 'preferences',
  limit: 10
});

// Search with custom filters
const recentFacts = await memory.semanticSearch('user information', {
  strategy: 'facts',
  filters: { verified: true },
  limit: 20
});

console.log(results);
// [
//   { id: 'mem-1', content: 'User loves pizza', score: 0.92, ... },
//   { id: 'mem-2', content: 'User prefers dark mode', score: 0.85, ... }
// ]

Updating Memories

Modify existing memories with new information.
// Update memory content
await memory.update('mem-001', {
  content: 'User birthday is March 15th, 1990',
  metadata: {
    verified: true,
    updated_reason: 'Added birth year'
  }
});

// Update only metadata
await memory.update('mem-002', {
  metadata: {
    confidence: 0.98,
    last_confirmed: new Date().toISOString()
  }
});

// Change memory strategy
await memory.update('mem-003', {
  strategy: 'important_facts'
});

Deleting Memories

Remove memories by ID or query conditions.
// Delete by ID
await memory.delete('mem-001');

// Delete by query (all matching memories)
await memory.delete({
  strategy: 'temporary',
  filters: { expired: true }
});

// Clear all memories with specific strategy
await memory.clear('temporary');

// Clear all memories (use with caution!)
await memory.clear();

Advanced Features

Automatic Memory Extraction ( Mem0 Only )

Mem0 automatically extracts meaningful information from conversations.
// Extract memories from conversation
const conversation = [
  { role: 'user', content: 'I just moved to New York and started working at Google' },
  { role: 'assistant', content: 'Congratulations on your new job and move!' },
  { role: 'user', content: 'Thanks! I\'m excited but also nervous about the change' }
];

const extractedMemories = await memory.extractAndRecord(conversation, {
  userId: 'user-123',
  metadata: {
    conversation_id: 'conv-456',
    extraction_date: new Date().toISOString()
  }
});

// Mem0 intelligently extracts:
// - "User moved to New York"
// - "User works at Google"
// - "User is excited but nervous about change"
Find memories related to a specific memory using graph-based relationships.
// Get memories related to a specific memory
const relatedMemories = await memory.getRelatedMemories('mem-001', 3);
// Returns up to 3 related memories

// Example: If mem-001 is "User loves Italian food"
// Related memories might be:
// - "User's favorite restaurant is Luigi's"
// - "User is allergic to shellfish"
// - "User enjoys cooking pasta"

Memory Consolidation ( Mem0 Only )

Automatically deduplicate, merge, and optimize stored memories.
// Trigger memory consolidation
await memory.consolidate();

// Mem0 automatically:
// - Deduplicates similar memories
// - Merges related information
// - Applies memory decay to old, unused memories
// - Reinforces frequently accessed memories

Integration with Agents

Long-term memory integrates with agents for persistent, cross-session knowledge. Learn more: Complete Agent Integration Guide

Best Practices

1. Use Appropriate Strategies

Organize memories with meaningful strategies:
// Good: Clear strategy categorization
await memory.record({
  strategy: 'preferences',
  content: 'User prefers dark mode',
  /* ... */
});

// Bad: Generic or unclear strategy
await memory.record({
  strategy: 'general',
  content: 'User prefers dark mode',
  /* ... */
});

2. Add Rich Metadata

Include contextual information in metadata:
// Good: Rich metadata
await memory.record({
  content: 'User completed Python course',
  metadata: {
    category: 'education',
    skill_level: 'intermediate',
    completion_date: '2024-01-15',
    verified: true,
    source: 'certificate'
  },
  /* ... */
});

// Bad: Minimal metadata
await memory.record({
  content: 'User completed Python course',
  metadata: {},
  /* ... */
});
Take advantage of semantic search for better retrieval:
// Good: Natural language queries
const results = await memory.semanticSearch('What are the user\'s hobbies?');

// Less optimal: Exact keyword matching
const results = await memory.retrieve({ filters: { keyword: 'hobby' } });

Performance Considerations

Mem0LongTermMemory

  • Automatic Optimization: Mem0 handles deduplication and consolidation
  • Semantic Search: Fast vector-based similarity search
  • Scalability: Handles millions of memories efficiently
  • Network Latency: Requires API calls to Mem0 service
  • Caching: Consider caching frequently accessed memories

Query Optimization

// Efficient: Use limits and filters
const memories = await memory.retrieve({
  strategy: 'preferences',
  limit: 10,
  filters: { category: 'food' }
});

// Inefficient: Retrieve all and filter in code
const allMemories = await memory.retrieve({});
const filtered = allMemories.filter(m => m.strategy === 'preferences');

Comparison: Short-term vs Long-term Memory

AspectShort-term MemoryLong-term Memory
PurposeConversation historyPersistent knowledge
ScopeSingle sessionCross-session
StorageRecent messagesExtracted facts
RetrievalChronologicalSemantic search
LifespanSession durationIndefinite
SizeLimited by tokensUnlimited
Use CaseContext windowPersonalization

Next Steps