Python SDK
beginnerComplete reference for the engramma-cloud Python package — installation, initialization, all methods, async support, error handling, typing, and retry policy.
Installation
pip install engramma-cloudRequires Python 3.9+.
Initialization
import os
from engramma_cloud import EngrammaClient
client = EngrammaClient(api_key=os.environ['ENGRAMMA_API_KEY'])| Parameter | Type | Default | Description |
|---|---|---|---|
api_key | str | — | Your API key (nx_live_ or nx_test_ prefix) |
base_url | str | https://api.engramma-memory.com | API base URL |
timeout | int | 30 | Request timeout in seconds |
max_retries | int | 3 | Automatic retries on 5xx and 429 |
org_id | str | None | None | Default 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| Parameter | Type | Required | Description |
|---|---|---|---|
text | str | Yes | The content to store |
metadata | dict | No | Key-value metadata |
importance | float | No | Override importance (0.0–1.0) |
context | str | No | Additional 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})')| Parameter | Type | Required | Description |
|---|---|---|---|
query | str | Yes | Natural-language question |
top_k | int | No | Max results (default: 5) |
min_confidence | float | No | Minimum confidence threshold |
pathway | str | No | Force pathway: auto, exact, energy, attention |
metadata_filter | dict | No | Filter 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
search
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 / link / timeline
# 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())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}')| Exception | HTTP Status | When |
|---|---|---|
AuthenticationError | 401 | Invalid or expired API key |
PermissionError | 403 | Key lacks required scope |
NotFoundError | 404 | Resource does not exist |
ValidationError | 422 | Invalid request parameters |
RateLimitError | 429 | Too many requests |
ServerError | 5xx | Internal 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:
| Condition | Retried | Backoff |
|---|---|---|
| 429 (Rate Limit) | Yes | Uses Retry-After header |
| 500, 502, 503, 504 | Yes | Exponential: 1s, 2s, 4s |
| Network timeout | Yes | Exponential: 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
- JavaScript SDK — TypeScript-first client for browser and Node.js
- Go SDK — Struct-based client with context propagation
- API Reference Overview — Full endpoint documentation
- Your First Memory — Quick start tutorial