Docs
Contents

Memory Management

Examples by language for memory writes, retrieval, record management and batch forgetting, import/export, profile and distillation, and skills/experience/context; see memory for concepts, parameters, and consistency semantics.

Run the Complete Write-to-Delete Flow Once

First follow Prerequisites to create a project, enable Memory, install the exact SDK version, and configure environment variables. The following is the complete memory-demo.mjs; execute it only in a trusted backend; the printed demo content should not be replaced with real sensitive content and then written directly to production logs.

import assert from 'node:assert/strict';
import { Client, Memory } from 'agentbase-node-sdk';

const required = [
  'APPBASE_ENDPOINT', 'APPBASE_PROJECT_ID', 'APPBASE_API_KEY',
  'APPBASE_USER_ID', 'MEMORY_OPERATION_ID'
];
for (const name of required) {
  if (!process.env[name]) throw new Error(`请先设置环境变量 ${name}`);
}
const endpoint = process.env.APPBASE_ENDPOINT.replace(/\/$/, '');
assert.ok(endpoint.endsWith('/v1'), 'SDK endpoint 必须包含 /v1');
const userId = process.env.APPBASE_USER_ID;
const originalContent = `用户喜欢拿铁咖啡。(SDK 演示 ${process.env.MEMORY_OPERATION_ID})`;
const updatedContent = `用户现在喜欢美式咖啡。(SDK 演示 ${process.env.MEMORY_OPERATION_ID})`;
const client = new Client()
  .setEndpoint(endpoint)
  .setProject(process.env.APPBASE_PROJECT_ID)
  .setKey(process.env.APPBASE_API_KEY);
const memory = new Memory(client);

// 1. Save a new fact as-is, avoiding treating async acceptance as a completed write.
client.addHeader('Idempotency-Key', process.env.MEMORY_OPERATION_ID);
const created = await memory.create({
  userId, scope: 'user', memoryType: 'preference', recordKind: 'fact',
  content: originalContent, infer: false, async: false
});
assert.equal(created.status, 'completed');
const memoryId = created.memory?.memoryId;
assert.equal(typeof memoryId, 'string');
console.log('新建记忆 ID:', memoryId);

// 2. Read back precisely by ID; updates must use the version read here.
const current = await memory.get({ memoryId });
assert.equal(current.memory.content, originalContent);

// 3. Open the user's memory list; pass nextCursor back unchanged when paginating.
const listing = await memory.list({ userId, limit: 20 });
console.log('列表条数:', listing.memories.length);

// 4. Find relevant memories with natural language; results may be empty if the projection is not yet ready.
const hits = await memory.search({
  query: '用户喜欢喝什么咖啡?', userId, scope: 'user', limit: 5
});
for (const item of hits.items) {
  console.log('检索:', item.memory.memoryId, item.memory.content);
}
console.log('检索降级:', hits.degraded);

// 5. Retrieve within budget; the app can add context to its own chat model requests.
const recalled = await memory.recallKnowledge({
  query: '给用户推荐一杯咖啡', scope: 'user', userId,
  kinds: ['memory', 'profile', 'skill', 'experience'],
  limit: 5, tokenBudget: 1000
});
console.log('召回上下文:', recalled.context);
console.log('召回降级:', recalled.degraded);

// 6. User corrects a preference; concurrent conflicts throw an error—do not overwrite with an old version.
client.addHeader('Idempotency-Key', `${process.env.MEMORY_OPERATION_ID}-update`);
const updated = await memory.update({
  memoryId, version: current.memory.version,
  content: updatedContent
});
assert.ok(updated.memory.version > current.memory.version);

// 7. Proactively delete the records created by this script; it does not perform user-scoped bulk deletes.
client.addHeader('Idempotency-Key', `${process.env.MEMORY_OPERATION_ID}-delete`);
const forgotten = await memory.delete({
  memoryId, reason: 'demo_finished', source: 'sdk_demo'
});
assert.equal(forgotten.status, 'forgotten');
console.log('完成:已创建、查询、更新并遗忘本次演示记忆。');

The last line “Done” means that this run's direct write, exact read-back, version update, and active deletion all succeeded; it does not mean every model retrieval route is ready. Active deletion clears memory and retrieval data, but sources and audit records may still be retained. If a failure occurs midway, use the printed memoryId to delete this demo's records in the Console. When putting the application into production, bind these steps to real user actions individually; do not treat repeatedly running the entire demo script as a retry mechanism.

Use a new MEMORY_OPERATION_ID for each new demo run; include the marker in the content to avoid writing the same content that was deleted last time. If a real business genuinely needs to re-learn the same content, it must explicitly use reRemember=true and a new idempotency key; this creates new evidence and does not restore the original record.

Intelligent Extraction from Multi-Turn Conversation

Create a new memory-async.mjs, copy the initialization part from the complete example (from import to const memory = new Memory(client)), then append the code below, excluding the create-to-delete flow above. Before running, set a new MEMORY_ASYNC_OPERATION_ID as the idempotency key for this extraction. Unlike the deterministic direct write above, this example uses the model and retains the extracted memories.

export MEMORY_ASYNC_OPERATION_ID="$(node -p 'require("node:crypto").randomUUID()')"
node memory-async.mjs
if (!process.env.MEMORY_ASYNC_OPERATION_ID) {
  throw new Error('请先设置 MEMORY_ASYNC_OPERATION_ID,标识本次提取。');
}
client.addHeader('Idempotency-Key', process.env.MEMORY_ASYNC_OPERATION_ID);
const accepted = await memory.create({
  userId, scope: 'user', memoryType: 'long_term', recordKind: 'conversation',
  sessionId: 'coffee-session-001',
  messages: [{ role: 'user', content: '我最近开始喝不加糖的美式咖啡。' }],
  infer: true, async: true
});
assert.equal(typeof accepted.jobId, 'string');
console.log('异步写入任务 ID:', accepted.jobId);
let job;
for (let attempt = 0; attempt < 30; attempt += 1) {
  job = await memory.getJob({ jobId: accepted.jobId });
  if (job.status === 'succeeded' || job.status === 'failed') break;
  await new Promise(resolve => setTimeout(resolve, 2000));
}
if (job.status === 'queued' || job.status === 'running') {
  throw new Error(`仍在处理,请保留任务 ${accepted.jobId},稍后继续 getJob,不要重新创建。`);
}
console.log('业务状态:', job.result?.status, '逐项结果:', job.result?.actions ?? []);
assert.equal(job.status, 'succeeded', job.reason ?? job.errorCode);
assert.equal(job.result?.status, 'completed');

After the task scheduling succeeds, still check result.status; when partial_failed, handle item by item and do not claim everything is complete. actions may contain ADD, UPDATE, DELETE, NONE, or be empty. Reuse the sessionId across turns of the same conversation; use a new ID for a new conversation, and first wait for the dependent previous-turn task to complete. The private scope does not load historical messages.

job.errorCode, result.errorCode, actions[].errorCode, and fallback.errorCode are all optional strings, e.g. LLM_TIMEOUT; they are not nested error objects. reason is also an optional string. Error information may appear in retried tasks or controlled fallback results; decide follow-up handling by combining task status, result.status, retryable, and per-item results.

A sample business result with partial failures is shown below. Successful actions and failed actions may coexist; do not resubmit the entire input as-is as a new operation; first verify which actions have taken effect, then handle the failed items according to application policy.

{
  "status": "partial_failed",
  "mode": "inferred",
  "actions": [
    { "index": 0, "action": "ADD", "status": "completed", "memoryId": "mem-example" },
    { "index": 1, "action": "NONE", "status": "failed", "errorCode": "VALIDATION_FAILED", "reason": "动作参数无效" }
  ]
}

Below are standalone operation cards for each language, reusing that language's Client initialization; do not concatenate them sequentially into one script. Use the Node.js example in this section as the entry point for the complete flow; keep the same idempotency key when retrying a write, and use a new key for a different write.

Examples by language

Write

create supports an optional sessionId (at most 128 UTF-8 bytes; in the Node SDK its positional parameter order comes after runId): when infer=true and scope is user / group / project, the service loads the bounded history of the same session (the most recent ≤12 earlier source turns, within a budget of about 4096 tokens) to assist coreference resolution; private / strict_private do not supplement historical messages, and runId does not fall back to sessionId. See API reference for message limits and failure handling.

import { Client, Memory, MemoryScope } from 'agentbase-node-sdk';

const client = new Client()
    .setEndpoint(process.env.APPBASE_ENDPOINT!)   // Must include /v1
    .setProject(process.env.APPBASE_PROJECT_ID!)
    .setKey(process.env.APPBASE_API_KEY!);        // memories.write minimal scope
const memory = new Memory(client);

await memory.create({
    messages: [{ role: 'user', content: '我习惯每天早上十一点查看早餐店经营简报' }],
    userId: 'user-123',
    scope: MemoryScope.User,
    memoryType: 'conversation',
    recordKind: 'conversation',
    infer: true            // Extract facts from the conversation and deduplicate them; to write known facts directly use false
});
// infer=true queues asynchronously by default; for batch combined operations see the batch endpoint on the REST tab

Retrieval and Recall

search retrieves by record (supporting five-way hybrid retrieval hybrid|vector|keyword|graph|profile, model-generated sparse vectors retrieval.sparse: true|false|"auto", and retrieval.strategy: "progressive" hierarchical progressive recall L3→L0); recallKnowledge returns memory, profile, experience, and skill context that can be directly assembled into a Prompt, within a unified token budget.

// 1. Five-way hybrid retrieval + model-generated sparse vectors (sparse: "auto") + progressive layered retrieval (strategy: "progressive", L3 overview -> L2 context -> L1 facts -> L0 evidence)
const hits = await memory.search({
    query: '早餐店经营简报',
    searchMode: 'hybrid',
    retrieval: {
        sparse: 'auto',
        strategy: 'progressive',
        entryLevel: 'auto',
        maxDepth: 2,
        tokenBudget: 1200,
        deadlineMs: 450,
        expansionToken: '',         // When expanding the next level of L2/L1/L0 nodes, pass the expansionToken returned by the previous round
    },
    userId: 'user-123',
    limit: 10,
    memoryType: 'long_term',        // Time decay layers: working / short_term / long_term
    recordKind: 'fact'
});

// 2. Unified Token budget retrieval (joint retrieval of memory + profile + skill + experience, returning context with injectionId)
const context = await memory.recallKnowledge({
    query: '用户每天什么时候查看经营简报?',
    scope: 'user',
    userId: 'user-123',
    sessionId: 'session-123',       // Stably reuses the same ID within a session (associated with the last 12 turns of conversation)
    kinds: ['memory', 'profile', 'skill', 'experience'],
    limit: 10,
    tokenBudget: 2000
});

Record Management and Batch Forgetting

Single-record get / list / update / delete; scoped deletion deleteMany is bounded paginated — hasMore=true must continue paginating and check failed items one by one; a single HTTP success does not mean the whole range has been deleted.

const one = await memory.get({ memoryId: '<memoryId>' });
const page = await memory.list({ userId: 'user-123', limit: 25 });
await memory.update({
    memoryId: one.memory.memoryId, version: one.memory.version,
    content: '更新后的事实'
});
await memory.delete({ memoryId: one.memory.memoryId });

// Use only when the business has confirmed that all memory of this user should be forgotten.
let res;
do {
    res = await memory.deleteMany({ userId: 'user-123', limit: 100 });
    if (res.failed > 0) throw new Error('存在失败项,请检查 res.items 后处理');
} while (res.hasMore); // No cursor; continue with the same scope; per-item failures cannot be ignored.

Import and Export

After an import or export is created, query it by its respective identifier; do not treat acceptance as completion. The import example below uses dryRun=true, which only validates and does not write.

const exported = await memory.createExport({ userId: 'user-123', mode: 'async' });
const progress = await memory.getExportJob({ exportId: exported.exportId });
// Query repeatedly until progress.job.status reaches a final state, then check job.result / manifestUrl.
const imported = await memory.createImport({
    userId: 'user-123', format: 'json', dryRun: true,
    records: [{ userId: 'user-123', scope: 'user', memoryType: 'preference',
        recordKind: 'fact', content: '用户喜欢拿铁咖啡。' }]
});
const importProgress = await memory.getImport({ importId: imported.importId });
// Check job.status and per-item results; before the formal import, change dryRun to false and use a new logical idempotency key.

Profile and Distillation

Profile extraction must pass new messages; replace is no exception. Distillation must pass a valid source or inline evidence; the example below uses an inline conversation. On first integration, submit profile extraction first; wait for completion before reading while queued, and getProfile may return 404 when the profile has not been generated yet. Reading, source queries, and rebuilds are independent operations, given below as comments to run as needed. Set MEMORY_DISTILLATION_OPERATION_ID to identify one distillation; keep that value when retrying.

await memory.createProfileExtraction({
    userId: 'user-123', mode: 'incremental',
    messages: [{ role: 'user', content: '我喜欢简洁的技术说明。' }]
});
// Runs independently after extraction completes:
// const profile = await memory.getProfile({ userId: 'user-123' });
// const sources = await memory.listProfileSources({ userId: 'user-123' });
// await memory.createProfileRebuild({ userId: 'user-123' });
const operationId = process.env.MEMORY_DISTILLATION_OPERATION_ID;
if (!operationId) throw new Error('请设置 MEMORY_DISTILLATION_OPERATION_ID');
client.addHeader('Idempotency-Key', operationId);
const submitted = await memory.submitDistillation({
    scope: 'user', userId: 'user-123', mode: 'async',
    messages: [{ role: 'assistant', content: '请求限流时读取 Retry-After,退避后用原幂等键重试。' },
        { role: 'user', content: '按此方法重试成功了。' }]
});
const dist = await memory.getDistillation({
    distillationId: submitted.distillationId, scope: 'user', userId: 'user-123'
});
// Keep querying dist.distillation.status and check counts, outputs, and manual confirmation status.

Skill / Experience / Context Dreaming and Self-Evolution Approval

Skills and experience use knowledgeId; context management uses hierarchical aggregation (Dreaming: createContextRun, confirmContext, rebuildContext, rollbackContext). Candidate experiences/skills produced by distillation are approved via /v1/memory/memories/knowledge/reviews/{reviewId} (approve / reject) or rolled back by revision comparison (/revisions, /diff, /rollback); the Ebbinghaus forgetting pipeline previews single-user forgetting results via POST /v1/memory/pipelines/{id}/validate (dryRun: true). The management calls in the examples below require administrative access capability.

const skills = await memory.listSkills({ userId: 'user-123' });
const found = await memory.searchSkills({ query: '周报排版', userId: 'user-123' });
const exps = await memory.listExperiences({ userId: 'user-123' });
const expHits = await memory.searchExperiences({ query: '投放复盘', userId: 'user-123' });

// 1. Trigger hierarchical context Dreaming and read the status
await memory.createContextRun({ scope: 'user', userId: 'user-123' });
const ctxStatus = await memory.getContextStatus({ scope: 'user', userId: 'user-123' });
const ctx = await memory.getContext({ contextId: '<contextId>', scope: 'user', userId: 'user-123' });
// Choose from the following independent actions as needed; targetRevision is the historical revision selected after business verification.
// await memory.confirmContext({ contextId: '<contextId>', expectedVersion: ctx.context.version, reason: 'Sources verified', scope: 'user', userId: 'user-123' });
// await memory.rollbackContext({ contextId: '<contextId>', expectedVersion: ctx.context.version, targetRevision, reason: 'Roll back to verified revision', scope: 'user', userId: 'user-123' });
// await memory.rebuildContext({ contextId: '<contextId>', reason: 'Re-aggregate', scope: 'user', userId: 'user-123' });

// 2. Self-evolution approvals (approve / reject), knowledge revision rollback, and single-user Dry-run validation of the Ebbinghaus forgetting pipeline (access management-plane endpoints via the underlying client.call)
// await client.call('post', new URL(`${endpoint}/memory/memories/knowledge/reviews/<reviewId>/approve`), { 'content-type': 'application/json' }, { expectedVersion: 1, reason: 'SRE review passed' });
// await client.call('post', new URL(`${endpoint}/memory/memories/knowledge/<knowledgeId>/rollback`), { 'content-type': 'application/json' }, { scope: 'user', userId: 'user-123', expectedVersion: 5, targetRevision: 3, reason: 'Rollback to stable revision' });
// await client.call('post', new URL(`${endpoint}/memory/pipelines/pipe_forgetting_01/validate`), { 'content-type': 'application/json' }, { dryRun: true, sampleUserId: 'user_zhangwei_001', simulatedDays: 14 });

Applicable Versions

The complete Node.js flow uses agentbase-node-sdk@2.9.0; the server-side flow applies to Agentbase 2.10.0. Other languages follow each operation card's SDK integration approach; see SDK integration for installation and version selection.