@aivm-brain/sdk
v0.1.1
Published
Official TypeScript SDK for the AIVM Brain memory API (add, get, list, update, delete, search memories + ask).
Readme
@aivm-brain/sdk
Official TypeScript SDK for the AIVM Brain memory API — add, get, list,
update, delete, and search memories (plus ask) with simple typed methods instead of hand-written
HTTP. Zero runtime dependencies; ships dual ESM + CommonJS with type declarations.
Server-side only. An
ak_live_…agent key grants full access to your memories. Never embed it in a browser or mobile app — use the SDK from a server, function, or job.
Install
npm install @aivm-brain/sdkRequires Node.js ≥ 18 (uses the built-in global fetch).
Authentication
Create an ak_live_ agent key in the AIVM dashboard and provide it either explicitly or via the
AIVM_API_KEY environment variable (preferred — keys should not be hard-coded):
import { AivmBrain } from "@aivm-brain/sdk";
// Reads AIVM_API_KEY (and optionally AIVM_BASE_URL) from the environment.
const brain = new AivmBrain();
// …or pass it explicitly.
const brain2 = new AivmBrain({ apiKey: process.env.AIVM_API_KEY });If no key can be resolved, the constructor throws a ConfigurationError.
Client options
| Option | Default | Description |
| ------------ | --------------------------------------------------- | ------------------------------------------------------ |
| apiKey | process.env.AIVM_API_KEY | Agent API key (ak_live_…). |
| tenantId | – | Workspace id for tenant-scoped keys (x-tenant-id). |
| baseUrl | process.env.AIVM_BASE_URL → https://brain-be.dev.aivm.io | API base URL. Override for a self-hosted brain. |
| timeout | 30000 | Timeout in ms for CRUD calls (add/get/list/update/delete). |
| retrievalTimeout | 120000 | Timeout in ms for search and ask — see below. |
| maxRetries | 2 | Retry attempts for idempotent GETs. |
| fetch | global fetch | Custom fetch implementation (testing / proxies). |
Why search and ask get their own timeout
They are not lookups. Both run retrieval plus answer synthesis server-side — the brain embeds your question, retrieves, and has a model write the answer — and the backend allows itself ~120s to do it. Putting them on the 30s CRUD timeout made the SDK hang up on requests the server was still working on, which surfaced as:
{ "type": "APITimeoutError", "code": "timeout", "status": null }status: null is the tell — no HTTP response ever arrived, because the client aborted first. If
your brain is slower still, raise retrievalTimeout; CRUD stays fast either way.
Quickstart
import { AivmBrain } from "@aivm-brain/sdk";
const brain = new AivmBrain({ apiKey: process.env.AIVM_API_KEY });
// Create (or topic-upsert) a memory.
const memory = await brain.memories.add({
title: "Q3 Budget",
body: "The Q3 engineering budget is two million dollars.",
domain: "finance",
});
// Semantic search.
const { items, answer } = await brain.memories.search({ query: "budget", topK: 5 });
// Fetch, update, delete.
const one = await brain.memories.get(memory.id);
await brain.memories.update(memory.id, { body: "Updated body." });
await brain.memories.delete(memory.id);
// Grounded question answering.
const result = await brain.ask({ question: "What is the engineering budget?" });
console.log(result.answer);Methods
| Method | HTTP | Returns |
| --------------------------------------------------- | -------------------------- | ----------------------------------- |
| memories.add({ title, body, domain?, topic? }) | POST /v1/memories | Memory |
| memories.get(id) | GET /v1/memories/{id} | Memory |
| memories.list({ limit?, cursor?, domain? }) | GET /v1/memories | Page<Memory> = { items, nextCursor } |
| memories.listAll({ domain? }) | iterates list | AsyncIterableIterator<Memory> |
| memories.update(id, { title?, body?, domain? }) | PATCH /v1/memories/{id} | Memory |
| memories.delete(id) | DELETE /v1/memories/{id} | { id } |
| memories.search({ query, topK? }) | POST /v1/memories/search | { items: SearchHit[], answer } |
| ask({ question, sessionId? }) | POST /v1/ask | AskResponse |
Reusing a topic on add performs an idempotent upsert of that memory instead of creating a new
one.
Pagination
list returns one page. nextCursor is an opaque string, or null on the last page. Pass it back as
cursor to page manually, or let listAll follow it for you:
// Manual paging.
let cursor: string | undefined;
do {
const page = await brain.memories.list({ cursor, limit: 50 });
for (const m of page.items) process(m);
cursor = page.nextCursor ?? undefined;
} while (cursor);
// Or iterate everything transparently.
for await (const memory of brain.memories.listAll()) {
process(memory);
}Error handling
Every failure is an AivmError (or subclass) carrying .status (number | null), .code (string),
.requestId (string | null), and a .message.
import {
AivmError,
AuthenticationError,
NotFoundError,
RateLimitError,
ValidationError,
} from "@aivm-brain/sdk";
try {
await brain.memories.get("does-not-exist");
} catch (err) {
if (err instanceof NotFoundError) {
// 404
} else if (err instanceof AuthenticationError) {
// 401 — bad/missing key
} else if (err instanceof AivmError) {
console.error(err.code, err.status, err.requestId, err.message);
}
}| Status | code | Class |
| ------------- | ------------------- | ------------------------ |
| 400, 422 | invalid_request | ValidationError |
| 401 | unauthorized | AuthenticationError |
| 402 | payment_required | PaymentRequiredError |
| 403 | forbidden | PermissionError |
| 404 | not_found | NotFoundError |
| 409 | conflict | ConflictError |
| 413 | payload_too_large | PayloadTooLargeError |
| 429 | rate_limited | RateLimitError |
| 5xx | server_error | ServerError |
| — (network) | unreachable | APIConnectionError |
| — (timeout) | timeout | APITimeoutError |
| — (no key) | configuration | ConfigurationError |
When the server returns a validation error with multiple messages, they are joined with "; ".
Retries & timeout
Only idempotent reads (memories.get, memories.list) are auto-retried, on 429 / 5xx /
network / timeout, with jittered exponential backoff (base ~0.5s, maxRetries = 2 by default). A
Retry-After header on a 429 is honored. Writes (add / update / delete / search / ask)
are never auto-retried, so a transient failure can't double-write. Each request times out after
timeout ms (default 30s).
Tenancy
For a tenant-scoped key, pass the workspace id — it is sent as the x-tenant-id header and verified
against the key server-side. Omit it for personal keys.
const brain = new AivmBrain({ apiKey: process.env.AIVM_API_KEY, tenantId: "ws_123" });License
MIT
