Skip to main content

MemoryLayer.ai Python SDK

Python SDK for MemoryLayer.ai - Memory infrastructure for AI agents.

Installation

pip install memorylayer-client

Quick Start

from memorylayer import MemoryLayerClient, MemoryType

async with MemoryLayerClient(
    base_url="http://localhost:61001",
    api_key="your-api-key",  # Optional for local development
    workspace_id="my-workspace"
) as client:
    # Store a memory
    memory = await client.remember(
        content="User prefers Python for backend development",
        type=MemoryType.SEMANTIC,
        importance=0.8,
        tags=["preferences", "programming"]
    )

    # Search memories
    results = await client.recall(
        query="what programming language does the user prefer?",
        limit=5
    )

    for memory in results.memories:
        print(f"{memory.content} (relevance: {memory.importance})")

    # Synthesize memories
    reflection = await client.reflect(
        query="summarize user's technology preferences"
    )
    print(reflection.reflection)

Features

  • Simple, Pythonic API - Async/await support with context managers
  • Type-safe - Full type hints with Pydantic models
  • Memory Operations - Remember, recall, reflect, forget, decay
  • Relationship Graph - Link memories with typed relationships
  • Repository Planning Graph - Typed client.rpg / sync_client.rpg namespaces for repository sync, traversal, overlays, conflicts, maintenance, and enrichment
  • Session Management - Working memory with TTL and commit
  • Batch Operations - Bulk create, update, delete
  • Error Handling - Comprehensive exception hierarchy

Core Operations

Remember (Store Memory)

memory = await client.remember(
    content="User prefers FastAPI over Flask",
    type=MemoryType.SEMANTIC,
    subtype=MemorySubtype.PREFERENCE,
    importance=0.8,
    tags=["preferences", "frameworks"],
    metadata={"source": "conversation"}
)

Recall (Search Memories)

from memorylayer import RecallMode, SearchTolerance

results = await client.recall(
    query="what frameworks does the user prefer?",
    types=[MemoryType.SEMANTIC],
    mode=RecallMode.RAG,  # Active mode: vector similarity + graph traversal
    limit=10,
    min_relevance=0.7,
    tolerance=SearchTolerance.MODERATE,
    include_associations=True  # Include related memories via graph traversal
)

# Note: LLM and Hybrid modes are deprecated. Use Context Environment's
# context_rlm() for LLM-powered analysis instead.

Recall can enforce a hard response budget and expose deterministic evidence:

result = await client.recall(
    "Who works for Acme?",
    budget_tokens=600,
    include_confidence=True,
    include_relations=True,
)
print(result.retrieval_confidence, result.budget_summary, result.relation_paths)

For compaction-safe sessions, capture raw transcript data first and resume from a single context pack and cursor:

from hashlib import sha256

checkpoint = await client.create_checkpoint(
    session.id,
    transcript_segment,
    content_hash=sha256(transcript_segment.encode()).hexdigest(),
    idempotency_key="host-session:boundary:hash",
    source_boundary=boundary,
)
pack = await client.get_context_pack(session.id, budget_tokens=2048)
delta = await client.get_context_delta(session.id, pack.cursor, budget_tokens=512)

Reflect (Synthesize Memories)

reflection = await client.reflect(
    query="summarize everything about the user's development workflow",
    detail_level="standard",  # "brief", "standard", or "detailed"
    include_sources=True
)

print(reflection.reflection)
from memorylayer import RelationshipType

association = await client.associate(
    source_id="mem_problem_123",
    target_id="mem_solution_456",
    relationship=RelationshipType.SOLVES,
    strength=0.9
)

Decay (Reduce Importance)

# Reduce memory importance over time
decayed = await client.decay("mem_123", decay_rate=0.1)

Trace (Memory Provenance)

# Get memory origin and association chain
trace = await client.trace_memory("mem_123")
print(trace["chain"])

Batch Operations

# Perform multiple operations in one request
results = await client.batch_memories([
    {"type": "create", "data": {"content": "Memory 1", "importance": 0.7}},
    {"type": "create", "data": {"content": "Memory 2", "importance": 0.8}},
    {"type": "delete", "data": {"memory_id": "mem_old", "hard": False}}
])
print(f"Successful: {results['successful']}, Failed: {results['failed']}")

Session Management

Sessions provide working memory with TTL that can be committed to long-term storage.

# Create session (auto-creates workspace if needed)
session = await client.create_session(
    ttl_seconds=3600,
    workspace_id="my-workspace"
)

# Store working memory
await client.set_context(
    session.id,
    "current_task",
    {"description": "Debugging auth", "file": "auth.py"}
)

# Retrieve working memory
context = await client.get_context(session.id, ["current_task"])

# Extend session TTL
await client.touch_session(session.id)

# Commit working memory to long-term storage
result = await client.commit_session(
    session.id,
    min_importance=0.5,
    deduplicate=True
)
print(f"Created {result['memories_created']} memories")

# Delete session
await client.delete_session(session.id)

Session Briefing

briefing = await client.get_briefing(lookback_minutes=1440)
print(briefing.recent_activity)

Context Environment

The Context Environment provides server-side Python execution for advanced memory analysis. Execute code, load memories into variables, and use LLM-powered reasoning.

Note: Context Environment operations require an active session. Call set_session() first.

Execute Python Code

# Set active session
client.set_session(session.id)

# Execute code in sandbox
await client.context_exec("import pandas as pd")
await client.context_exec("data = [1, 2, 3, 4, 5]")

# Execute and get result
result = await client.context_exec("sum(data)")
print(result["result"])  # 15

Load Memories into Sandbox

# Load memories as a variable
await client.context_load(
    var="preferences",
    query="user preferences",
    limit=20,
    min_relevance=0.7
)

# Inspect loaded data
state = await client.context_inspect("preferences")
print(state["type"], state["preview"])

Query with LLM

# Ask LLM to analyze sandbox variables
result = await client.context_query(
    prompt="Summarize the user's preferences and find patterns",
    variables=["preferences"]
)
print(result["response"])

Recursive Language Model (RLM)

# Run autonomous reasoning loop
result = await client.context_rlm(
    goal="Analyze coding preferences and identify contradictions",
    memory_query="coding preferences",
    max_iterations=10,
    detail_level="detailed"
)
print(result["result"])

Inject Values

# Inject data into sandbox
await client.context_inject(
    key="config",
    value={"debug": True, "max_retries": 3}
)

Status and Cleanup

# Check sandbox status
status = await client.context_status()
print(f"Variables: {status['variable_count']}")

# Checkpoint state (for enterprise persistence)
await client.context_checkpoint()

# Clean up sandbox
await client.context_cleanup()

Workspace Management

# Create workspace
workspace = await client.create_workspace("my-project")

# Get workspace
workspace = await client.get_workspace("ws_123")

# Update workspace
workspace = await client.update_workspace(
    "ws_123",
    name="New Name",
    settings={"key": "value"}
)

# Get workspace schema (relationship types, memory subtypes)
schema = await client.get_workspace_schema("ws_123")
print(schema["relationship_types"])

Memory Types

Cognitive Types

  • Episodic - Specific events/interactions
  • Semantic - Facts, concepts, relationships
  • Procedural - How to do things
  • Working - Current task context (session-scoped)

Domain Subtypes

  • Solution - Working fixes to problems
  • Problem - Issues encountered
  • Code Pattern - Reusable patterns
  • Fix - Bug fixes with context
  • Error - Error patterns and resolutions
  • Workflow - Process knowledge
  • Preference - User/project preferences
  • Decision - Architectural decisions
  • Directive - User instructions/constraints

Relationship Types

Link memories with typed relationships organized into 11 categories. The SDK supports 60+ relationship types:

from memorylayer import RelationshipType

# Causal (4 types)
RelationshipType.CAUSES
RelationshipType.TRIGGERS
RelationshipType.LEADS_TO
RelationshipType.PREVENTS

# Solution (4 types)
RelationshipType.SOLVES
RelationshipType.ADDRESSES
RelationshipType.ALTERNATIVE_TO
RelationshipType.IMPROVES

# Learning (4 types)
RelationshipType.BUILDS_ON
RelationshipType.CONTRADICTS
RelationshipType.CONFIRMS
RelationshipType.SUPERSEDES

# Similarity (3 types)
RelationshipType.SIMILAR_TO
RelationshipType.VARIANT_OF
RelationshipType.RELATED_TO

# Workflow (4 types)
RelationshipType.FOLLOWS
RelationshipType.DEPENDS_ON
RelationshipType.ENABLES
RelationshipType.BLOCKS

# Quality (3 types)
RelationshipType.EFFECTIVE_FOR
RelationshipType.PREFERRED_OVER
RelationshipType.DEPRECATED_BY

# Context (4 types)
RelationshipType.OCCURS_IN
RelationshipType.APPLIES_TO
RelationshipType.WORKS_WITH
RelationshipType.REQUIRES

# ... and more categories (11 total)

Error Handling

from memorylayer import (
    MemoryLayerError,
    AuthenticationError,
    NotFoundError,
    ValidationError,
    RateLimitError,
    ServerError
)

try:
    memory = await client.get_memory("mem_123")
except NotFoundError:
    print("Memory not found")
except AuthenticationError:
    print("Invalid API key")
except ValidationError as e:
    print(f"Validation error: {e}")
except RateLimitError:
    print("Rate limit exceeded")
except ServerError as e:
    print(f"Server error: {e.status_code}")
except MemoryLayerError as e:
    print(f"MemoryLayer error: {e}")

Configuration

client = MemoryLayerClient(
    base_url="http://localhost:61001",  # Default
    api_key="your-api-key",             # Optional for local dev
    workspace_id="my-workspace",        # Default workspace
    session_id="sess_123",              # Optional active session
    timeout=30.0                        # Request timeout in seconds
)

Development

Install Development Dependencies

pip install -e ".[dev]"

Run Tests

pytest

Type Checking

mypy src/memorylayer

Linting

ruff check src/memorylayer
ruff format src/memorylayer

License

Apache 2.0 License -- see LICENSE for details.

Metadata

Release files for memorylayer-client 0.2.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for memorylayer-client 0.2.1
File Size Uploaded
memorylayer_client-0.2.1.tar.gz 71.9 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for memorylayer-client 0.2.1
File Interpreter ABI Platform
memorylayer_client-0.2.1-py3-none-any.whl Python 3 none any Details

Total release size: 150.9 kB

Release files / memorylayer_client-0.2.1.tar.gz

Download URL memorylayer_client-0.2.1.tar.gz
Size 71.9 kB
Tags Source
SHA-256 checksum
How to use checksums
bdec01d07160afeeaccdfc2100d153d8afd860dbd36f7d028dff36e9bab11504
BLAKE2b-256 checksum
How to use checksums
7fd2ea73b38d6a6ba4cfc55323808c5f9729fa1d1893f99bcaa533be64ea03e6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 9, 2026.

Transparency log

Release files / memorylayer_client-0.2.1-py3-none-any.whl

Download URL memorylayer_client-0.2.1-py3-none-any.whl
Size 79.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
bed3d32bc006e39f58324198434ea77e10207187e95aef2a0c7c587b9d838514
BLAKE2b-256 checksum
How to use checksums
2b1ccf317de72ec25c7fdd952b3b4b8c3bbe029aa05eaa77a06c9b7bb5c52900
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 9, 2026.

Transparency log

Release history Release notifications | RSS feed

This release

0.2.1 This release

2 release files

0.2.0

2 release files

0.1.22

2 release files

0.0.5

2 release files

0.0.4

2 release files

0.0.3

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page