JavaScript SDK
Official JavaScript/TypeScript SDK for Engram Memory
JavaScript SDK
The official JavaScript/TypeScript SDK for the Engram Memory platform.
npm: engrammemory-ai
Node: >=18.0.0
Dependencies: Zero runtime dependencies (uses native fetch)
Formats: ESM and CommonJS
Installation
npm install engrammemory-ai
yarn add engrammemory-ai
pnpm add engrammemory-ai
Quick Start
import { Engram } from 'engrammemory-ai';
const client = new Engram({ apiKey: 'pr_live_xxxxx' });
// Store a memory
const result = await client.store('User prefers dark mode and vim keybindings.');
console.log(result.id); // "mem_8f3a..."
// Search memories
const results = await client.search('What are the user\'s preferences?');
for (const memory of results.memories) {
console.log(`[${memory.score.toFixed(3)}] ${memory.content}`);
}
CommonJS:
const { Engram } = require('engrammemory-ai');
Constructor
const client = new Engram({
apiKey: 'pr_live_xxxxx',
baseUrl: 'https://api.engrammemory.ai/v1', // default
timeout: 30000, // milliseconds, default 30000
maxRetries: 3, // default 3
});
| Parameter | Type | Default | Description |
|---|---|---|---|
apiKey | string | required | Your Engram API key (pr_live_* or pr_test_*) |
baseUrl | string | https://api.engrammemory.ai/v1 | API base URL. Override for self-hosted instances. |
timeout | number | 30000 | Request timeout in milliseconds |
maxRetries | number | 3 | Number of retries on transient failures (429, 5xx) |
Methods
store
Store a memory with optional classification and metadata.
const result = await client.store(
'The deployment pipeline uses GitHub Actions with Docker.',
{
category: 'technical',
importance: 0.8,
metadata: { project: 'infra', author: 'eddy' },
collection: 'engineering-notes',
}
);
console.log(result.id); // "mem_a1b2c3..."
console.log(result.category); // "technical"
console.log(result.stored); // true
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
text | string | required | Content to store |
options.category | string | undefined | Memory category. Auto-classified if omitted. |
options.importance | number | undefined | Importance score 0.0-1.0 |
options.metadata | Record<string, unknown> | undefined | Arbitrary key-value metadata |
options.collection | string | undefined | Target collection. Uses default if omitted. |
Returns: Promise<MemoryResult>
search
Semantic search across stored memories.
const results = await client.search('deployment pipeline', {
limit: 10,
category: 'technical',
minScore: 0.7,
collection: 'engineering-notes',
});
console.log(results.total);
for (const memory of results.memories) {
console.log(`[${memory.score.toFixed(3)}] ${memory.content}`);
console.log(` Category: ${memory.category}`);
console.log(` ID: ${memory.id}`);
}
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
query | string | required | Natural language search query |
options.limit | number | 10 | Maximum results to return |
options.category | string | undefined | Filter by category |
options.minScore | number | undefined | Minimum similarity score (0.0-1.0) |
options.collection | string | undefined | Search within specific collection |
Returns: Promise<SearchResult>
recall
Alias for search. Provided for semantic convenience in agent workflows.
const results = await client.recall('What does the user prefer for editors?', {
limit: 5,
minScore: 0.6,
});
for (const memory of results.memories) {
console.log(memory.content);
}
Parameters: Same as search.
Returns: Promise<SearchResult>
forget
Delete memories by ID or by semantic query match.
// Forget by ID
const result = await client.forget({ memoryId: 'mem_a1b2c3' });
console.log(result.deleted); // 1
// Forget by query
const result2 = await client.forget({
query: 'deployment pipeline',
collection: 'engineering-notes',
});
console.log(result2.deleted);
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
options.memoryId | string | undefined | Specific memory ID to delete |
options.query | string | undefined | Delete memories matching this query |
options.collection | string | undefined | Target collection |
At least one of memoryId or query is required.
Returns: Promise<ForgetResult>
connect
Health check. Verifies API key and connectivity.
const status = await client.connect();
console.log(status.connected); // true
console.log(status.latencyMs); // 42
console.log(status.tier); // "builder"
Returns: Promise<ConnectionResult>
consolidate
Trigger memory consolidation. Merges duplicates and optimizes storage.
const result = await client.consolidate('engineering-notes');
console.log(result.merged); // 3
console.log(result.removed); // 2
console.log(result.totalAfter); // 145
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
collection | string | undefined | Collection to consolidate. All collections if omitted. |
Returns: Promise<ConsolidateResult>
embed
Generate an embedding vector without storing anything.
const result = await client.embed('The quick brown fox jumps over the lazy dog.');
console.log(result.vector.length); // 768
console.log(result.model); // "engram-embed-v1"
console.log(result.dimensions); // 768
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
text | string | required | Text to embed |
Returns: Promise<EmbedResult>
intelligence
Full pipeline in one call: embed, classify, deduplicate, compress, and store.
const result = await client.intelligence(
'User switched from VS Code to Neovim on 2026-03-15.',
{
checkDedup: true,
compress: true,
targetBits: 4,
}
);
console.log(result.memoryId); // "mem_8f3a..."
console.log(result.category); // "decision"
console.log(result.isDuplicate); // false
console.log(result.compressed); // true
console.log(result.compressionRatio); // 6.2
console.log(result.cosinePreserved); // 0.9947
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
text | string | required | Content to process |
options.checkDedup | boolean | true | Check for duplicate memories |
options.compress | boolean | true | Apply proprietary compression |
options.targetBits | number | 4 | Compression bit depth (2, 4, or 8) |
Returns: Promise<IntelligenceResult>
Types
interface MemoryResult {
id: string;
stored: boolean;
category: string;
createdAt: string;
}
interface SearchResult {
memories: Memory[];
total: number;
query: string;
}
interface Memory {
id: string;
content: string;
score: number;
category: string;
metadata: Record<string, unknown>;
createdAt: string;
}
interface EmbedResult {
vector: number[];
dimensions: number;
model: string;
}
interface IntelligenceResult {
memoryId: string;
category: string;
isDuplicate: boolean;
compressed: boolean;
compressionRatio: number;
cosinePreserved: number;
}
interface ForgetResult {
deleted: number;
}
interface ConnectionResult {
connected: boolean;
latencyMs: number;
tier: string;
}
interface ConsolidateResult {
merged: number;
removed: number;
totalAfter: number;
}
Error Handling
All errors extend EngramError.
import {
Engram,
EngramError,
AuthenticationError,
RateLimitError,
NotFoundError,
ValidationError,
} from 'engrammemory-ai';
try {
const result = await client.store('Some memory');
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Invalid or expired API key');
} else if (error instanceof RateLimitError) {
console.error(`Rate limited. Retry after ${error.retryAfter}s`);
} else if (error instanceof NotFoundError) {
console.error('Resource not found');
} else if (error instanceof ValidationError) {
console.error(`Invalid input: ${error.message}`);
} else if (error instanceof EngramError) {
console.error(`Unexpected error: ${error.message}`);
}
}
| Exception | HTTP Status | When |
|---|---|---|
AuthenticationError | 401 | Invalid or missing API key |
RateLimitError | 429 | Too many requests. Has retryAfter property. |
NotFoundError | 404 | Memory or collection not found |
ValidationError | 422 | Invalid parameters |
EngramError | Any | Base class for all Engram errors |
Multi-Agent Example
Use collection namespaces to isolate memory per agent or project.
import { Engram } from 'engrammemory-ai';
const client = new Engram({ apiKey: 'pr_live_xxxxx' });
// Agent 1: Research assistant
await client.store(
'Found 3 papers on transformer attention mechanisms.',
{ category: 'research', collection: 'agent-researcher' }
);
// Agent 2: Code assistant
await client.store(
'Refactored the auth module to use JWT tokens.',
{ category: 'engineering', collection: 'agent-coder' }
);
// Agent 3: Coordinator queries across all agents
const research = await client.search('attention mechanisms', {
collection: 'agent-researcher',
});
const code = await client.search('authentication changes', {
collection: 'agent-coder',
});
// Or search globally (no collection filter)
const everything = await client.search('recent changes', { limit: 20 });
Environment Variables
The SDK reads these environment variables as fallbacks:
| Variable | Maps to |
|---|---|
ENGRAM_API_KEY | apiKey |
ENGRAM_BASE_URL | baseUrl |
// No apiKey needed — reads from ENGRAM_API_KEY
const client = new Engram({});
Next Steps
- Python SDK — Python SDK
- API Reference — Full endpoint documentation
- MCP Server — Connect Engram to AI agents via MCP