Skip to main content
MemLayer raises specific, typed exception classes for every failure mode. Instead of parsing error messages or inspecting raw HTTP status codes, you can catch exactly the error you care about and handle it appropriately — keeping your agent resilient and easy to debug.

Exception Types

ExceptionWhen RaisedRecommended Action
AuthenticationErrorInvalid or missing API keyVerify your ml_live_xxx key and check it’s set correctly
PlanLimitErrorMemory count limit reached for your planUpgrade your plan or delete old memories to free up space
DuplicateMemoryErrorAn identical memory already existsSafe to ignore — no action needed
MemoryNotFoundErrorThe memory_id does not existVerify the UUID; it may have been deleted or expired
MemLayerErrorAny other API errorInspect e.status_code and e.detail for specifics
All exceptions except MemLayerError are subclasses of MemLayerError, so you can catch the base class as a final fallback while still handling specific cases first.

Full Example

Import all exception classes alongside the client and wrap your calls in a try/except block:
from memlayer import (
    MemLayerClient,
    AuthenticationError,
    PlanLimitError,
    MemoryNotFoundError,
    DuplicateMemoryError,
    MemLayerError,
)

client = MemLayerClient(api_key="ml_live_xxx")

try:
    result = client.remember(
        "User prefers dark mode",
        user_id="user_123",
        agent_id="support_bot",
    )
    print(f"Stored: {result.id}")

except AuthenticationError:
    print("Invalid API key — check your ml_live_xxx key")

except PlanLimitError:
    print("Memory limit reached — upgrade your plan at memlayer.online")

except DuplicateMemoryError:
    print("This memory already exists — skipped")

except MemoryNotFoundError:
    print("Memory ID not found")

except MemLayerError as e:
    print(f"API error {e.status_code}: {e.detail}")

Handling Plan Limits

When you hit your plan’s memory limit, every remember() call raises PlanLimitError until you free up space or upgrade.
On the Free plan you can store up to 500 memories. On Pro, 50,000. If you hit the limit in production, new memories are silently dropped unless you handle PlanLimitError. Always have a strategy for this case.
Check how many memories a user has before storing a new one by calling client.list() and reading .total:
from memlayer import MemLayerClient, PlanLimitError

client = MemLayerClient(api_key="ml_live_xxx")

# Check current usage before storing
page = client.list(
    user_id="user_123",
    agent_id="support_bot",
    limit=1,   # we only need the total count
    offset=0,
)

PLAN_LIMIT = 500  # adjust for your plan

if page.total >= PLAN_LIMIT:
    print(f"At limit ({page.total} memories). Pruning oldest entries...")
    # Implement your eviction strategy here
else:
    try:
        client.remember(
            "New fact about user",
            user_id="user_123",
            agent_id="support_bot",
        )
    except PlanLimitError:
        # Race-condition safety net
        print("Plan limit hit — skipping store")

Handling Duplicates

DuplicateMemoryError is raised when remember() detects content that is near-identical to an existing memory (cosine similarity ≥ 0.95 by default). This is almost always safe to ignore — the memory you wanted to store is already there. The recommended pattern is to catch it, log it at debug level, and continue:
import logging
from memlayer import MemLayerClient, DuplicateMemoryError

log = logging.getLogger(__name__)
client = MemLayerClient(api_key="ml_live_xxx")

def store_safely(content: str, user_id: str, agent_id: str) -> str | None:
    """Store a memory, returning the ID or None if it already exists."""
    try:
        result = client.remember(
            content,
            user_id=user_id,
            agent_id=agent_id,
        )
        return result.id

    except DuplicateMemoryError:
        log.debug("Skipped duplicate memory for user=%s: %r", user_id, content[:60])
        return None  # already stored — nothing to do
Alternatively, you can pre-check with is_duplicate() before calling remember() — useful in high-throughput pipelines where you want to avoid even the first store request:
if not client.is_duplicate(content, user_id="user_123", agent_id="support_bot"):
    client.remember(content, user_id="user_123", agent_id="support_bot")

REST API Error Codes

If you’re calling the MemLayer API directly without the SDK, use this reference for HTTP status codes:
CodeMeaningNotes
401Invalid or missing API keyCheck the X-API-Key header
402Plan limit reachedUpgrade or delete memories to free space
403Account suspendedContact support@memlayer.online
404Memory not foundThe memory_id does not exist or has expired
409Duplicate memoryNear-identical content already stored — safe to ignore
422Validation errorCheck the request body; the response includes field-level details
All error responses return a JSON body with a detail field:
{
  "detail": "Memory limit reached (500/500) for plan 'free'. Upgrade to store more."
}
For 422 errors, the body also includes an errors array with per-field information:
{
  "detail": "Validation failed",
  "errors": [
    {
      "field": "body → importance",
      "message": "Input should be less than or equal to 1",
      "type": "less_than_equal"
    }
  ]
}