Skip to main content
{
  "items": [
    {
      "memory_id": "mem_abc123",
      "content": "User loves Italian cuisine",
      "categories": ["preferences", "food"],
      "created_at": "2024-01-15T10:30:00Z"
    },
    {
      "memory_id": "mem_def456",
      "content": "User is vegetarian",
      "categories": ["preferences", "food", "health"],
      "created_at": "2024-01-15T10:30:05Z"
    },
    {
      "memory_id": "mem_ghi789",
      "content": "Lives in New York City",
      "categories": ["personal", "location"],
      "created_at": "2024-01-12T14:20:00Z"
    }
  ],
  "total": 45,
  "has_more": true
}

Overview

Memories are facts, preferences, and contextual information extracted from processed sessions. RecallrAI automatically analyzes conversations to identify and store meaningful information about users. Memories are organized into categories and can be retrieved with filtering and pagination.

Memory Object

memory_id
string
required
Unique identifier for the memory.
content
string
required
The actual memory content (e.g., “User prefers Italian cuisine”, “Lives in New York”).
categories
array
required
List of category tags for the memory (e.g., ["preferences", "food"], ["personal", "location"]).
created_at
timestamp
required
ISO 8601 timestamp of when the memory was created.

Memory Categories

Memories are automatically categorized based on their content. Common categories include:
  • preferences - User likes, dislikes, and preferences
  • personal - Personal information (name, age, location, etc.)
  • professional - Work-related information
  • habits - Behavioral patterns and routines
  • health - Health-related information
  • relationships - Information about relationships with others
  • goals - User goals and aspirations
  • interests - Hobbies and interests
  • technical - Technical knowledge or skills
  • custom - Any custom categories defined in your application
Categories are automatically assigned by RecallrAI’s memory extraction system. You can filter memories by one or more categories when retrieving them.

Listing User Memories

Retrieve all memories for a user with optional filtering by categories.
from recallrai import RecallrAI

client = RecallrAI(
    api_key="rai_your_api_key",
    project_id="your_project_id"
)

user = client.get_user("alice_123")

# List all memories
memories = user.list_memories()

print(f"Total memories: {memories.total}")
for item in memories.items:
    print(f"- {item.content}")
    print(f"  Categories: {', '.join(item.categories)}")
    print(f"  Created: {item.created_at}")

# List with pagination
memories = user.list_memories(offset=0, limit=50)

# Filter by specific categories
food_prefs = user.list_memories(
    categories=["preferences", "food"]
)

print(f"\nFood preferences: {food_prefs.total}")
for item in food_prefs.items:
    print(f"- {item.content}")

# Check for more pages
if memories.has_more:
    # Calculate next offset
    next_offset = len(memories.items)
    next_memories = user.list_memories(offset=next_offset, limit=50)
offset
integer
default:"0"
Number of memories to skip (for pagination).
limit
integer
default:"20"
Maximum number of memories to return (1-100).
categories
array
List of category names to filter by. Returns memories that have ANY of the specified categories.
{
  "items": [
    {
      "memory_id": "mem_abc123",
      "content": "User loves Italian cuisine",
      "categories": ["preferences", "food"],
      "created_at": "2024-01-15T10:30:00Z"
    },
    {
      "memory_id": "mem_def456",
      "content": "User is vegetarian",
      "categories": ["preferences", "food", "health"],
      "created_at": "2024-01-15T10:30:05Z"
    },
    {
      "memory_id": "mem_ghi789",
      "content": "Lives in New York City",
      "categories": ["personal", "location"],
      "created_at": "2024-01-12T14:20:00Z"
    }
  ],
  "total": 45,
  "has_more": true
}
Category filtering is inclusive: When you specify multiple categories, memories matching ANY of those categories will be returned (OR logic, not AND).

Common Patterns

Get All Memories by Category

def get_all_memories_by_category(user, category):
    """Fetch all memories for a specific category."""
    all_memories = []
    offset = 0
    limit = 100
    
    while True:
        result = user.list_memories(
            offset=offset,
            limit=limit,
            categories=[category]
        )
        
        all_memories.extend(result.items)
        
        if not result.has_more:
            break
            
        offset += len(result.items)
    
    return all_memories

# Usage
food_memories = get_all_memories_by_category(user, "food")
print(f"Found {len(food_memories)} food-related memories")

Organize Memories by Category

def organize_memories_by_category(user):
    """Organize all memories into a dictionary by category."""
    memories = user.list_memories(limit=100)
    organized = {}
    
    for item in memories.items:
        for category in item.categories:
            if category not in organized:
                organized[category] = []
            organized[category].append(item.content)
    
    return organized

# Usage
memory_map = organize_memories_by_category(user)

print("Memory Categories:")
for category, contents in memory_map.items():
    print(f"\n{category.upper()} ({len(contents)} memories):")
    for content in contents[:3]:  # Show first 3
        print(f"  - {content}")

Search Memories by Keyword

def search_memories(user, keyword):
    """Search for memories containing a specific keyword."""
    all_memories = user.list_memories(limit=100)
    matching = [
        item for item in all_memories.items
        if keyword.lower() in item.content.lower()
    ]
    
    return matching

# Usage
italian_memories = search_memories(user, "italian")
print(f"Found {len(italian_memories)} memories about Italian:")
for mem in italian_memories:
    print(f"- {mem.content}")

Display Memory Timeline

from datetime import datetime

def display_memory_timeline(user, days=7):
    """Display memories created in the last N days."""
    memories = user.list_memories(limit=100)
    now = datetime.now()
    
    recent = []
    for item in memories.items:
        # Convert to timezone-aware if needed
        created = item.created_at
        if created.tzinfo is None:
            created = created.replace(tzinfo=now.tzinfo)
        
        days_ago = (now - created).days
        if days_ago <= days:
            recent.append((days_ago, item))
    
    # Sort by most recent
    recent.sort(key=lambda x: x[0])
    
    print(f"Memories from last {days} days:")
    for days_ago, item in recent:
        print(f"\n{days_ago} days ago:")
        print(f"  {item.content}")
        print(f"  Categories: {', '.join(item.categories)}")
    
    return recent

# Usage
timeline = display_memory_timeline(user, days=14)

Export Memories

import json

def export_memories_to_json(user, filename="memories.json"):
    """Export all user memories to a JSON file."""
    all_memories = []
    offset = 0
    limit = 100
    
    # Fetch all memories
    while True:
        result = user.list_memories(offset=offset, limit=limit)
        
        for item in result.items:
            all_memories.append({
                "memory_id": item.memory_id,
                "content": item.content,
                "categories": item.categories,
                "created_at": item.created_at.isoformat()
            })
        
        if not result.has_more:
            break
        
        offset += len(result.items)
    
    # Write to file
    with open(filename, 'w') as f:
        json.dump({
            "user_id": user.user_id,
            "total_memories": len(all_memories),
            "exported_at": datetime.now().isoformat(),
            "memories": all_memories
        }, f, indent=2)
    
    print(f"Exported {len(all_memories)} memories to {filename}")
    return all_memories

# Usage
export_memories_to_json(user, "alice_memories.json")

Memory Statistics

def get_memory_statistics(user):
    """Get statistics about user memories."""
    memories = user.list_memories(limit=100)
    
    # Count by category
    category_counts = {}
    for item in memories.items:
        for category in item.categories:
            category_counts[category] = category_counts.get(category, 0) + 1
    
    stats = {
        "total_memories": memories.total,
        "categories": category_counts,
        "most_common_category": max(category_counts.items(), key=lambda x: x[1]) if category_counts else None,
        "average_categories_per_memory": sum(len(item.categories) for item in memories.items) / len(memories.items) if memories.items else 0
    }
    
    return stats

# Usage
stats = get_memory_statistics(user)
print(f"Total Memories: {stats['total_memories']}")
print(f"\nCategory Breakdown:")
for category, count in sorted(stats['categories'].items(), key=lambda x: x[1], reverse=True):
    print(f"  {category}: {count}")
if stats['most_common_category']:
    print(f"\nMost Common: {stats['most_common_category'][0]} ({stats['most_common_category'][1]} memories)")

Understanding Memory Updates

Memories are automatically created and updated when you process sessions. You don’t manually create or update memories directly. Instead:
  1. Add messages to a session
  2. Process the session
  3. RecallrAI extracts and updates memories automatically
  4. Conflicting updates create merge conflicts (which you can resolve)
To update or correct a memory:
  1. Create a new session with correcting information
  2. Process the session
  3. If there’s a conflict, resolve it via the Merge Conflicts API

Memory Lifecycle

Error Handling

Raised when trying to list memories for a user that doesn’t exist.
from recallrai.exceptions import UserNotFoundError

try:
    memories = user.list_memories()
except UserNotFoundError as e:
    print(f"User not found: {e.message}")
Raised when invalid categories are provided.
from recallrai.exceptions import InvalidCategoriesError

try:
    # Invalid category names
    memories = user.list_memories(categories=["invalid_category"])
except InvalidCategoriesError as e:
    print(f"Invalid categories: {e.message}")

Best Practices

Pagination for large memory sets: If a user has many memories, use pagination to avoid loading everything at once. Start with a limit of 50-100.
Category filtering for performance: When you know what type of information you need, filter by category to reduce API calls and improve performance.
Monitor memory growth: Track the number of memories per user over time. A sudden spike might indicate issues with session processing or duplicate information.
Memories are read-only via API: You cannot directly create, update, or delete memories. They are managed automatically through session processing.

Next Steps

I