JavaScript SDK
beginnerComplete reference for the @engramma/sdk package — TypeScript-first, browser and Node.js support, error handling, interceptors, and retry.
Installation
npm install @engramma/sdkRequires Node.js 18+ or any modern browser with fetch support. Full TypeScript types included.
Initialization
import { Engramma } from '@engramma/sdk';
const client = new Engramma({
apiKey: process.env.ENGRAMMA_API_KEY
});| Parameter | Type | Default | Description |
|---|---|---|---|
apiKey | string | — | Your API key (sent as X-API-Key header) |
baseUrl | string | https://api.engramma-memory.com | API base URL |
timeout | number | 30000 | Request timeout in milliseconds |
maxRetries | number | 3 | Automatic retries on 5xx and 429 |
fetch | typeof fetch? | globalThis.fetch | Custom fetch implementation |
Text operations
store
Stores a text pattern in memory.
const result = await client.text.store(
'The deployment window is Tuesday 2-4pm UTC',
{ category: 'ops', priority: 'high' }
);
console.log(result.pattern_id); // 'pat_7f3a2b...'
console.log(result.embedding_dim); // 384
console.log(result.patterns_used); // 42
console.log(result.patterns_limit); // 10000| Parameter | Type | Required | Description |
|---|---|---|---|
text | string | Yes | The content to store |
metadata | Record<string, unknown> | No | Arbitrary key-value metadata |
Response:
| Field | Type | Description |
|---|---|---|
success | boolean | Whether the store succeeded |
pattern_id | string | Unique pattern identifier (pat_...) |
embedding_dim | number | Embedding dimensionality (384) |
patterns_used | number | Current pattern count |
patterns_limit | number | Plan pattern limit |
batchStore
Store up to 50 items in a single request.
const results = await client.text.batchStore([
{ text: 'Alice joined the team on Jan 5' },
{ text: 'Project deadline is March 15', metadata: { dept: 'engineering' } },
{ text: 'Budget approved for Q2', metadata: { dept: 'finance' } }
]);
console.log(results);| Parameter | Type | Required | Description |
|---|---|---|---|
items | Array<{text: string, metadata?: Record<string, unknown>}> | Yes | Up to 50 items to store |
retrieve
Semantic search over stored patterns.
const response = await client.text.retrieve('When can we deploy?', 5);
console.log(`Latency: ${response.latency_ms}ms`);
for (const r of response.results) {
console.log(`${r.text} (similarity: ${r.similarity}, id: ${r.pattern_id})`);
console.log('Metadata:', r.metadata);
}| Parameter | Type | Required | Description |
|---|---|---|---|
query | string | Yes | Natural-language query |
topK | number | No | Max results (default: 5) |
Response:
| Field | Type | Description |
|---|---|---|
results | Array | Matching patterns |
results[].text | string | Stored text |
results[].metadata | object | Associated metadata |
results[].similarity | number | Cosine similarity score |
results[].pattern_id | string | Pattern identifier |
latency_ms | number | Server-side latency |
recall
Active Inference retrieval — the system actively refines what to retrieve based on prediction errors.
const response = await client.text.recall('What happened before the outage?', 10);
for (const r of response.results) {
console.log(`${r.text} (similarity: ${r.similarity})`);
}| Parameter | Type | Required | Description |
|---|---|---|---|
query | string | Yes | Natural-language query |
topK | number | No | Max results (default: 5) |
explain
Get a natural-language explanation of how a query would be resolved.
const explanation = await client.text.explain('When can we deploy?', 'en');
console.log(explanation.explanation);
console.log(explanation.method); // e.g. 'cosine_similarity'
console.log(explanation.confidence); // 0.92| Parameter | Type | Required | Description |
|---|---|---|---|
query | string | Yes | The query to explain |
lang | string | No | Language: 'en' or 'fr' (default: 'en') |
Response:
| Field | Type | Description |
|---|---|---|
explanation | string | Human-readable explanation |
method | string | Retrieval method used |
confidence | number | Confidence score |
forget
Delete patterns matching a query and/or category above a similarity threshold.
const result = await client.text.forget(
'deployment window',
'ops',
0.85
);
console.log(result);| Parameter | Type | Required | Description |
|---|---|---|---|
query | string | Yes | Query to match patterns for deletion |
category | string | No | Filter by category metadata |
threshold | number | No | Minimum similarity to delete (default: 0.85) |
stats
Get statistics about the current memory store.
const stats = await client.text.stats();
console.log(`Total patterns: ${stats.total_patterns}`);
console.log(`Embedding dim: ${stats.embedding_dim}`);
console.log(`Storage: ${stats.storage_bytes} bytes`);Response:
| Field | Type | Description |
|---|---|---|
total_patterns | number | Number of stored patterns |
embedding_dim | number | Embedding dimensionality |
storage_bytes | number | Total storage used in bytes |
embed
Get the raw embedding vector for a text input.
const embedding = await client.text.embed('deployment window');
console.log(`Dimensions: ${embedding.length}`); // 384| Parameter | Type | Required | Description |
|---|---|---|---|
text | string | Yes | Text to embed |
Consolidation
Memory consolidation mimics biological sleep-based memory optimization.
sleep
Trigger a consolidation cycle.
const result = await client.consolidation.sleep('full');
console.log(result);
// Light consolidation (faster, less aggressive)
const light = await client.consolidation.sleep('light');| Parameter | Type | Required | Description |
|---|---|---|---|
mode | string | Yes | 'full' or 'light' |
status
Check the current consolidation status.
const status = await client.consolidation.status();
console.log(status);Regime
current
Get the current memory regime (encoding mode the system is operating in).
const regime = await client.regime.current();
console.log(regime);Causal operations
Explore causal relationships between stored patterns.
strength
Measure causal strength between two texts.
const result = await client.causal.strength(
'Deployment failed',
'Alert triggered'
);
console.log(result);| Parameter | Type | Required | Description |
|---|---|---|---|
textA | string | Yes | Source text |
textB | string | Yes | Target text |
neighbors
Find causally connected patterns.
const neighbors = await client.causal.neighbors(
'Server CPU spike',
'forward', // 'forward' | 'backward' | 'both'
0.5 // minimum causal strength
);
for (const n of neighbors) {
console.log(n);
}| Parameter | Type | Required | Description |
|---|---|---|---|
text | string | Yes | The anchor text |
direction | string | No | 'forward', 'backward', or 'both' |
minStrength | number | No | Minimum causal strength threshold |
TypeScript types
All methods return fully typed responses. Key types are exported for use in your application:
import type {
StoreResult,
RetrieveResponse,
RetrieveResult,
ExplainResult,
TextStats,
EngrammaConfig
} from '@engramma/sdk';
// StoreResult
interface StoreResult {
success: boolean;
pattern_id: string;
embedding_dim: number;
patterns_used: number;
patterns_limit: number;
}
// RetrieveResponse
interface RetrieveResponse {
results: RetrieveResult[];
latency_ms: number;
}
interface RetrieveResult {
text: string;
metadata: Record<string, unknown>;
similarity: number;
pattern_id: string;
}
// ExplainResult
interface ExplainResult {
explanation: string;
method: string;
confidence: number;
}
// TextStats
interface TextStats {
total_patterns: number;
embedding_dim: number;
storage_bytes: number;
}
// Generic metadata support
interface MyMeta { category: string; priority: string }
const response = await client.text.retrieve('test', 5);
const first = response.results[0];
console.log(first.similarity); // numberError handling
The SDK throws typed errors for all failure cases:
import {
EngrammaError, // Base error class
AuthenticationError, // 401
PermissionError, // 403
NotFoundError, // 404
ValidationError, // 422
RateLimitError, // 429
ServerError // 5xx
} from '@engramma/sdk';
try {
const response = await client.text.retrieve('test');
} catch (error) {
if (error instanceof RateLimitError) {
console.log(`Rate limited. Retry after ${error.retryAfter}s`);
} else if (error instanceof AuthenticationError) {
console.log('Invalid API key');
} else if (error instanceof ValidationError) {
console.log(`Validation failed: ${error.message}`);
} else if (error instanceof EngrammaError) {
console.log(`Error ${error.statusCode}: ${error.message}`);
}
}| Error Class | HTTP Status | When |
|---|---|---|
AuthenticationError | 401 | Invalid or missing X-API-Key header |
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 |
Interceptors
Add request/response interceptors for logging, metrics, or custom headers:
const client = new Engramma({
apiKey: process.env.ENGRAMMA_API_KEY
});
// Request interceptor
client.interceptors.request.use((config) => {
console.log(`[${config.method}] ${config.url}`);
config.headers['X-Request-Id'] = crypto.randomUUID();
return config;
});
// Response interceptor
client.interceptors.response.use(
(response) => {
console.log(`Response: ${response.status} in ${response.duration}ms`);
return response;
},
(error) => {
console.error(`Failed: ${error.message}`);
throw error;
}
);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:
const client = new Engramma({
apiKey: 'nx_live_...',
maxRetries: 5, // default: 3
retryBackoff: 2.0, // backoff multiplier
retryMaxWait: 30000 // max wait between retries (ms)
});Browser vs Node.js
The SDK works in both environments with zero configuration:
| Feature | Node.js | Browser |
|---|---|---|
fetch | Native (18+) or polyfill | Native |
| Streaming | Yes (ReadableStream) | Yes |
| Environment variables | process.env | Build-time injection |
Never expose your API key in client-side browser code. Use a backend proxy or edge function to forward requests.
Next steps
- Python SDK — Async-native Python client
- API Reference Overview — Full endpoint documentation