Docs
Contents

JavaScript Example

Replace <APPBASE_ENDPOINT_WITH_V1>, <APPBASE_CONSOLE_ORIGIN>, and <APPBASE_CONSOLE_HOST> where used with values for the intended environment before running the examples.

This document covers initialization and real invocation examples for each feature across the 2.12.0 JavaScript SDKs. Versions must always be pinned exactly: agentbase-web-sdk@2.12.0 (browser), agentbase-node-sdk@2.12.0 (server), agentbase-console-sdk@2.12.0 (management plane). latest, ^, ~, or substitute packages are forbidden.

npm install agentbase-web-sdk@2.12.0 agentbase-node-sdk@2.12.0 agentbase-console-sdk@2.12.0 --save-exact

Common conventions: endpoint = environment base URL + /v1 (SIT https://appbuild-sit.oceanbase.com/v1, production https://appbuild.oceanbase.com/v1, self-hosted http(s)://<host>[:port]/v1); region is fixed to 'default'.

Client SDK (Web) Initialization

import { Client, Account, ID } from 'agentbase-web-sdk';

const client = new Client()
  .setEndpoint(import.meta.env.VITE_APPWRITE_ENDPOINT)   // Includes /v1
  .setProject(import.meta.env.VITE_APPWRITE_PROJECT_ID);

const account = new Account(client);

// Email/password registration + login
await account.create({ userId: ID.unique(), email, password, name });
await account.createEmailPasswordSession({ email, password });
const me = await account.get();

// Anonymous login
await account.createAnonymousSession();

// Read the current account's own quota (the Client SDK provides account level only, does not manage project quota)
const accountQuota = await account.getQuotaLimits();

// Delete the current session
await account.deleteSession('current');

Browser security boundary: only user Sessions belong here — never project API Keys, Gateway Keys, or upstream Provider keys.

Server SDK (Node) Initialization

import { Client, TablesDB, Users, Query, ID } from 'agentbase-node-sdk';
import 'dotenv/config';

const client = new Client()
  .setEndpoint(process.env.APPWRITE_ENDPOINT)
  .setProject(process.env.APPWRITE_PROJECT_ID)
  .setKey(process.env.APPWRITE_API_KEY);   // Stored server-side only
{
  const prepareRequest = client.prepareRequest.bind(client);
  client.prepareRequest = (...args) => {
    const request = prepareRequest(...args);
    request.options.redirect = 'error';
    return request;
  };
}

const tablesDB = new TablesDB(client);

Console SDK initialization

import { sdk, realtime, Client } from 'agentbase-console-sdk';

// Console level (organization/project governance)
sdk.forConsole.projects.list([]);

// Project resource plane (automatic setProject + setMode('admin'))
const proj = sdk.forProject('default', '<projectId>');
await proj.tablesDB.listRows('<databaseId>', '<tableId>', []);

// Bare Client + email/password Session (before Console-only operations)
const client = new Client()
  .setEndpoint('<APPBASE_ENDPOINT_WITH_V1>')
  .setProject('<consoleProjectId>');           // Usually 'console'
// After login, load the cookie: client.setCookie(cookieFromLoginResponse)
// Short-lived JWT scenario: client.setJWT(token)
// SQL scenario: client.setProject('<应用项目ID>').setKey('<项目APIKey>')

TablesDB (Databases, Tables, Rows, Transactions, Aggregations)

await tablesDB.create({ databaseId: 'app-db', name: 'App' });

await tablesDB.createTable({
  databaseId: 'app-db',
  tableId: 'tasks',
  name: 'Tasks',
  rowSecurity: true,
  columns: [
    { key: 'title', type: 'varchar', size: 256, required: true },
    { key: 'done', type: 'boolean', required: true },
  ],
  indexes: [{ key: 'title_idx', type: 'key', attributes: ['title'] }],
});

await tablesDB.createRow('app-db', 'tasks', ID.unique(), { title: '写周报', done: false });

const rows = await tablesDB.listRows('app-db', 'tasks', [
  Query.equal('done', false),
  Query.orderDesc('$createdAt'),
  Query.limit(25),
]);

// Row-level aggregation
const stats = await tablesDB.aggregateRows({
  databaseId: 'app-db',
  tableId: 'tasks',
  select: ['count'],
  groupBy: ['done'],
});

// Transactional batch (a transaction is a project-level object; operations carry databaseId)
const tx = await tablesDB.createTransaction();
await tablesDB.createOperations({
  transactionId: tx.$id,
  operations: [
    { databaseId: 'app-db', tableId: 'tasks', action: 'create', rowId: ID.unique(), data: { title: 'A', done: false } },
  ],
});
await tablesDB.updateTransaction({ transactionId: tx.$id, commit: true });

Storage (Buckets and Files)

import { Storage } from 'agentbase-node-sdk';
import { InputFile } from 'agentbase-node-sdk/file';
const storage = new Storage(client);

await storage.createBucket({ bucketId: 'attachments', name: '附件', fileSecurity: true });
await storage.createFile({
  bucketId: 'attachments',
  fileId: ID.unique(),
  file: InputFile.fromPath('./report.pdf'),   // or new File([blob], 'report.pdf')
});
const fileBytes = await storage.getFileDownload({ bucketId: 'attachments', fileId: '<fileId>' }); // ArrayBuffer

Functions (Deployment and Execution)

import { Functions } from 'agentbase-node-sdk';
import { InputFile } from 'agentbase-node-sdk/file';
const functions = new Functions(client);

const dep = await functions.createDeployment({
  functionId: 'send-mailer',
  code: InputFile.fromPath('./code.tar.gz'),  // Source package, excluding node_modules/.env
  activate: true,
});

const exec = await functions.createExecution({
  functionId: 'send-mailer',
  body: JSON.stringify({ to: 'a@b.c' }),
  async: false,                                // Synchronous, capped at 30s; for long tasks use true + polling
});

Realtime (Browser Subscriptions)

import { Realtime, Channel } from 'agentbase-web-sdk';

const realtime = new Realtime(client);
const sub = await realtime.subscribe(
  [
    Channel.tablesdb('app-db').table('tasks').row(),  // All rows; .row('<rowId>') for a single row
    Channel.files(),                                  // File changed
    Channel.account(),                                // Current account events
  ],
  (event) => console.log(event.type, event.data),
);
// Adjust subscription in place
await sub.update({ channels: [Channel.tablesdb('app-db').table('tasks').row('<rowId>')] });
await sub.unsubscribe();          // Single-subscription teardown
Realtime.disconnect();            // Close the entire connection

Memory (Memory Write and Retrieval)

import { Memory, MemoryScope } from 'agentbase-node-sdk';
const memory = new Memory(client);

const created = await memory.create({
  content: '我喜欢简洁的回复',
  userId: '<userId>',
  scope: MemoryScope.User,
  memoryType: 'preference',
  recordKind: 'fact',
  infer: false, async: false,  // Complete direct writes first; query model extraction separately via async tasks
});
if (created.status !== 'completed') throw new Error('记忆未完成写入');

const hits = await memory.search({ query: '回复偏好', userId: '<userId>', limit: 5 });
const ctx = await memory.recallKnowledge({
  query: '回复偏好', scope: 'user', userId: '<userId>', limit: 10, tokenBudget: 2000
});

For the complete flow from project preparation to update, deletion, and asynchronous extraction, see the Memory SDK Guide and Memory Operations.

Knowledge Bases (RAG Ingestion and Retrieval)

import { KnowledgeBases } from 'agentbase-node-sdk';
const kb = new KnowledgeBases(client);

const base = await kb.create({ knowledgeBaseId: ID.unique(), name: '产品手册', embeddingModel: 'text-embedding-v3' });

const doc = await kb.createDocument({ knowledgeBaseId: base.$id, fileId: '<storageFileId>' });
await kb.createIngestion({ knowledgeBaseId: base.$id, documentId: doc.$id });   // Asynchronous: poll kb.getIngestion

const found = await kb.createSearch({
  knowledgeBaseId: base.$id,
  query: '退款政策是什么?',
  searchMode: 'hybrid',        // Parameter name is searchMode; vector/fulltext/hybrid
  limit: 10,
  rerank: true,
});

The browser side (agentbase-web-sdk) can create/query Yuque OAuth sessions for the current user and import authorized Yuque personal document URLs; knowledge base retrieval, Wiki, GraphRAG, and index governance examples use the Server SDK.

Knowledge Wiki (Pages and Index Governance, 2.7.0)

import { KnowledgeBases, Capability, Kind, PageType, Mode } from 'agentbase-node-sdk';
const kb = new KnowledgeBases(client);   // Server SDK; Web has no Wiki/GraphRAG/index-governance surface

// Capability configuration and async build (stable idempotency key; poll for final state succeeded/failed/cancelled/cleared)
await kb.updateIndexCapability({
  knowledgeBaseId: base.$id,
  capability: Capability.Wiki,           // graphrag / raptor / wiki
  config: { enabled: true, language: 'zh' },   // language: auto/zh/en/ja, full replacement
});
const op = await kb.createIndexOperation({
  knowledgeBaseId: base.$id,
  capability: Capability.Wiki,
  idempotencyKey: 'wiki-build-20260918-01',
  kind: Kind.Build,
});
await kb.getIndexOperation({ knowledgeBaseId: base.$id, operationId: op.$id });
// await kb.cancelIndexOperation({ knowledgeBaseId: base.$id, operationId: op.$id });

// Wiki pages: write operations carry contentRevision for optimistic concurrency
const page = await kb.createWikiPage({
  knowledgeBaseId: base.$id,
  slug: 'refund-policy',
  title: '退款政策',
  pageType: PageType.Topic,
  contentMd: '# 退款政策\n\n详见 [[order-lifecycle]]。',   // [[slug]] automatic link extraction
});
await kb.updateWikiPage({
  knowledgeBaseId: base.$id, slug: 'refund-policy',
  contentRevision: page.contentRevision,
  page: { summary: '退款规则与边界' },
});
const beforeRestore = await kb.getWikiPage({ knowledgeBaseId: base.$id, slug: 'refund-policy' });
await kb.restoreWikiPage({
  knowledgeBaseId: base.$id,
  slug: 'refund-policy',
  revisionId: '<revisionId>',
  contentRevision: beforeRestore.contentRevision,  // number; the restore is written as a new revision
});

// Below are two independent write scenarios; choose based on your actual situation; re-read the current page revision before each write.
const beforeAccept = await kb.getWikiPage({ knowledgeBaseId: base.$id, slug: '<proposalTargetSlug>' });
await kb.acceptWikiProposal({
  knowledgeBaseId: base.$id,
  proposalId: '<proposalId>',
  contentRevision: beforeAccept.contentRevision,
});

const beforeResolve = await kb.getWikiPage({ knowledgeBaseId: base.$id, slug: '<conflictPageSlug>' });
await kb.resolveWikiConflict({
  knowledgeBaseId: base.$id, slug: '<conflictPageSlug>', contentRevision: beforeResolve.contentRevision,
  resolvedConflictId: '<conflictId>', resolvedConflictOptionText: '<chosenOption>',
});

// Query and knowledge graph browsing
await kb.createWikiQuery({ knowledgeBaseIds: [base.$id], query: '退款流程是什么?', mode: Mode.Auto, topK: 5 });
await kb.createWikiProjectSearch({ query: '退款流程是什么?' });   // All visible knowledge bases within the project
await kb.getWikiGraph({ knowledgeBaseId: base.$id });              // Wiki page link graph (red links redLink=true)
await kb.getGraph({ knowledgeBaseId: base.$id, seed: '<entityId>', hops: 2, limit: 50 });   // GraphRAG bounded snapshot

// Maintenance: recommended limits / export Memory / clear (keeps canonical) and reset (deletes canonical)
await kb.getWikiRecommendedLimits({ knowledgeBaseId: base.$id, enableLlmRefine: false });
await kb.createWikiPageMemoryExport({ knowledgeBaseId: base.$id, slug: 'refund-policy', agentId: '<agentId>' });
await kb.clearIndexCapability({ knowledgeBaseId: base.$id, capability: Capability.Wiki, confirmation: 'clear:wiki', idempotencyKey: 'clear-wiki-01' });
await kb.resetWiki({ knowledgeBaseId: base.$id, confirmation: 'reset:wiki', idempotencyKey: 'reset-wiki-01' });

For per-method signatures and Java / Python / Go / REST examples, see knowledge-base/wiki.md.

LLM Gateway (Execution and Keys)

import { LlmGateway } from 'agentbase-node-sdk';
const llmGateway = new LlmGateway(client);

// Execution plane: OpenAI compatible
const chat = await llmGateway.createChatCompletion({
  model: 'qwen-max',
  messages: [{ role: 'user', content: '用一句话介绍 TablesDB' }],
  temperature: 0.2,
  maxTokens: 300,
  stream: false,
});
await llmGateway.createEmbeddings({ model: 'text-embedding-v3', input: ['文本'] });
await llmGateway.createRerank({ model: '<rerank-model>', query: 'q', documents: ['d1', 'd2'], topN: 3 });

// Management plane: issue a Gateway Key (plaintext appears only once in the response)
const key = await llmGateway.createKey({
  keyId: ID.unique(),
  name: 'frontend',
  allowedModels: ['qwen-max'],
});

AI Gateway (2.6.0 New Data Plane and Control Plane)

import { AiGateway } from 'agentbase-node-sdk';
const aiGateway = new AiGateway(client);
await aiGateway.listKeys();
await aiGateway.createKey({ name: 'agent-consumer', gatewayIds: ['<gatewayId>'], allowedModels: [], allowedTools: ['<TOOL_ID>'], allowedAgents: [] });
// For other control-plane methods (Policy/Snapshot/Target/Tool/Invocation families), see the SDK type definitions under the same names
// Tool data plane uses HTTP: /ai-gateway/g/{gatewayId}/mcp | /a2a/{targetSlug}; use LLM Gateway for model calls

Agent Runtime (Project-Level Agent Workbench)

import { Client } from 'agentbase-node-sdk';

// The business backend uses a Project API Key (with the agent-runtime.project scope) to access the current project's agent workbench
const endpoint = process.env.APPWRITE_ENDPOINT; // e.g. https://appbuild-sit.oceanbase.com/v1
const projectId = process.env.APPWRITE_PROJECT_ID; // e.g. enterprise-ai-hub-210
const apiKey = process.env.APPWRITE_API_KEY;
const client = new Client().setEndpoint(endpoint).setProject(projectId).setKey(apiKey);
{
  const prepareRequest = client.prepareRequest.bind(client);
  client.prepareRequest = (...args) => {
    const request = prepareRequest(...args);
    request.options.redirect = 'error';
    return request;
  };
}

const headers = {
  'X-Appwrite-Project': projectId,
  'X-Appwrite-Key': apiKey,
  'Content-Type': 'application/json',
};

// 1. Idempotently initialize the project agent workbench and update the run configuration (the project-shared interface does not pass userId)
await fetch(`${endpoint}/agent-runtime/project`, { method: 'POST', headers, body: '{}' });
await fetch(`${endpoint}/agent-runtime/project/config`, {
  method: 'PATCH',
  headers,
  body: JSON.stringify({
    system_prompt: '仅基于企业知识回答问题并保留引用来源。',
    model_id: 'qwen-plus',
    memory_enabled: true,
    powercontext_enabled: false,
    knowledge_search_enabled: true,
    knowledge_base_ids: ['kb_enterprise_support'],
    max_steps: 12,
  }),
});

// 2. User-level sessions and asynchronous Runs (pass userId in the JSON Body for POST requests, and in the URL Query for GET/DELETE)
const userId = 'user_zhangwei_001';
const thread = await fetch(`${endpoint}/agent-runtime/project/threads`, {
  method: 'POST',
  headers,
  body: JSON.stringify({ userId }),
}).then((r) => r.json());

const run = await fetch(`${endpoint}/agent-runtime/project/runs`, {
  method: 'POST',
  headers: { ...headers, 'Idempotency-Key': 'order-query-20261022-01' },
  body: JSON.stringify({
    userId,
    thread_id: thread.thread_id,
    user_message: '我的订单什么时候发货?',
  }),
}).then((r) => r.json());

// 3. Subscribe to the resumable SSE event stream (include Last-Event-ID when reconnecting); cancellation requires an explicit call to POST .../cancel
const sseRes = await fetch(
  `${endpoint}/agent-runtime/project/runs/${encodeURIComponent(run.run_id)}/events?userId=${encodeURIComponent(userId)}`,
  { headers: { 'X-Appwrite-Project': projectId, 'X-Appwrite-Key': apiKey, Accept: 'text/event-stream' } }
);

For the complete project-level agent workbench interface (lexicon binding /project/lexicons, Gateway binding /project/gateway, Skill package upload /project/skills, Client Tool callback /runs/{runId}/tool-messages), see agent-runtime.md.

Observability (Reporting and 207 Handling)

import { Observability } from 'agentbase-node-sdk';
const observability = new Observability(client);

const res = await observability.createIngestion({
  batch: [{
    id: crypto.randomUUID(),            // Outer idempotency ID
    timestamp: new Date().toISOString(),
    type: 'trace-create',
    body: { id: traceId32Hex, name: 'agent-run' },
  }],
});
// All succeed: HTTP 200; partial failure: HTTP 207 — the response body carries per-item errors[]; you must check item by item, not just whether an error is thrown
if (res.errors?.length) {
  for (const item of res.errors) console.error(item);
}

// Trace logs (independent scope traceLogs.read; time window ≤24h)
const logs = await observability.listLogs({ query: `executionId:${execId}`, limit: 50 });

Moderation (Table Text Moderation)

import { Moderation, Query, ResourceType } from 'agentbase-node-sdk';
const moderation = new Moderation(client);

await moderation.createConfig({
  resourceType: ResourceType.Collections,
  resourceId: 'tasks',
  databaseId: 'app-db',
  mode: 'pre',
  contentTypes: ['text'],
  enabled: true,
});
const blocked = await moderation.listLogs({
  queries: [Query.equal('result', 'block')],
  total: true,
});

Sql (Console SDK Only)

const proj = sdk.forProject('default', '<projectId>');
const rows = await proj.sql.query({ databaseId: 'app-db', query: 'SELECT * FROM tasks LIMIT 100', params: [] });
const upd  = await proj.sql.execute({ databaseId: 'app-db', query: 'UPDATE tasks SET done = ? WHERE $id = ?', params: [true, '<rowId>'] });
// rows/upd: { columns, rows, rowCount, affectedRows, truncated }

Sites (Deployment Sequence)

import { Sites } from 'agentbase-node-sdk';
import { InputFile } from 'agentbase-node-sdk/file';
const sites = new Sites(client);

await sites.create({
  siteId: 'portal',
  name: '用户门户',
  framework: 'react',
  buildRuntime: 'node-22',
  adapter: 'static',
  fallbackFile: 'index.html',       // Required for SPA
  outputDirectory: 'dist',
  installCommand: 'npm install',
  buildCommand: 'npm run build',
});
await sites.createVariable({ siteId: 'portal', key: 'VITE_API_BASE', value: '<APPBASE_ENDPOINT_WITH_V1>' });
const dep = await sites.createDeployment({ siteId: 'portal', code: InputFile.fromPath('./site.tar.gz'), activate: true });
// Poll sites.getDeployment until status === 'ready'; resolve the URL via Proxy rules using this deploymentId

Custom Token (Server-Side Issuance → Client Session Exchange)

// Server side
const token = await new Users(client).createToken('<userId>');   // { secret, expire }
// Browser
await account.createSession({ userId: '<userId>', secret: token.secret });

Quotas and Usage

import { Client, Account, Organizations, Projects } from 'agentbase-console-sdk';

const consoleClient = new Client()
  .setEndpoint('<APPBASE_ENDPOINT_WITH_V1>')
  .setProject('<consoleProjectId>')
  .setCookie(cookieFromLoginResponse); // Console Session cookie; do not use a project API Key

const projects = new Projects(consoleClient);
const account = new Account(consoleClient);
const organizations = new Organizations(consoleClient);

// Project quota is provided by the Console SDK; the Server SDK's Projects does not have these two methods
await projects.getQuotaLimits({ projectId: '<projectId>' });
await projects.updateQuotaLimits({ projectId: '<projectId>', tablesPerProject: 120 });

// Three-level usage (Console SDK, last 30 UTC days; quantity=null means missing, do not convert to 0)
await account.listUsageAggregates();
await organizations.listUsageAggregates({ organizationId: '<orgId>' });
await projects.listUsageAggregates({ projectId: '<projectId>' });

Misc(Webhooks / Health / Locale)

import { Webhooks, Health, Locale } from 'agentbase-node-sdk';
await new Webhooks(client).create({ webhookId: ID.unique(), url: 'https://example.com/hook', name: 'notify', events: ['databases.*.tables.*.rows.*.create'], enabled: true, security: true });
await new Health(client).get();
await new Locale(client).listCountries();

For error handling, catch AgentbaseException uniformly (e.code HTTP status, e.type error type); common codes are listed in troubleshooting.md.