Skip to content

Python SDK

beginner

Complete reference for the engramma-cloud Python package — installation, initialization, all methods, async support, error handling, typing, and retry policy.

Installation

pip install engramma-cloud

Requires Python 3.9+.


Initialization

import os
from engramma_cloud import EngrammaClient

client = EngrammaClient(api_key=os.environ['ENGRAMMA_API_KEY'])
ParameterTypeDefaultDescription
api_keystrYour API key (nx_live_ or nx_test_ prefix)
base_urlstrhttps://api.engramma-memory.comAPI base URL
timeoutint30Request timeout in seconds
max_retriesint3Automatic retries on 5xx and 429
org_idstr | NoneNoneDefault organization for all requests

Memory operations

store

Store a single memory pattern.

result = client.store(
    text='The deployment window is Tuesday 2-4pm UTC',
    metadata={'category': 'ops', 'priority': 'high'},
    importance=0.9
)
print(result.pattern_id)  # pat_7f3a2b
print(result.confidence)  # 0.93
ParameterTypeRequiredDescription
textstrYesThe content to store
metadatadictNoKey-value metadata
importancefloatNoOverride importance (0.0–1.0)
contextstrNoAdditional context for encoding

batch_store

Store multiple memories in a single request.

results = client.batch_store([
    {'text': 'Alice joined the team on Jan 5'},
    {'text': 'Project deadline is March 15', 'importance': 0.95},
    {'text': 'Budget approved for Q2', 'metadata': {'dept': 'finance'}}
])
print(f'Stored {results.stored} patterns')

retrieve

Retrieve memories matching a natural-language query.

results = client.retrieve(
    query='When can we deploy?',
    top_k=5,
    min_confidence=0.5,
    pathway='auto'
)
for r in results:
    print(f'{r.text} (confidence: {r.confidence}, pathway: {r.pathway})')
ParameterTypeRequiredDescription
querystrYesNatural-language question
top_kintNoMax results (default: 5)
min_confidencefloatNoMinimum confidence threshold
pathwaystrNoForce pathway: auto, exact, energy, attention
metadata_filterdictNoFilter by metadata fields

recall

Context-aware recall with temporal and causal weighting.

results = client.recall(
    query='What happened before the outage?',
    temporal_weight=0.8,
    causal_weight=0.7,
    limit=10
)
for r in results:
    print(f'{r.text} (relevance: {r.relevance_score})')

explain

Get a human-readable explanation of why a result was returned.

explanation = client.explain(
    query='When can we deploy?',
    level='detailed'  # 'brief', 'detailed', or 'debug'
)
print(explanation.summary)
print(explanation.pathway_scores)
print(explanation.reasoning_chain)

forget

Remove a specific memory pattern.

client.forget(pattern_id='pat_7f3a2b')
# or soft-delete (can be recovered within 30 days)
client.forget(pattern_id='pat_7f3a2b', soft=True)

Text operations

Full-text search with filters and sorting.

results = client.text.search(
    query='deployment',
    filters={'category': 'ops'},
    sort='relevance',
    limit=20
)

summarize

Generate a summary of memories matching a topic.

summary = client.text.summarize(
    topic='Q1 project updates',
    max_length=200
)
print(summary.text)
print(f'Based on {summary.source_count} memories')

compare

Compare two memories for similarity and differences.

comparison = client.text.compare(
    pattern_id_a='pat_abc123',
    pattern_id_b='pat_def456'
)
print(f'Similarity: {comparison.similarity}')
print(f'Differences: {comparison.differences}')
# Tag memories
client.text.tag(pattern_id='pat_abc123', tags=['important', 'ops'])

# Create causal link
client.text.link(
    source_id='pat_abc123',
    target_id='pat_def456',
    relation='caused_by'
)

# Get timeline
timeline = client.text.timeline(
    topic='deployment',
    from_date='2026-01-01',
    to_date='2026-01-31'
)

Engine operations

consolidation

# Preview what consolidation would do
preview = client.engine.consolidation.preview()
print(f'Would merge: {preview.merge_candidates}')
print(f'Would prune: {preview.prune_candidates}')

# Trigger consolidation
result = client.engine.consolidation.merge()
print(f'Merged: {result.merged}, Pruned: {result.pruned}')

diagnostics

# Prefetch for faster retrieval
client.engine.diagnostics.prefetch(queries=['deployment', 'budget'])

# Warmup cache
client.engine.diagnostics.warmup()

# Get memory space structure
structure = client.engine.diagnostics.structure()
print(f'Total patterns: {structure.total_patterns}')

Organization & billing

# List organizations
orgs = client.organizations.list()

# Usage summary
usage = client.usage.summary()
print(f'Patterns: {usage.patterns.used}/{usage.patterns.limit}')

# Notifications
notifications = client.notifications.list(unread_only=True)
print(f'Unread: {notifications.unread_count}')

GDPR

# List consents
consents = client.gdpr.consents()

# Request data export
export_req = client.gdpr.export(format='json')
print(f'Export ready in ~{export_req.estimated_time_minutes} min')

# Request erasure (irreversible after 7 days)
client.gdpr.erasure(confirm=True, reason='Account closure')

Async support

All methods have async equivalents via AsyncEngrammaClient:

import asyncio
from engramma_cloud import AsyncEngrammaClient

async def main():
    client = AsyncEngrammaClient(api_key='nx_live_...')

    # All methods are awaitable
    result = await client.store('Async memory storage works')
    results = await client.retrieve('What was stored?')

    # Concurrent operations
    stores = await asyncio.gather(
        client.store('Fact A'),
        client.store('Fact B'),
        client.store('Fact C')
    )
    print(f'Stored {len(stores)} patterns concurrently')

    await client.close()

asyncio.run(main())
Tip

Always call await client.close() when done, or use the async context manager: async with AsyncEngrammaClient(...) as client:


Error handling

The SDK raises typed exceptions for all error cases:

from engramma_cloud.exceptions import (
    EngrammaError,        # Base exception
    AuthenticationError,  # 401 — invalid or expired key
    PermissionError,      # 403 — insufficient scope
    NotFoundError,        # 404 — resource not found
    ValidationError,      # 422 — invalid parameters
    RateLimitError,       # 429 — rate limit exceeded
    ServerError           # 5xx — server-side error
)

try:
    result = client.retrieve(query='test')
except RateLimitError as e:
    print(f'Rate limited. Retry after {e.retry_after}s')
except AuthenticationError:
    print('Invalid API key')
except EngrammaError as e:
    print(f'Error {e.status_code}: {e.message}')
ExceptionHTTP StatusWhen
AuthenticationError401Invalid or expired API key
PermissionError403Key lacks required scope
NotFoundError404Resource does not exist
ValidationError422Invalid request parameters
RateLimitError429Too many requests
ServerError5xxInternal server error

Typing

The SDK is fully typed with Pydantic models. All responses return typed objects with IDE autocompletion:

from engramma_cloud.types import (
    StoreResult,
    RetrieveResult,
    RecallResult,
    Explanation,
    UsageSummary,
    ConsentRecord
)

# Type hints work everywhere
result: StoreResult = client.store('typed result')
results: list[RetrieveResult] = client.retrieve('query')

# Access typed fields
result.pattern_id   # str
result.confidence   # float
result.pathway      # Literal['exact', 'energy', 'attention']

Retry policy

The SDK automatically retries failed requests with exponential backoff:

ConditionRetriedBackoff
429 (Rate Limit)YesUses Retry-After header
500, 502, 503, 504YesExponential: 1s, 2s, 4s
Network timeoutYesExponential: 1s, 2s, 4s
4xx (other)No

Configure retry behavior:

client = EngrammaClient(
    api_key='nx_live_...',
    max_retries=5,          # default: 3
    retry_backoff=2.0,      # backoff multiplier (default: 2.0)
    retry_max_wait=30       # max wait between retries in seconds
)

Logging

Enable debug logging to see requests and responses:

import logging
logging.basicConfig(level=logging.DEBUG)

# Or enable only for the SDK
logging.getLogger('engramma_cloud').setLevel(logging.DEBUG)

Next steps