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.mjsif (!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.
- Node.js (Server)
- Web (user session)
- Java
- Python
- Go
- REST (curl)
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 tabimport { Client, Memory } from 'agentbase-web-sdk'; // Prerequisite: the user is logged in
const memory = new Memory(client);
await memory.create({
messages: [{ role: 'user', content: '我习惯每天早上十一点查看早餐店经营简报' }],
userId: '<当前登录用户 ID>', // Session is limited to the user themselves; cannot target another user
scope: 'user',
memoryType: 'conversation',
recordKind: 'conversation',
infer: true // Extract facts from the conversation and deduplicate them
});import io.agentbase.enums.MemoryMessageRole;
import io.agentbase.enums.MemoryScope;
import io.agentbase.enums.RecordKind;
import io.agentbase.models.MemoryMessage;
import io.agentbase.services.Memory;
Memory memory = new Memory(client); // For client initialization, see server-sdk/java.md
memory.create("user-123", MemoryScope.USER, "conversation", RecordKind.CONVERSATION,
null, // content: choose one of content or messages (when both are passed, messages is the authoritative input for fact extraction)
List.of(new MemoryMessage(MemoryMessageRole.USER, "我习惯每天早上十一点查看早餐店经营简报")),
null, null, null, null, null, null, // agentId / runId / sessionId / sensitivity / handlingPolicy / metadata
true, // infer: extraction deduplicates facts from conversations; use false to write known facts directly
null, null); // reRemember / async
// infer=true queues asynchronously by default; for batch combined operations see the batch endpoint on the REST tabfrom agentbase.services.memory import Memory
memory = Memory(client) # Synchronous call; create returns a JSON object
memory.create(
user_id='user-123', scope='user',
memory_type='conversation', record_kind='conversation',
messages=[{'role': 'user', 'content': '我习惯每天早上十一点查看早餐店经营简报'}],
infer=True) # Extracts facts from conversations and deduplicates them; use infer=False to write a known fact directly
# infer=True enqueues asynchronously by default; batch combined operations see the batch endpoint on the REST tabimport "agentbase-go-sdk/models"
memory := agentbase.NewMemory(cl) // facade constructor; cl is a Client already loaded with an API Key
memory.Create("user-123", "user", "conversation", "conversation",
memory.WithCreateMessages([]models.MemoryMessage{{Role: "user", Content: "我习惯每天早上十一点查看早餐店经营简报"}}),
memory.WithCreateInfer(true)) // Extract facts from the conversation and deduplicate them; to write known facts directly use WithCreateInfer(false)
// infer=true queues asynchronously by default; for batch combined operations see the batch endpoint on the REST tabcurl -sS -X POST "$APPBASE_ENDPOINT/memory/memories" \
-H 'Content-Type: application/json' \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-d '{"userId":"user-123","scope":"user","memoryType":"conversation","recordKind":"conversation","messages":[{"role":"user","content":"我习惯每天早上十一点查看早餐店经营简报"}],"infer":true}'
# Returns 202 by default; when infer=true is enqueued asynchronously, poll with GET /memory/jobs/{jobId}
# Batch combined operations: POST /memory/memories/batch (items.create / items.delete / items.search mixed; scope requires the union of read, write, and delete)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.
- Node.js (Server)
- Web (user session)
- Java
- Python
- Go
- REST (curl)
// 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
});const hits = await memory.search({ query: '我的偏好', userId: '<当前登录用户 ID>', limit: 10 });
const context = await memory.recallKnowledge({
query: '我的偏好',
scope: 'user',
userId: '<当前登录用户 ID>',
limit: 10,
tokenBudget: 2000 // Returns context that fits the token budget and can be assembled directly into a Prompt
});// retrieval supports Map.of("sparse", "auto", "strategy", "progressive", "entryLevel", "auto", "maxDepth", 2, "tokenBudget", 1200, "deadlineMs", 450)
Object hits = memory.search("早餐店经营简报",
io.agentbase.enums.SearchMode.HYBRID,
Map.of("sparse", "auto", "strategy", "progressive", "entryLevel", "auto", "maxDepth", 2, "tokenBudget", 1200, "deadlineMs", 450),
"user-123",
null, null, // agentId / runId
null, "long_term", "fact", // scope / memoryType (working|short_term|long_term) / recordKind
null, 10L, null, null, null, null, null, null); // filter / limit / cursor / sort / memorySubStoreId / sessionId / groupId / accessMode
Object context = memory.recallKnowledge("用户每天什么时候查看经营简报?",
io.agentbase.enums.Scope.USER, "user-123",
null, "session-123", // agentId / sessionId (the same ID is stably reused within the same session)
null, null, // runId / memorySubStoreId
List.of(io.agentbase.enums.Kinds.MEMORY, io.agentbase.enums.Kinds.PROFILE,
io.agentbase.enums.Kinds.SKILL, io.agentbase.enums.Kinds.EXPERIENCE),
10L, 2000L, null, null); // limit / tokenBudget (returns context that fits the token budget and can be assembled into the Prompt) / retrieval / accessModehits = memory.search(
query='早餐店经营简报', user_id='user-123', limit=10,
search_mode='hybrid',
retrieval={'sparse': 'auto', 'strategy': 'progressive', 'entryLevel': 'auto', 'maxDepth': 2, 'tokenBudget': 1200, 'deadlineMs': 450},
memory_type='long_term', record_kind='fact') # memory_type: working / short_term / long_term
context = memory.recall_knowledge(
query='用户每天什么时候查看经营简报?', scope='user',
user_id='user-123', session_id='session-123', # The same ID is stably reused within the same session
kinds=['memory', 'profile', 'skill', 'experience'],
limit=10, token_budget=2000) # Returns context that fits the token budget and can be assembled directly into a Promptmemory.Search("早餐店经营简报",
memory.WithSearchSearchMode("hybrid"),
memory.WithSearchRetrieval(map[string]interface{}{
"sparse": "auto", "strategy": "progressive", "entryLevel": "auto",
"maxDepth": 2, "tokenBudget": 1200, "deadlineMs": 450,
}),
memory.WithSearchUserId("user-123"),
memory.WithSearchLimit(10),
memory.WithSearchMemoryType("long_term"), // working / short_term / long_term
memory.WithSearchRecordKind("fact"))
memory.RecallKnowledge("用户每天什么时候查看经营简报?",
memory.WithRecallKnowledgeScope("user"),
memory.WithRecallKnowledgeUserId("user-123"),
memory.WithRecallKnowledgeSessionId("session-123"), // The same ID is stably reused within the same session
memory.WithRecallKnowledgeKinds([]string{"memory", "profile", "skill", "experience"}),
memory.WithRecallKnowledgeLimit(10),
memory.WithRecallKnowledgeTokenBudget(2000)) // Returns context that fits the token budget and can be assembled directly into a Promptcurl -sS -X POST "$APPBASE_ENDPOINT/memory/memories/search" \
-H 'Content-Type: application/json' \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-d '{"query":"早餐店经营简报","searchMode":"hybrid","retrieval":{"sparse":"auto","strategy":"progressive","entryLevel":"auto","maxDepth":2,"tokenBudget":1200,"deadlineMs":450},"userId":"user-123","limit":10,"memoryType":"long_term","recordKind":"fact"}'
# recallKnowledge retrieves within the token budget (scope/userId/sessionId/kinds/limit/tokenBudget) and returns context that can be directly appended to a PromptRecord 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.
- Node.js (Server)
- Web (user session)
- Java
- Python
- Go
- REST (curl)
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.// Same data-plane subset: get / list / update / delete on one's own memory
const one = await memory.get({ memoryId: '<memoryId>' });Map<?, ?> one = (Map<?, ?>) memory.get("<memoryId>");
Map<?, ?> record = (Map<?, ?>) one.get("memory");
long version = ((Number) record.get("version")).longValue();
Object page = memory.list(null, 25L, null, null, "user-123", null);
memory.update("<memoryId>", version, "更新后的事实", null, null);
memory.delete("<memoryId>", null, null);
// Use only when the business has confirmed that all memory of this user should be forgotten.
io.agentbase.models.MemoryBulkDeleteResponse res;
do {
res = memory.deleteMany("user-123", 100L, null, null);
if (res.getFailed() > 0) throw new IllegalStateException("检查 res.getItems() 中的失败项");
} while (Boolean.TRUE.equals(res.getHasMore()));one = memory.get(memory_id='<memoryId>')
page = memory.list(user_id='user-123', limit=25)
memory.update(memory_id='<memoryId>', version=one['memory']['version'], content='更新后的事实')
memory.delete(memory_id='<memoryId>')
# Use only when the business has confirmed that all memories of this user should be forgotten. delete_many returns a typed model.
while True:
res = memory.delete_many(user_id='user-123', limit=100)
if res.failed:
raise RuntimeError('检查 res.items 中的失败项')
if not res.hasmore:
breakone, err := memory.Get("<memoryId>")
if err != nil { panic(err) }
record := (*one).(map[string]interface{})["memory"].(map[string]interface{})
version := int(record["version"].(float64)) // Number after JSON decoding
_, err = memory.Update("<memoryId>", version, memory.WithUpdateContent("更新后的事实"))
if err != nil { panic(err) }
_, err = memory.Delete("<memoryId>", memory.WithDeleteReason("user request"))
if err != nil { panic(err) }
// Use only when the business has confirmed that all memory of this user should be forgotten.
for {
res, err := memory.DeleteMany(memory.WithDeleteManyUserId("user-123"), memory.WithDeleteManyLimit(100))
if err != nil { panic(err) }
if res.Failed > 0 { panic("检查 res.Items 中的失败项") }
if !res.HasMore { break }
}curl -sS --get "$APPBASE_ENDPOINT/memory/memories" \
--data-urlencode 'userId=user-123' --data-urlencode 'limit=25' \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" -H "X-Appwrite-Key: $APPBASE_API_KEY"
# Single item: GET /memory/memories/{memoryId}; update: PATCH /memory/memories/{memoryId} (CAS version)
# Single delete: DELETE /memory/memories/{memoryId}; bounded batch forgetting: DELETE /memory/memories (pass userId/limit in the body)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.
- Node.js (Server)
- Web (user session)
- Java
- Python
- Go
- REST (curl)
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.// Export/import is a server-side capability (memories.export scope); not exposed on the Web Session surfaceMap<?, ?> exported = (Map<?, ?>) memory.createExport("user-123",
io.agentbase.enums.Format.JSON, null, null, null, io.agentbase.enums.ExportJobMode.ASYNC);
Object progress = memory.getExportJob((String) exported.get("exportId"));
String data = "[{\"userId\":\"user-123\",\"scope\":\"user\",\"memoryType\":\"preference\",\"recordKind\":\"fact\",\"content\":\"用户喜欢拿铁咖啡。\"}]";
Map<?, ?> imported = (Map<?, ?>) memory.createImport("user-123",
io.agentbase.enums.Format.JSON, data, null, true);
Object importProgress = memory.getImport((String) imported.get("importId"));
// Keep querying and check job.status and per-item results; dryRun=true does not write.exported = memory.create_export(user_id='user-123', mode='async')
progress = memory.get_export_job(export_id=exported['exportId'])
imported = memory.create_import(user_id='user-123', format='json', dry_run=True,
data='[{"userId":"user-123","scope":"user","memoryType":"preference","recordKind":"fact","content":"用户喜欢拿铁咖啡。"}]')
import_progress = memory.get_import(import_id=imported['importId'])
# Continue querying and check job.status and per-item results; dry_run=True does not write.exported, err := memory.CreateExport("user-123", memory.WithCreateExportMode("async"))
if err != nil { panic(err) }
exportID := (*exported).(map[string]interface{})["exportId"].(string)
_, err = memory.GetExportJob(exportID)
if err != nil { panic(err) }
imported, err := memory.CreateImport("user-123",
memory.WithCreateImportFormat("json"),
memory.WithCreateImportData(`[{"userId":"user-123","scope":"user","memoryType":"preference","recordKind":"fact","content":"用户喜欢拿铁咖啡。"}]`),
memory.WithCreateImportDryRun(true))
if err != nil { panic(err) }
importID := (*imported).(map[string]interface{})["importId"].(string)
_, err = memory.GetImport(importID)
if err != nil { panic(err) }
// Keep querying and check job.status and per-item results; dryRun=true does not write.curl -sS -X POST "$APPBASE_ENDPOINT/memory/memories/exports" \
-H 'Content-Type: application/json' \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" -H "X-Appwrite-Key: $APPBASE_API_KEY" \
-d '{"userId":"user-123"}'
# Task details: GET /memory/memories/exports/{exportId}; synchronous export: GET /memory/memories/export
# Import: POST /memory/memories/imports, task details GET /memory/memories/imports/{importId}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.
- Node.js (Server)
- Web (user session)
- Java
- Python
- Go
- REST (curl)
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.// Profiling/distillation are server-side management capabilities, not exposed on the Web Session planememory.createProfileExtraction("user-123", null,
List.of(new io.agentbase.models.MemoryMessage(io.agentbase.enums.MemoryMessageRole.USER, "我喜欢简洁的技术说明。")),
null, null, io.agentbase.enums.ProfileExtractionMode.INCREMENTAL);
// Runs independently after extraction completes:
// memory.getProfile("user-123", null);
// memory.listProfileSources("user-123", null);
// memory.createProfileRebuild("user-123", null);
String operationId = java.util.Objects.requireNonNull(System.getenv("MEMORY_DISTILLATION_OPERATION_ID"));
client.addHeader("Idempotency-Key", operationId);
Map<?, ?> submitted = (Map<?, ?>) memory.submitDistillation(io.agentbase.enums.Scope.USER,
"user-123", null, null, null, null, null, null,
List.of(new io.agentbase.models.DistillationMessage(io.agentbase.enums.DistillationMessageRole.ASSISTANT,
"请求限流时读取 Retry-After,退避后用原幂等键重试。")),
null, io.agentbase.enums.DistillationMode.ASYNC, null);
memory.getDistillation((String) submitted.get("distillationId"), io.agentbase.enums.Scope.USER,
"user-123", null, null, null, null);
// Keep querying distillation.status and check counts, outputs, and manual confirmation status.import os
memory.create_profile_extraction(user_id='user-123', mode='incremental',
messages=[{'role': 'user', 'content': '我喜欢简洁的技术说明。'}])
# Runs independently after extraction completes:
# memory.get_profile(user_id='user-123')
# memory.list_profile_sources(user_id='user-123')
# memory.create_profile_rebuild(user_id='user-123')
client.add_header('Idempotency-Key', os.environ['MEMORY_DISTILLATION_OPERATION_ID'])
submitted = memory.submit_distillation(scope='user', user_id='user-123', mode='async',
messages=[{'role': 'assistant', 'content': '请求限流时读取 Retry-After,退避后用原幂等键重试。'}])
dist = memory.get_distillation(distillation_id=submitted['distillationId'], scope='user', user_id='user-123')
# Continue querying dist['distillation']['status'] to check counts, outputs, and manual confirmation status._, err := memory.CreateProfileExtraction("user-123",
memory.WithCreateProfileExtractionMessages([]models.MemoryMessage{{Role: "user", Content: "我喜欢简洁的技术说明。"}}),
memory.WithCreateProfileExtractionMode("incremental"))
if err != nil { panic(err) }
// After extraction completes, call independently as needed and check error:
// memory.GetProfile("user-123")
// memory.ListProfileSources("user-123")
// memory.CreateProfileRebuild("user-123")
operationID := os.Getenv("MEMORY_DISTILLATION_OPERATION_ID") // Requires import "os"
if operationID == "" { panic("请设置 MEMORY_DISTILLATION_OPERATION_ID") }
cl.AddHeader("Idempotency-Key", operationID)
submitted, err := memory.SubmitDistillation(memory.WithSubmitDistillationScope("user"),
memory.WithSubmitDistillationUserId("user-123"), memory.WithSubmitDistillationMode("async"),
memory.WithSubmitDistillationMessages([]models.DistillationMessage{{Role: "assistant", Content: "请求限流时读取 Retry-After,退避后用原幂等键重试。"}}))
if err != nil { panic(err) }
distillationID := (*submitted).(map[string]interface{})["distillationId"].(string)
_, err = memory.GetDistillation(distillationID, memory.WithGetDistillationScope("user"), memory.WithGetDistillationUserId("user-123"))
if err != nil { panic(err) }
// Keep querying distillation.status and check counts, outputs, and manual confirmation status.# Profile: GET /memory/memories/users/{userId}/profile
curl -sS "$APPBASE_ENDPOINT/memory/memories/users/user-123/profile" \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" -H "X-Appwrite-Key: $APPBASE_API_KEY"
# Incremental/replace extraction: POST .../profile/extractions
curl -sS -X POST "$APPBASE_ENDPOINT/memory/memories/users/user-123/profile/extractions" \
-H 'Content-Type: application/json' \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" -H "X-Appwrite-Key: $APPBASE_API_KEY" \
-d '{"mode":"incremental","messages":[{"role":"user","content":"我喜欢简洁的技术说明。"}]}'
# Full rebuild: POST .../profile/rebuild; evidence sources: GET .../profile/sources
# Distillation: POST /memory/memories/distillations (scope parameters same as the Node plane); details GET /memory/memories/distillations/{distillationId};
# Replay: POST /memory/memories/distillations/{distillationId}/replaySkill / 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.
- Node.js (Server)
- Web (user session)
- Java
- Python
- Go
- REST (curl)
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 });// Read-only retrieval of skills/experience may be opened as needed (owner scope); context governance is a server-side capability, not exposed on the Web planememory.listSkills(null, "user-123", null, null, null, null, null, null);
memory.searchSkills("周报排版", null, "user-123", null, null, null, null, null, null, null);
memory.listExperiences(null, "user-123", null, null, null, null, null, null);
memory.searchExperiences("投放复盘", null, "user-123", null, null, null, null, null, null, null);
memory.createContextRun(io.agentbase.enums.Scope.USER, "user-123",
null, null, null, null); // Schedule a Dreaming run
Map<?, ?> detail = (Map<?, ?>) memory.getContext("<contextId>", io.agentbase.enums.Scope.USER, "user-123", null, null, null, null);
long version = ((Number) ((Map<?, ?>) detail.get("context")).get("version")).longValue();
// Choose from the following independent actions as needed; targetRevision is selected from verified history.
// memory.confirmContext("<contextId>", version, "source verified", io.agentbase.enums.Scope.USER, "user-123", null, null, null, null);
// memory.rollbackContext("<contextId>", version, targetRevision, "rollback to a verified revision", io.agentbase.enums.Scope.USER, "user-123", null, null, null, null);
// memory.rebuildContext("<contextId>", "re-aggregate", io.agentbase.enums.Scope.USER, "user-123", null, null, null, null);memory.list_skills(user_id='user-123')
memory.search_skills(query='周报排版', user_id='user-123')
memory.list_experiences(user_id='user-123')
memory.search_experiences(query='投放复盘', user_id='user-123')
memory.create_context_run(scope='user', user_id='user-123')
ctx = memory.get_context('<contextId>', scope='user', user_id='user-123')
# Choose the following standalone actions as needed; select target_revision from the verified history.
# memory.confirm_context('<contextId>', expected_version=ctx['context']['version'], reason='Source verified', scope='user', user_id='user-123')
# memory.rollback_context('<contextId>', expected_version=ctx['context']['version'], target_revision=target_revision, reason='Rollback to verified revision', scope='user', user_id='user-123')
# memory.rebuild_context('<contextId>', reason='Re-aggregate', scope='user', user_id='user-123')memory.ListSkills(memory.WithListSkillsUserId("user-123"))
memory.SearchSkills("周报排版", memory.WithSearchSkillsUserId("user-123"))
memory.ListExperiences(memory.WithListExperiencesUserId("user-123"))
memory.SearchExperiences("投放复盘", memory.WithSearchExperiencesUserId("user-123"))
_, err := memory.CreateContextRun(memory.WithCreateContextRunScope("user"), memory.WithCreateContextRunUserId("user-123"))
if err != nil { panic(err) }
ctx, err := memory.GetContext("<contextId>", memory.WithGetContextScope("user"), memory.WithGetContextUserId("user-123"))
if err != nil { panic(err) }
version := int((*ctx).(map[string]interface{})["context"].(map[string]interface{})["version"].(float64))
_ = version
// Choose from the following independent actions as needed; targetRevision is selected from verified history, and handle the error returned each time.
// memory.ConfirmContext("<contextId>", version, "source verified", memory.WithConfirmContextScope("user"), memory.WithConfirmContextUserId("user-123"))
// memory.RollbackContext("<contextId>", version, targetRevision, "rollback to a verified revision", memory.WithRollbackContextScope("user"), memory.WithRollbackContextUserId("user-123"))
// memory.RebuildContext("<contextId>", "re-aggregate", memory.WithRebuildContextScope("user"), memory.WithRebuildContextUserId("user-123"))# Skills: GET /memory/memories/skills; retrieval POST /memory/memories/skills/search; details/evidence sources GET .../skills/{knowledgeId}[/sources]
curl -sS -X POST "$APPBASE_ENDPOINT/memory/memories/skills/search" \
-H 'Content-Type: application/json' \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" -H "X-Appwrite-Key: $APPBASE_API_KEY" \
-d '{"query":"周报排版","userId":"user-123"}'
# Experience: GET /memory/memories/experiences; search POST .../experiences/search
# Context dreaming: GET /memory/memories/contexts; scheduling POST /memory/memories/contexts/runs;
# Confirm POST .../contexts/{contextId}/confirm; rollback .../rollback; rebuild .../rebuild; status GET .../contexts/status
# Self-evolution approval and rollback: GET/PATCH /memory/memories/knowledge/reviews/{reviewId}; POST .../approve | .../reject; GET .../knowledge/{knowledgeId}/revisions | .../diff; POST .../rollback
# Ebbinghaus forgetting pipeline dry-run preview: POST /memory/pipelines/{id}/validate {"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.