Skip to content

Python API Reference

Reference for memorylayer-client 0.2.x. Everything below is importable from the top-level memorylayer package.

MemoryLayerClient

The main async client class for interacting with MemoryLayer. Use it as an async context manager; the transport is opened on __aenter__ and closed on __aexit__.

Constructor

MemoryLayerClient(
base_url: str = "http://localhost:61001",
api_key: str | None = None,
workspace_id: str | None = None,
session_id: str | None = None,
timeout: float = 30.0,
default_authority: AuthorityContext | None = None,
*,
max_retries: int = 3,
transport: str | Transport = "http",
aether_client: Any = None,
aether_target: str = "sv::memorylayer",
)

Parameters:

ParameterTypeDefaultDescription
base_urlstr"http://localhost:61001"Server URL (HTTP transport only). The SDK appends /v1.
api_keystr | NoneNoneAPI key, sent as Authorization: Bearer <key>
workspace_idstr | NoneNoneDefault workspace ID for operations that accept one
session_idstr | NoneNoneActive session ID (sent as X-Session-ID header)
timeoutfloat30.0Request timeout in seconds
default_authorityAuthorityContext | NoneNoneOn-behalf-of authority applied to every request that does not override it
max_retriesint3Retries for idempotent requests (GET/PUT/DELETE/PATCH/HEAD/OPTIONS) on 5xx, 429, or connection errors, honoring Retry-After. POST is never retried. 0 disables. HTTP transport only.
transportstr | Transport"http""http", "aether", or a custom Transport instance
aether_clientAnyNoneRequired when transport="aether": an already-connected Aether AsyncAgentClient or AsyncServiceClient
aether_targetstr"sv::memorylayer"Aether service topic (Aether transport only)

See Aether Transport for the Aether options.

Usage:

async with MemoryLayerClient(
base_url="http://localhost:61001",
api_key="your-key",
workspace_id="ws_123"
) as client:
memory = await client.remember("Hello world")

Namespaces

The client exposes four sub-APIs as attributes:

AttributeClassSurface
client.skillsSkillsAPISkills
client.mcp_serversMcpServersAPIMCP server registry
client.kbKnowledgebaseAPIKnowledgebase
client.rpgRpgAPIRepository Planning Graph

On-Behalf-Of (OBO) Scoping

acting_for()

Async context manager that yields a proxy with an OBO authority baked in. The underlying client is not mutated, so it is safe to use concurrently for different subjects.

@asynccontextmanager
async def acting_for(
grant_id: str,
subject: tuple[str, str] | None = None,
) -> AsyncIterator[_OBOProxy]
async with client.acting_for("g_abc", subject=("user", "alice")) as alice:
await alice.remember("Alice prefers dark mode")
await alice.recall("preferences", workspace_id="ws_work")
await alice.skills.list()

When subject is omitted, requests use direct authority (X-Aether-Authority-Mode: direct). The proxy exposes remember, recall, reflect, append_messages, delete_message, acting_for, for_workspace, and scoped skills, mcp_servers, and kb namespaces.

for_workspace()

def for_workspace(workspace_id: str) -> _OBOProxy

Returns the same kind of proxy with workspace_id bound and the client’s default_authority applied.

Most methods also accept a per-call authority: AuthorityContext | None argument, which overrides both the proxy authority and default_authority.


Memory Operations

remember()

Store a new memory.

async def remember(
content: str,
type: str | MemoryType | None = None,
subtype: str | None = None,
importance: float = 0.5,
tags: list[str] | None = None,
metadata: dict[str, Any] | None = None,
context_id: str | None = None,
user_id: str | None = None,
workspace_id: str | None = None,
authority: AuthorityContext | None = None,
relations: list[EntityRelationInput | dict[str, Any]] | None = None,
) -> Memory

Parameters:

ParameterTypeDefaultDescription
contentstrrequiredMemory content to store
typeMemoryType | str | NoneNoneCognitive memory type
subtypestr | NoneNoneDomain subtype (a MemorySubtype value)
importancefloat0.5Importance score 0.0-1.0
tagslist[str] | NoneNoneTags for categorization
metadatadict | NoneNoneAdditional metadata
context_idstr | NoneNoneContext within workspace
user_idstr | NoneNoneUser ID to associate
workspace_idstr | Noneclient defaultWorkspace override
authorityAuthorityContext | NoneNonePer-call OBO authority
relationslist[EntityRelationInput | dict] | NoneNoneEntity relations to write alongside the memory (requires the server’s entity registry). The outcome is reported on Memory.relation_write_result.

Returns: Memory

memory = await client.remember(
content="User prefers concise code comments",
type=MemoryType.SEMANTIC,
subtype=MemorySubtype.PREFERENCE,
importance=0.8,
tags=["preferences", "coding-style"]
)

recall()

Search memories by semantic query.

async def recall(
query: str,
types: list[str | MemoryType] | None = None,
subtypes: list[str] | None = None,
tags: list[str] | None = None,
mode: str | RecallMode | None = None,
limit: int = 10,
min_relevance: float | None = None,
recency_weight: float | None = None,
tolerance: str | SearchTolerance | None = None,
include_associations: bool | None = None,
traverse_depth: int | None = None,
max_expansion: int | None = None,
created_after: str | None = None,
created_before: str | None = None,
offset: int | None = None,
event_after: str | None = None,
event_before: str | None = None,
time_order: str | None = None,
include_global: bool | None = None,
include_global_user: bool | None = None,
user_id: str | None = None,
workspace_id: str | None = None,
authority: AuthorityContext | None = None,
budget_tokens: int | None = None,
include_confidence: bool = True,
include_relations: bool = True,
) -> RecallResult

Parameters (None means “use the server default”):

ParameterTypeDefaultDescription
querystrrequiredNatural language search query
typeslist[MemoryType | str] | NoneNoneFilter by memory types
subtypeslist[str] | NoneNoneFilter by subtypes
tagslist[str] | NoneNoneFilter by tags
modeRecallMode | str | NoneNoneRetrieval mode (rag, llm, hybrid)
limitint10Maximum memories to return
min_relevancefloat | NoneNoneMinimum relevance score 0.0-1.0
recency_weightfloat | NoneNoneWeight for recency in ranking 0.0-1.0
toleranceSearchTolerance | str | NoneNoneSearch precision (loose, moderate, strict)
include_associationsbool | NoneNoneInclude linked memories
traverse_depthint | NoneNoneMulti-hop graph traversal depth
max_expansionint | NoneNoneMax memories discovered via graph expansion
created_after / created_beforestr | NoneNoneISO 8601 creation-time bounds
offsetint | NoneNoneResults to skip (pagination)
event_after / event_beforestr | NoneNoneISO 8601 bounds on the memory’s effective event time
time_orderstr | NoneNoneOrder by effective event time: "asc" or "desc" (default: by relevance)
include_globalbool | NoneNoneInclude the _global workspace
include_global_userbool | NoneNoneInclude the user-scoped _global_user workspace (only effective when user_id is set)
user_idstr | NoneNoneFilter by user ID
workspace_idstr | Noneclient defaultWorkspace override
authorityAuthorityContext | NoneNonePer-call OBO authority
budget_tokensint | NoneNoneToken budget for the returned memories; see RecallResult.budget_summary
include_confidenceboolTrueReturn retrieval_confidence and confidence_reasons
include_relationsboolTrueReturn entity relation_paths

Returns: RecallResult

results = await client.recall(
query="coding preferences",
types=[MemoryType.SEMANTIC],
limit=5,
min_relevance=0.7
)
# Temporal query: what happened last week, oldest first
timeline = await client.recall(
query="deployment incidents",
event_after="2026-09-14T00:00:00Z",
event_before="2026-09-21T00:00:00Z",
time_order="asc",
)

reflect()

Synthesize insights across memories.

async def reflect(
query: str,
max_tokens: int = 500,
include_sources: bool = True,
authority: AuthorityContext | None = None,
) -> ReflectResult
ParameterTypeDefaultDescription
querystrrequiredWhat to reflect on
max_tokensint500Maximum tokens in reflection
include_sourcesboolTrueInclude source memory IDs
authorityAuthorityContext | NoneNonePer-call OBO authority

Returns: ReflectResult with fields: reflection: str, source_memories: list[str], confidence: float, tokens_processed: int | None

get_memory()

async def get_memory(memory_id: str) -> Memory

update_memory()

async def update_memory(
memory_id: str,
content: str | None = None,
importance: float | None = None,
tags: list[str] | None = None,
metadata: dict[str, Any] | None = None,
) -> Memory

Only the fields you pass are changed.

forget()

Delete or soft-delete a memory.

async def forget(memory_id: str, hard: bool = False) -> bool

hard=True permanently deletes; the default is a soft delete. Returns True on success.

decay()

Reduce a memory’s importance.

async def decay(memory_id: str, decay_rate: float = 0.1) -> Memory

list_memories()

Browse memories ordered by recency (no vector search).

async def list_memories(
*,
limit: int = 50,
offset: int = 0,
type: str | MemoryType | None = None,
subtype: str | None = None,
tag: str | None = None,
context_id: str | None = None,
authority: AuthorityContext | None = None,
) -> RecallResult

total_count on the result is the size of the returned page, not a grand total. Use iterate_memories() to walk every page.

iterate_memories()

Async generator that auto-paginates list_memories().

async def iterate_memories(
*,
page_size: int = 50, # clamped to 200
type: str | MemoryType | None = None,
subtype: str | None = None,
tag: str | None = None,
context_id: str | None = None,
authority: AuthorityContext | None = None,
) -> AsyncGenerator[Memory, None]
async for mem in client.iterate_memories(tag="preferences"):
print(mem.content)

batch_memories()

Perform multiple create/update/delete operations in one request.

async def batch_memories(operations: list[dict[str, Any]]) -> dict[str, Any]

The operations are sent to the server unchanged. Each one is a flat object whose op field is "create", "update", or "delete":

results = await client.batch_memories([
{"op": "create", "content": "Memory 1", "importance": 0.7, "tags": ["a"]},
{"op": "update", "memory_id": "mem_123", "content": "Updated", "pinned": True},
{"op": "delete", "memory_id": "mem_old", "hard": False},
])
print(results["successful"], results["failed"])

Returns: Dict with total_operations, successful, failed, and results (one entry per operation with index, type, status, memory_id, error).


Association Operations

associate()

Create a relationship between memories.

async def associate(
source_id: str,
target_id: str,
relationship: str | RelationshipType,
strength: float = 0.5,
metadata: dict[str, Any] | None = None,
) -> Association
assoc = await client.associate(
"mem_123", "mem_456",
RelationshipType.SOLVES, strength=0.9
)

get_associations()

async def get_associations(memory_id: str, direction: str = "both") -> list[Association]

direction is "outgoing", "incoming", or "both".

update_association()

Update an edge’s strength and/or metadata. The relationship type cannot be changed; delete and recreate instead.

async def update_association(
memory_id: str,
association_id: str,
*,
strength: float | None = None,
metadata: dict[str, Any] | None = None,
authority: AuthorityContext | None = None,
) -> bool

memory_id must be one of the association’s endpoints. Returns False if the association was not found.

delete_association()

async def delete_association(
memory_id: str,
association_id: str,
*,
authority: AuthorityContext | None = None,
) -> bool

Returns False if the association was not found.

traverse_graph()

Multi-hop traversal from a starting memory.

async def traverse_graph(
memory_id: str,
*,
max_depth: int = 2, # 1-5
relationship_types: list[str] | None = None,
direction: str = "both",
min_strength: float = 0.0,
workspace_id: str | None = None,
authority: AuthorityContext | None = None,
) -> dict[str, Any]

Returns: Dict with paths, total_paths, unique_nodes, and query_latency_ms.


Entity Registry

These methods require the server’s entity registry. If the server returns 501 for it, they raise EnterpriseRequiredError.

async def list_entities(*, status: str = "active", limit: int = 100,
workspace_id: str | None = None,
authority: AuthorityContext | None = None) -> list[Entity]
async def get_entity(entity_id: str, *, workspace_id: str | None = None,
authority: AuthorityContext | None = None) -> Entity
async def resolve_entity(name: str, *, entity_type: str = "person",
workspace_id: str | None = None,
authority: AuthorityContext | None = None) -> EntityResolution | None
async def merge_entities(source_id: str, target_id: str, *, reason: str,
workspace_id: str | None = None,
authority: AuthorityContext | None = None) -> Entity
MethodNotes
list_entities()status is "active" or "merged". Ordered by ID.
resolve_entity()Maps a surface name or alias to an existing canonical entity. Never creates one; returns None when nothing matches.
merge_entities()Merges source_id into target_id and returns the surviving entity. reason is recorded in its provenance.

API Tokens

async def create_token(name: str, *, principal_type: str = "User",
workspace_patterns: list[str] | None = None, # default ["*"]
scopes: list[str] | None = None, # default ["*"]
expires_in_days: int | None = None,
authority: AuthorityContext | None = None) -> TokenCreateResult
async def list_tokens(*, include_revoked: bool = False,
authority: AuthorityContext | None = None) -> list[TokenInfo]
async def get_token(token_id: str, *, authority: AuthorityContext | None = None) -> TokenInfo
async def revoke_token(token_id: str, *, authority: AuthorityContext | None = None) -> None
async def delete_token(token_id: str, *, authority: AuthorityContext | None = None) -> None

TokenCreateResult carries the plaintext token. It is only returned at creation time. Revoked tokens stop working immediately but remain visible in list_tokens(include_revoked=True).


Session Operations

create_session()

Create a new working memory session. The workspace and context are auto-created if they don’t exist.

async def create_session(
ttl_seconds: int = 3600,
workspace_id: str | None = None,
context_id: str | None = None,
auto_set_session: bool = True,
) -> Session
ParameterTypeDefaultDescription
ttl_secondsint3600Time to live in seconds
workspace_idstr | NoneNoneWorkspace ID (auto-created if needed)
context_idstr | NoneNoneContext ID (defaults to _default)
auto_set_sessionboolTrueMake this the active session

get_session() / list_sessions() / delete_session() / touch_session()

async def get_session(session_id: str) -> Session
async def list_sessions(workspace_id: str | None = None, context_id: str | None = None,
include_expired: bool = False) -> list[dict[str, Any]]
async def delete_session(session_id: str) -> bool
async def touch_session(session_id: str) -> dict[str, Any] # extends TTL; returns expires_at

set_session() / get_session_id() / clear_session()

def set_session(session_id: str) -> None
def get_session_id() -> str | None
def clear_session() -> None

Synchronous helpers that manage the active session ID. When set, it is sent as the X-Session-ID header on all requests.

set_context() / get_context()

Key-value working memory scoped to a session.

async def set_context(session_id: str, key: str, value: Any,
ttl_seconds: int | None = None) -> None
async def get_context(session_id: str, keys: list[str]) -> dict[str, Any]

commit_session()

Extract long-term memories from session working memory.

async def commit_session(
session_id: str,
min_importance: float = 0.5,
deduplicate: bool = True,
categories: list[str] | None = None,
max_memories: int = 50,
) -> dict[str, Any]

Returns: Dict with memories_extracted, memories_deduplicated, memories_created, and related stats.

Session checkpoints

Checkpoints capture a raw transcript segment so a session can be recovered after context compaction.

async def create_checkpoint(
session_id: str,
transcript_segment: str,
*,
content_hash: str,
idempotency_key: str,
source_kind: str = "transcript",
source_sequence: int | None = None,
source_boundary: int | None = None,
) -> SessionCheckpoint
async def get_checkpoint(session_id: str, checkpoint_id: str) -> SessionCheckpoint

content_hash is the SHA-256 of the segment. idempotency_key is scoped to the session, so a retried call does not create a duplicate. SessionCheckpoint reports capture_status, index_status, and enrichment_status.

Context packs and deltas

A context pack is a budgeted, rendered bundle of what an agent needs to resume a session. It comes with a cursor. Pass that cursor to get_context_delta() later to get only what changed since then.

async def get_context_pack(
session_id: str,
*,
topic: str | None = None,
entity_ids: list[str] | None = None,
entity_names: list[str] | None = None,
budget_tokens: int = 2048,
section_limits: dict[str, int] | None = None,
**inclusion_controls: bool,
) -> ContextPack
async def get_context_delta(
session_id: str,
cursor: str,
*,
budget_tokens: int = 2048,
) -> ContextDelta

inclusion_controls are forwarded to the server. It accepts include_directives, include_working_memory, include_recent_activity, include_contradictions, include_sandbox_summary, and include_checkpoint_recovery, all of which default to True.

pack = await client.get_context_pack(session.id, topic="auth refactor", budget_tokens=1500)
print(pack.rendered)
later = await client.get_context_delta(session.id, pack.cursor)
if later.items:
print(later.rendered)

ContextPack fields: rendered, items: list[ContextPackItem], open_threads, unresolved_contradictions, budget_summary, generation_summary, cursor, degradation_notices. ContextDelta has rendered, items, budget_summary, generation_summary, cursor, has_more, and degradation_notices.

get_briefing()

async def get_briefing(
lookback_hours: int | None = None,
lookback_minutes: int = 60,
detail_level: str = "abstract",
limit: int = 10,
include_memories: bool = True,
include_contradictions: bool = True,
) -> SessionBriefing
ParameterTypeDefaultDescription
lookback_hoursint | NoneNoneDeprecated. If set, it overrides lookback_minutes.
lookback_minutesint60Time window in minutes
detail_levelstr"abstract""abstract", "overview", or "full"
limitint10Max recent memories to include
include_memoriesboolTrueInclude memory content
include_contradictionsboolTrueFlag contradicting memories

Returns: SessionBriefing with fields: workspace_summary, recent_activity, open_threads, contradictions_detected.


Workspace Operations

async def create_workspace(name: str, tags: list[str] | None = None) -> Workspace
async def list_workspaces(tags: list[str] | None = None, match: str = "all") -> list[Workspace]
async def get_workspace(workspace_id: str | None = None) -> Workspace
async def update_workspace(workspace_id: str, name: str | None = None,
settings: dict[str, Any] | None = None,
tags: list[str] | None = None) -> Workspace
async def get_workspace_schema(workspace_id: str) -> dict[str, Any]
  • list_workspaces(tags=...) filters by discovery tags. match="all" requires every tag, match="any" requires at least one.
  • get_workspace() uses the client’s default workspace_id if none is given.
  • get_workspace_schema() returns relationship_types, memory_subtypes, and can_customize.

Contexts

async def create_context(workspace_id: str, name: str, description: str | None = None,
settings: dict[str, Any] | None = None) -> dict[str, Any]
async def list_contexts(workspace_id: str) -> list[dict[str, Any]]
async def delete_context(context_id: str, workspace_id: str | None = None) -> None

Export and import

async def export_workspace(workspace_id: str | None = None, include_associations: bool = True,
offset: int = 0, limit: int = 0) -> dict
async def export_workspace_stream(workspace_id: str | None = None, include_associations: bool = True,
offset: int = 0, limit: int = 0) -> AsyncGenerator[dict, None]
async def import_workspace(workspace_id: str, data: dict) -> dict
async def import_workspace_stream(workspace_id: str, ndjson_lines: list[dict]) -> dict
  • export_workspace() returns version, workspace_id, memories, associations, total_memories, and total_associations. limit=0 exports everything.
  • export_workspace_stream() yields NDJSON objects with a type of "header", "memory", "association", or "footer". Memory and association payloads are under data.
  • Imports return imported, skipped_duplicates, and errors.

Chat Thread Operations

Chat threads store conversation history and can be decomposed into memories. By default threads are user-owned (ownership="user"). They live in the cross-workspace _user_chat home (USER_CHAT_HOME_WORKSPACE), and the caller’s workspace is stamped on each message’s metadata under app_workspace (MESSAGE_META_APP_WORKSPACE_KEY). Pass ownership="workspace" for workspace-scoped storage.

create_thread()

async def create_thread(
*,
workspace_id: str | None = None,
thread_id: str | None = None,
user_id: str | None = None,
context_id: str | None = None,
observer_id: str | None = None,
subject_id: str | None = None,
title: str | None = None,
metadata: dict[str, Any] | None = None,
expires_at: str | None = None,
scope: str | None = None,
ownership: str = "user",
) -> ChatThread

The thread_id parameter is still accepted, but the server ignores it because thread IDs are always generated by the server.

list_threads() / list_user_threads()

async def list_threads(*, workspace_id: str | None = None, user_id: str | None = None,
limit: int = 50, offset: int = 0,
scope_filter: str | None = None,
ownership_filter: str | None = None) -> list[ChatThread]
async def list_user_threads(user_id: str, *, ownership: str = "user",
scope_filter: str | None = None,
limit: int = 50, offset: int = 0) -> list[ChatThread]

list_user_threads() lists a user’s threads across all workspaces and needs no workspace_id.

get_thread() / get_thread_full() / update_thread() / delete_thread()

async def get_thread(thread_id: str, *, workspace_id: str | None = None) -> ChatThread
async def get_thread_full(thread_id: str, *, workspace_id: str | None = None,
limit: int = 100, offset: int = 0,
order: str = "asc") -> ChatThreadWithMessages
async def update_thread(thread_id: str, *, workspace_id: str | None = None,
title: str | None = None,
metadata: dict[str, Any] | None = None) -> ChatThread
async def delete_thread(thread_id: str, *, workspace_id: str | None = None) -> None

ChatThreadWithMessages has thread, messages, and total_messages.

append_messages() / get_messages() / delete_message()

async def append_messages(thread_id: str, messages: list[dict[str, Any]], *,
workspace_id: str | None = None, ownership: str = "user",
authority: AuthorityContext | None = None) -> list[ChatMessage]
async def get_messages(thread_id: str, *, workspace_id: str | None = None,
limit: int = 100, offset: int = 0,
after_index: int | None = None,
order: str = "asc") -> list[ChatMessage]
async def delete_message(thread_id: str, message_id: str, *,
workspace_id: str | None = None,
authority: AuthorityContext | None = None) -> bool

Each message dict needs role and content, plus optional metadata.

decompose_thread()

Extract memories from messages that haven’t been processed yet.

async def decompose_thread(thread_id: str, *, workspace_id: str | None = None) -> DecompositionResult

Returns: DecompositionResult with thread_id, workspace_id, messages_processed, memories_created, from_index, to_index.


Context Environment Operations

All context environment methods require an active session (call set_session() or create_session() first). See the Context Environment guide.

async def context_exec(code: str, result_var: str | None = None, return_result: bool = True,
max_return_chars: int = 10000) -> dict
async def context_inspect(variable: str | None = None, preview_chars: int = 200) -> dict
async def context_load(var: str, query: str, limit: int = 50, types: list[str] | None = None,
tags: list[str] | None = None, min_relevance: float | None = None,
include_embeddings: bool = False) -> dict
async def context_inject(key: str, value: Any, parse_json: bool = False) -> dict
async def context_query(prompt: str, variables: list[str], max_context_chars: int | None = None,
result_var: str | None = None) -> dict
async def context_rlm(goal: str, memory_query: str | None = None, memory_limit: int = 100,
max_iterations: int = 10, variables: list[str] | None = None,
result_var: str | None = None, detail_level: str = "standard") -> dict
async def context_status() -> dict
async def context_checkpoint() -> None
async def context_cleanup() -> None
MethodPurpose
context_exec()Run Python code in the session sandbox. result_var stores the expression result.
context_inspect()Inspect sandbox state or one variable
context_load()Run a recall and store the results in a sandbox variable
context_inject()Put a value into the sandbox (parse_json=True parses a JSON string)
context_query()Send sandbox variables and a prompt to the server-side LLM
context_rlm()Run a Recursive Language Model loop. detail_level is "brief", "standard", or "detailed".
context_status()Sandbox status (variable count, memory usage)
context_checkpoint()Persist sandbox state
context_cleanup()Remove the sandbox

Documents

If the server returns 501 because document ingestion is not available, these methods raise EnterpriseRequiredError.

async def upload_document(file_data: bytes, filename: str, *, target_context_id: str = "_default",
chunking_strategy: str = "page", chunk_size: int = 4096,
chunk_overlap: int = 200, importance: float = 0.5,
retain_original: bool = True) -> tuple[DocumentInfo, JobInfo]
async def list_documents(*, status: str | None = None, limit: int = 50,
offset: int = 0) -> tuple[list[DocumentInfo], int]
async def get_document(document_id: str) -> DocumentInfo
async def delete_document(document_id: str, *, delete_memories: bool = False) -> None
async def reprocess_document(document_id: str, *, target_context_id: str | None = None,
chunking_strategy: str | None = None, chunk_size: int | None = None,
chunk_overlap: int | None = None,
importance: float | None = None) -> JobInfo
async def search_document_pages(query: str, *, limit: int = 10,
doc_ids: list[str] | None = None) -> PageSearchResult
async def get_document_pages(document_id: str) -> list[DocumentPage]
async def get_page_image(document_id: str, page_id: str) -> bytes # PNG
async def get_job(job_id: str) -> JobInfo
async def list_jobs(*, status: str | None = None, limit: int = 50) -> list[JobInfo]
async def cancel_job(job_id: str) -> None

chunking_strategy is "page", "semantic", or "fixed". search_document_pages() ranks pages by ColPali visual similarity. See Document Ingestion for the server side.

Datasets

async def upload_dataset(file_data: bytes, filename: str, *, name: str | None = None,
target_context_id: str = "_default", importance: float = 0.5,
sample_rows: int = 1000, detect_time_series: bool = True,
generate_summaries: bool = True) -> tuple[DatasetInfo, DatasetJobInfo]
async def list_datasets(*, status: str | None = None, limit: int = 50,
offset: int = 0) -> tuple[list[DatasetInfo], int]
async def get_dataset(dataset_id: str) -> DatasetInfo
async def delete_dataset(dataset_id: str, *, delete_memories: bool = False) -> None
async def get_dataset_memories(dataset_id: str) -> list[dict[str, Any]]
async def query_dataset_slice(dataset_id: str, *, sql: str | None = None,
columns: list[str] | None = None,
filters: list[dict[str, Any]] | None = None,
order_by: str | None = None, descending: bool = False,
limit: int = 100, offset: int = 0) -> DatasetSliceResult
async def get_dataset_job(job_id: str) -> DatasetJobInfo
async def list_dataset_jobs(*, status: str | None = None, limit: int = 50) -> list[DatasetJobInfo]
async def cancel_dataset_job(job_id: str) -> None

query_dataset_slice() runs against the dataset through DuckDB, using either structured columns/filters/order_by or a read-only sql query. See Dataset Management.


Skills (client.skills)

Manage Agent Skills bundles (a SKILL.md manifest plus files) stored in MemoryLayer. See Skills & MCP Servers.

MethodSignatureReturns
list(scope=None, name=None, tags=None, enabled=None, include_shadowed=False, workspace_id=None, authority=None)list[SkillModel]
get(skill_id, authority=None)SkillModel
get_manifest(skill_id)str (rendered SKILL.md)
get_file(skill_id, path)bytes
list_files(skill_id, authority=None)list[dict]
save(name, description, body="", files=None, scope="workspace", source_mode="server", workspace_id=None, user_id=None, authority=None, **manifest_extras)SkillModel (create or update by name)
delete(skill_id, workspace_id=None, authority=None)None
resolve(name=None, query=None, workspace_id=None, authority=None)SkillModel when resolving by name (precedence winner), or list[SkillModel] for a query (vector recall)
pull(name, out_dir: Path, workspace_id=None)Path to out_dir/{name}/
push(skill_dir: Path, scope="workspace", source_mode="server", workspace_id=None)SkillModel
materialize(target_dir: Path, scope=None, workspace_id=None)list[Path]. Pulls every visible skill; unchanged bundles are skipped based on bundle_hash.

parse_skill_folder(path) (in memorylayer.skills) parses a local skill directory with a SKILL.md manifest.

skill = await client.skills.save(
name="deploy-checklist",
description="Steps to deploy the API",
body="1. Run tests\n2. Tag release\n3. Deploy",
)
await client.skills.pull("deploy-checklist", Path(".claude/skills"))

MCP Servers (client.mcp_servers)

A registry of MCP server definitions. Names are resolved with the server’s four-tier precedence.

MethodSignatureReturns
list(transport=None, enabled=None, name=None, user_id=None, limit=100, offset=0, workspace_id=None, authority=None)list[McpServerModel]
get(server_id, authority=None)McpServerModel
create(name, transport, command=None, args=None, env=None, url=None, headers=None, description=None, metadata=None, source_mode="server", enabled=True, workspace_id=None, user_id=None, authority=None)McpServerModel
update(server_id, description=None, command=None, args=None, env=None, url=None, headers=None, metadata=None, source_mode=None, enabled=None, authority=None)McpServerModel
delete(server_id, authority=None)None
resolve(name, workspace_id=None, authority=None)McpServerModel | None
push_json(json_path: Path, scope="workspace", source_mode="server", workspace_id=None, user_id=None, authority=None)list[McpServerModel] (one per entry in a .mcp.json)
pull_json(out_path: Path, workspace_id=None, user_id=None, transport=None, enabled=None, authority=None)Path of the written .mcp.json

transport is one of "stdio", "http", "sse", or "streamable-http".

Knowledgebase (client.kb)

Generates Markdown articles from a workspace’s graph structure. If the server returns 501 for the knowledgebase, these methods raise EnterpriseRequiredError.

MethodSignatureReturns
get(workspace_id=None, *, context_id=None, authority=None)KbMetadata
list_articles(workspace_id=None, *, article_type=None, limit=100, offset=0, authority=None)list[KbArticle]
get_article(article_id, workspace_id=None, *, authority=None)KbArticle (e.g. "index", "community-3")
generate(workspace_id=None, *, regenerate=False, max_communities=None, max_god_nodes=None, include_rpg=False, context_id=None, authority=None)KbMetadata
export_vault(workspace_id=None, *, authority=None)bytes (Obsidian-compatible vault zip)
get_graph_analysis(workspace_id=None, *, context_id=None, authority=None)KbGraphAnalysis | None
get_community(community_id, workspace_id=None, *, authority=None)KbCommunity

Repository Planning Graph (client.rpg)

Client for the Repository Planning Graph (RPG) server plugin (memorylayer-server-rpg). See Repository Planning Graph. context_id defaults to "rpg".

MethodSignatureReturns
sync(nodes, edges, *, full_sync=False, source_commit=None, context_id="rpg", task_id=None)RpgSyncResult
get_subgraph(*, path=None, node_id=None, depth=3, node_types=None, relationship_types=None, context_id="rpg", max_nodes=2000)RpgSubgraph
search(query, *, node_types=None, limit=20, context_id="rpg")RpgSearchResult
get_status(context_id=None)RpgStatus
list_overlays / delete_overlay() / (context_id)RpgOverlayList / RpgOverlayDeleteResult
list_nodes(*, node_type=None, context_id="rpg", limit=5000)RpgNodeList
delete_nodes / delete_edges(node_ids, *, context_id="rpg") / (association_ids)RpgDeleteResult
get_merged_subgraph(overlay_context, *, base_context="rpg", path=None, depth=3)RpgSubgraph
get_conflicts / get_symbol_conflicts(task_id) / (task_id_a, task_id_b)RpgConflictResult / RpgSymbolConflictResult
maintenance(operation) where operation is "validate", "cleanup", "statistics", "cleanup_intents", or "recompute_counts"RpgMaintenanceResult
enrich(*, context_id="rpg", phases=None, async_mode=True)RpgEnrichmentResult

Every async RPG method also accepts authority=.


SyncMemoryLayerClient

Synchronous client for scripts and non-async code. Use it as a regular context manager.

from memorylayer import SyncMemoryLayerClient
with SyncMemoryLayerClient(
base_url="http://localhost:61001",
api_key="your-key",
workspace_id="ws_123"
) as client:
memory = client.remember("User prefers Python")
results = client.recall("coding preferences")

Its constructor is narrower than the async client’s:

SyncMemoryLayerClient(
base_url: str = "http://localhost:61001",
api_key: str | None = None,
workspace_id: str | None = None,
session_id: str | None = None,
timeout: float = 30.0,
max_retries: int = 3,
backoff_factor: float = 0.5,
)

The sync client always uses HTTP and has no default_authority, transport, or Aether options. It mirrors the async memory, association, entity, token, session, checkpoint/context-pack, workspace, thread, context-environment, document, and dataset methods without await, plus sync skills, mcp_servers, kb, and rpg namespaces. It does not provide acting_for(), for_workspace(), update_thread(), or delete_message(), and most sync methods take no authority argument. Use connect() and close() to manage the lifecycle manually.

sync_client()

Convenience context manager:

from memorylayer import sync_client
with sync_client(
base_url="http://localhost:61001",
api_key="your-key",
workspace_id="ws_123"
) as client:
memory = client.remember("Hello world")

Types

All enums are StrEnums, so you can pass either the member or its string value.

MemoryType

class MemoryType(StrEnum):
EPISODIC = "episodic" # Specific events/interactions
SEMANTIC = "semantic" # Facts, concepts, relationships
PROCEDURAL = "procedural" # How to do things
WORKING = "working" # Current task context

MemorySubtype

class MemorySubtype(StrEnum):
SOLUTION = "solution"
PROBLEM = "problem"
CODE_PATTERN = "code_pattern"
FIX = "fix"
ERROR = "error"
WORKFLOW = "workflow"
PREFERENCE = "preference"
DECISION = "decision"
DIRECTIVE = "directive"
PROFILE = "profile"
ENTITY = "entity"
EVENT = "event"
INFERENCE = "inference"

RecallMode

class RecallMode(StrEnum):
RAG = "rag" # Vector similarity search + graph traversal
LLM = "llm" # LLM-driven retrieval
HYBRID = "hybrid" # RAG first, LLM fallback

RAG is the recommended mode and the server default. LLM and HYBRID require the server’s LLM generation policy to allow query rewriting. When you need LLM-driven analysis over memories, use the Context Environment with context_rlm().

The server also defines an "agentic" mode, an iterative LLM-controlled retrieval loop provided by MemoryLayer Enterprise. The SDK enum does not include it, but you can pass mode="agentic" as a string.

SearchTolerance

class SearchTolerance(StrEnum):
LOOSE = "loose" # Fuzzy matching, broader results
MODERATE = "moderate" # Balanced precision/recall
STRICT = "strict" # Exact matching, high relevance

RelationshipType

RelationshipType provides constants for the most common relationship types:

class RelationshipType(StrEnum):
# Causal
CAUSES = "causes"; TRIGGERS = "triggers"; LEADS_TO = "leads_to"; PREVENTS = "prevents"
# Solution
SOLVES = "solves"; ADDRESSES = "addresses"; ALTERNATIVE_TO = "alternative_to"; IMPROVES = "improves"
# Context
OCCURS_IN = "occurs_in"; APPLIES_TO = "applies_to"; WORKS_WITH = "works_with"; REQUIRES = "requires"
# Learning
BUILDS_ON = "builds_on"; CONTRADICTS = "contradicts"; CONFIRMS = "confirms"; SUPERSEDES = "supersedes"
# Similarity
SIMILAR_TO = "similar_to"; VARIANT_OF = "variant_of"; RELATED_TO = "related_to"
# Workflow
FOLLOWS = "follows"; DEPENDS_ON = "depends_on"; ENABLES = "enables"; BLOCKS = "blocks"
# Quality
EFFECTIVE_FOR = "effective_for"; PREFERRED_OVER = "preferred_over"; DEPRECATED_BY = "deprecated_by"

The server’s ontology defines more types (hierarchical, temporal, reference, and others), and associate() accepts any of them as a plain string. Use get_workspace_schema() to list every relationship type available in a workspace.

RelationshipCategory

class RelationshipCategory(StrEnum):
HIERARCHICAL = "hierarchical"
CAUSAL = "causal"
TEMPORAL = "temporal"
SIMILARITY = "similarity"
LEARNING = "learning"
REFERENCE = "reference"
SOLUTION = "solution"
CONTEXT = "context"
WORKFLOW = "workflow"
QUALITY = "quality"

Constants

ConstantValueMeaning
USER_CHAT_HOME_WORKSPACE"_user_chat"Storage workspace for user-owned chat threads
MESSAGE_META_APP_WORKSPACE_KEY"app_workspace"Message metadata key holding the originating app workspace

Model Classes

All models are Pydantic BaseModels. Only the most-used fields are listed.

Memory

class Memory(BaseModel):
id: str
workspace_id: str
tenant_id: str = "_default"
context_id: str | None
user_id: str | None
session_id: str | None
content: str
content_hash: str | None
type: MemoryType
subtype: str | None
importance: float
tags: list[str]
metadata: dict[str, Any]
abstract: str | None
overview: str | None
access_count: int
last_accessed_at: datetime | None
decay_factor: float
pinned: bool
status: str # "active", ...
created_at: datetime
updated_at: datetime
archived_at: datetime | None
observer_id: str | None
subject_id: str | None
source_memory_id: str | None
# Populated on recall results
relevance_score: float | None
boosted_score: float | None
source_scope: str | None
match_signals: list[str] | None
# Populated when remember() was called with relations=
relation_write_result: EntityRelationWriteResult | None

RecallResult

class RecallResult(BaseModel):
memories: list[Memory]
total_count: int
query_tokens: int | None
search_latency_ms: int | None
mode_used: str | None
retrieval_confidence: Literal["strong", "moderate", "weak"]
confidence_reasons: list[str]
budget_summary: BudgetSummary | None # requested, used, estimator, truncated_items, omitted_items
generation_summary: GenerationSummary | None
relation_paths: list[EntityRelationPath]

Association

class Association(BaseModel):
id: str
workspace_id: str
source_id: str
target_id: str
relationship: str
strength: float
metadata: dict[str, Any]
created_at: datetime

Session and SessionCheckpoint

class Session(BaseModel):
id: str
workspace_id: str
user_id: str | None
metadata: dict[str, Any]
expires_at: datetime
created_at: datetime
class SessionCheckpoint(BaseModel):
id: str
workspace_id: str
session_id: str
raw_memory_id: str
source_kind: str
source_sequence: int | None
source_boundary: int | None
content_hash: str
byte_count: int
capture_status: str
index_status: str
enrichment_status: str
idempotency_key: str
created_at: datetime
updated_at: datetime

Workspace

class Workspace(BaseModel):
id: str
tenant_id: str
name: str
settings: dict[str, Any]
tags: list[str]
created_at: datetime
updated_at: datetime

Entity and EntityResolution

class Entity(BaseModel):
id: str
workspace_id: str
entity_type: str
canonical_name: str
normalized_name: str
aliases: list[str]
confidence: float
provenance: dict[str, Any]
representative_memory_id: str | None
status: str # "active" or "merged"
merged_into: str | None
created_at: datetime
updated_at: datetime
class EntityResolution(BaseModel):
entity: Entity
matched_via: str
score: float

EntityRelationInput

class EntityRelationInput(BaseModel):
relationship: str
source_entity_id: str | None
source_entity_name: str | None
target_entity_id: str | None
target_entity_name: str | None
confidence: float = 1.0
source_span_start: int | None
source_span_end: int | None

TokenInfo and TokenCreateResult

class TokenInfo(BaseModel):
id: str
name: str
principal_type: str = "User"
workspace_patterns: list[str]
scopes: list[str]
created_at: str
expires_at: str | None
revoked: bool
class TokenCreateResult(TokenInfo):
token: str # plaintext secret, returned once

ChatThread

class ChatThread(BaseModel):
id: str
workspace_id: str
tenant_id: str = "_default"
user_id: str | None
context_id: str = "_default"
observer_id: str | None
subject_id: str | None
title: str | None
metadata: dict[str, Any]
message_count: int
last_decomposed_at: datetime | None
last_decomposed_index: int
expires_at: datetime | None
created_at: datetime
updated_at: datetime
scope: str | None
ownership: str = "user" # "user" or "workspace"

ChatMessage

class ChatMessage(BaseModel):
id: str
thread_id: str
message_index: int
role: str
content: str | list[ChatMessageContent]
metadata: dict[str, Any]
created_at: datetime

AuthorityContext and PrincipalRef

class PrincipalRef(BaseModel):
type: str
id: str
class AuthorityContext(BaseModel):
grant_id: str
subject: PrincipalRef | None = None # None = direct authority

Exceptions

MemoryLayerError # Base exception
├── AuthenticationError # 401 - Invalid API key
├── AuthorizationError # 403 - Access denied
├── NotFoundError # 404 - Resource not found (also 501 on non-Enterprise endpoints)
├── ValidationError # 422 - Invalid request
├── RateLimitError # 429 - Rate limit exceeded
├── ServerError # 5xx - Server error
└── EnterpriseRequiredError # 501 on an Enterprise-only feature

All exceptions have these properties:

PropertyTypeDescription
messagestrError message
status_codeint | NoneHTTP status code

EnterpriseRequiredError is raised when the server returns 501 because the feature needs MemoryLayer Enterprise, the open-source (AGPL-3.0) production edition. Examples are document ingestion, dataset management, and the entity registry or knowledgebase when the server does not provide them. The error has a feature property naming the missing capability. Its status_code attribute is 404, not the 501 the server sent, so check the exception type rather than the code.

Timeouts and connection failures are raised as a plain MemoryLayerError.