Python SDK for MemoryLayer.ai - Memory infrastructure for AI agents.
pip install memorylayer-clientfrommemorylayerimportMemoryLayerClient, MemoryTypeasyncwithMemoryLayerClient(
base_url="http://localhost:61001",
api_key="your-api-key", # Optional for local developmentworkspace_id="my-workspace"
) asclient:
# Store a memorymemory=awaitclient.remember(
content="User prefers Python for backend development",
type=MemoryType.SEMANTIC,
importance=0.8,
tags=["preferences", "programming"]
)
# Search memoriesresults=awaitclient.recall(
query="what programming language does the user prefer?",
limit=5
)
formemoryinresults.memories:
print(f"{memory.content} (relevance: {memory.importance})")
# Synthesize memoriesreflection=awaitclient.reflect(
query="summarize user's technology preferences"
)
print(reflection.reflection)- 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
- Session Management - Working memory with TTL and commit
- Batch Operations - Bulk create, update, delete
- Error Handling - Comprehensive exception hierarchy
memory=awaitclient.remember(
content="User prefers FastAPI over Flask",
type=MemoryType.SEMANTIC,
subtype=MemorySubtype.PREFERENCE,
importance=0.8,
tags=["preferences", "frameworks"],
metadata={"source": "conversation"}
)frommemorylayerimportRecallMode, SearchToleranceresults=awaitclient.recall(
query="what frameworks does the user prefer?",
types=[MemoryType.SEMANTIC],
mode=RecallMode.RAG, # Active mode: vector similarity + graph traversallimit=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.reflection=awaitclient.reflect(
query="summarize everything about the user's development workflow",
detail_level="standard", # "brief", "standard", or "detailed"include_sources=True
)
print(reflection.reflection)frommemorylayerimportRelationshipTypeassociation=awaitclient.associate(
source_id="mem_problem_123",
target_id="mem_solution_456",
relationship=RelationshipType.SOLVES,
strength=0.9
)# Reduce memory importance over timedecayed=awaitclient.decay("mem_123", decay_rate=0.1)# Get memory origin and association chaintrace=awaitclient.trace_memory("mem_123")
print(trace["chain"])# Perform multiple operations in one requestresults=awaitclient.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']}")Sessions provide working memory with TTL that can be committed to long-term storage.
# Create session (auto-creates workspace if needed)session=awaitclient.create_session(
ttl_seconds=3600,
workspace_id="my-workspace"
)
# Store working memoryawaitclient.set_context(
session.id,
"current_task",
{"description": "Debugging auth", "file": "auth.py"}
)
# Retrieve working memorycontext=awaitclient.get_context(session.id, ["current_task"])
# Extend session TTLawaitclient.touch_session(session.id)
# Commit working memory to long-term storageresult=awaitclient.commit_session(
session.id,
min_importance=0.5,
deduplicate=True
)
print(f"Created {result['memories_created']} memories")
# Delete sessionawaitclient.delete_session(session.id)briefing=awaitclient.get_briefing(lookback_minutes=1440)
print(briefing.recent_activity)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.
# Set active sessionclient.set_session(session.id)
# Execute code in sandboxawaitclient.context_exec("import pandas as pd")
awaitclient.context_exec("data = [1, 2, 3, 4, 5]")
# Execute and get resultresult=awaitclient.context_exec("sum(data)")
print(result["result"]) # 15# Load memories as a variableawaitclient.context_load(
var="preferences",
query="user preferences",
limit=20,
min_relevance=0.7
)
# Inspect loaded datastate=awaitclient.context_inspect("preferences")
print(state["type"], state["preview"])# Ask LLM to analyze sandbox variablesresult=awaitclient.context_query(
prompt="Summarize the user's preferences and find patterns",
variables=["preferences"]
)
print(result["response"])# Run autonomous reasoning loopresult=awaitclient.context_rlm(
goal="Analyze coding preferences and identify contradictions",
memory_query="coding preferences",
max_iterations=10,
detail_level="detailed"
)
print(result["result"])# Inject data into sandboxawaitclient.context_inject(
key="config",
value={"debug": True, "max_retries": 3}
)# Check sandbox statusstatus=awaitclient.context_status()
print(f"Variables: {status['variable_count']}")
# Checkpoint state (for enterprise persistence)awaitclient.context_checkpoint()
# Clean up sandboxawaitclient.context_cleanup()# Create workspaceworkspace=awaitclient.create_workspace("my-project")
# Get workspaceworkspace=awaitclient.get_workspace("ws_123")
# Update workspaceworkspace=awaitclient.update_workspace(
"ws_123",
name="New Name",
settings={"key": "value"}
)
# Get workspace schema (relationship types, memory subtypes)schema=awaitclient.get_workspace_schema("ws_123")
print(schema["relationship_types"])- Episodic - Specific events/interactions
- Semantic - Facts, concepts, relationships
- Procedural - How to do things
- Working - Current task context (session-scoped)
- 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
Link memories with typed relationships organized into 11 categories. The SDK supports 60+ relationship types:
frommemorylayerimportRelationshipType# Causal (4 types)RelationshipType.CAUSESRelationshipType.TRIGGERSRelationshipType.LEADS_TORelationshipType.PREVENTS# Solution (4 types)RelationshipType.SOLVESRelationshipType.ADDRESSESRelationshipType.ALTERNATIVE_TORelationshipType.IMPROVES# Learning (4 types)RelationshipType.BUILDS_ONRelationshipType.CONTRADICTSRelationshipType.CONFIRMSRelationshipType.SUPERSEDES# Similarity (3 types)RelationshipType.SIMILAR_TORelationshipType.VARIANT_OFRelationshipType.RELATED_TO# Workflow (4 types)RelationshipType.FOLLOWSRelationshipType.DEPENDS_ONRelationshipType.ENABLESRelationshipType.BLOCKS# Quality (3 types)RelationshipType.EFFECTIVE_FORRelationshipType.PREFERRED_OVERRelationshipType.DEPRECATED_BY# Context (4 types)RelationshipType.OCCURS_INRelationshipType.APPLIES_TORelationshipType.WORKS_WITHRelationshipType.REQUIRES# ... and more categories (11 total)frommemorylayerimport (
MemoryLayerError,
AuthenticationError,
NotFoundError,
ValidationError,
RateLimitError,
ServerError
)
try:
memory=awaitclient.get_memory("mem_123")
exceptNotFoundError:
print("Memory not found")
exceptAuthenticationError:
print("Invalid API key")
exceptValidationErrorase:
print(f"Validation error: {e}")
exceptRateLimitError:
print("Rate limit exceeded")
exceptServerErrorase:
print(f"Server error: {e.status_code}")
exceptMemoryLayerErrorase:
print(f"MemoryLayer error: {e}")client=MemoryLayerClient(
base_url="http://localhost:61001", # Defaultapi_key="your-api-key", # Optional for local devworkspace_id="my-workspace", # Default workspacesession_id="sess_123", # Optional active sessiontimeout=30.0# Request timeout in seconds
)pip install -e ".[dev]"pytestmypy src/memorylayerruff check src/memorylayer
ruff format src/memorylayerApache 2.0 License -- see LICENSE for details.