Docs
文档目录

JavaScript 示例

示例中的 <APPBASE_ENDPOINT_WITH_V1>、<APPBASE_CONSOLE_ORIGIN> 和 <APPBASE_CONSOLE_HOST> 均需按实际使用位置替换为目标环境信息;先确认环境再运行。

本文给出 2.12.0 三个 JavaScript SDK 的初始化与各功能点真实调用写法。版本一律精确钉:agentbase-web-sdk@2.12.0(浏览器)、agentbase-node-sdk@2.12.0(服务端)、agentbase-console-sdk@2.12.0(管理面)。禁止 latest、^、~ 或替代包。

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

通用约定:endpoint = 环境基址 + /v1(SIT https://appbuild-sit.oceanbase.com/v1,生产 https://appbuild.oceanbase.com/v1,自托管 http(s)://<host>[:port]/v1);region 固定 'default'。

客户端 SDK(Web)初始化

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

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

const account = new Account(client);

// 邮箱密码注册 + 登录
await account.create({ userId: ID.unique(), email, password, name });
await account.createEmailPasswordSession({ email, password });
const me = await account.get();

// 匿名登录
await account.createAnonymousSession();

// 读取当前账号自己的 quota(Client SDK 仅提供账号级,不管理项目 quota)
const accountQuota = await account.getQuotaLimits();

// 注销当前会话
await account.deleteSession('current');

浏览器安全边界:只放用户 Session,不放项目 API Key、Gateway Key、上游 Provider 密钥。

Server SDK(Node)初始化

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);   // 只存服务端
{
  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 初始化

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

// 控制台级(组织/项目治理)
sdk.forConsole.projects.list([]);

// 项目资源面(自动 setProject + setMode('admin'))
const proj = sdk.forProject('default', '<projectId>');
await proj.tablesDB.listRows('<databaseId>', '<tableId>', []);

// 裸 Client + 邮箱密码 Session(Console-only 操作前)
const client = new Client()
  .setEndpoint('<APPBASE_ENDPOINT_WITH_V1>')
  .setProject('<consoleProjectId>');           // 常为 'console'
// 登录后装载 cookie:client.setCookie(cookieFromLoginResponse)
// 短期 JWT 场景:client.setJWT(token)
// SQL 场景:client.setProject('<应用项目ID>').setKey('<项目APIKey>')

TablesDB(建库、建表、行、事务、聚合)

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),
]);

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

// 事务批量(事务是项目级对象;操作里带 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(桶与文件)

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'),   // 或 new File([blob], 'report.pdf')
});
const fileBytes = await storage.getFileDownload({ bucketId: 'attachments', fileId: '<fileId>' }); // ArrayBuffer

Functions(部署与执行)

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'),  // 源码包,排除 node_modules/.env
  activate: true,
});

const exec = await functions.createExecution({
  functionId: 'send-mailer',
  body: JSON.stringify({ to: 'a@b.c' }),
  async: false,                                // 同步受约 30s 上限;长任务 true + 轮询
});

Realtime(浏览器订阅)

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

const realtime = new Realtime(client);
const sub = await realtime.subscribe(
  [
    Channel.tablesdb('app-db').table('tasks').row(),  // 全部行;.row('<rowId>') 为单行
    Channel.files(),                                  // 文件变化
    Channel.account(),                                // 当前账号事件
  ],
  (event) => console.log(event.type, event.data),
);
// 原地调整订阅
await sub.update({ channels: [Channel.tablesdb('app-db').table('tasks').row('<rowId>')] });
await sub.unsubscribe();          // 单订阅拆卸
Realtime.disconnect();            // 关闭整个连接

Memory(记忆写入与召回)

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,  // 先完成直接写入;模型提取另用异步任务查询
});
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
});

从项目准备到更新、删除及异步提取的完整流程见Memory SDK 指南与记忆操作。

Knowledge Bases(RAG 摄取与检索)

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 });   // 异步:轮询 kb.getIngestion

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

浏览器端(agentbase-web-sdk)可为当前用户创建/查询语雀 OAuth 会话,并导入已授权的语雀个人文档 URL;知识库检索、Wiki、GraphRAG 与索引治理示例使用服务端 SDK。

Knowledge Wiki(页面与索引治理,2.7.0)

import { KnowledgeBases, Capability, Kind, PageType, Mode } from 'agentbase-node-sdk';
const kb = new KnowledgeBases(client);   // Server SDK;Web 无 Wiki/GraphRAG/索引治理面

// 能力配置与异步构建(稳定幂等键;轮询终态 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,完整替换
});
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 页面:写操作携带 contentRevision 做乐观并发
const page = await kb.createWikiPage({
  knowledgeBaseId: base.$id,
  slug: 'refund-policy',
  title: '退款政策',
  pageType: PageType.Topic,
  contentMd: '# 退款政策\n\n详见 [[order-lifecycle]]。',   // [[slug]] 链接自动抽取
});
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;恢复写成新 revision
});

// 以下是两种独立的写入场景,按实际情况选择;每次写入前重新读取当前页面 revision。
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>',
});

// 查询与图谱浏览
await kb.createWikiQuery({ knowledgeBaseIds: [base.$id], query: '退款流程是什么?', mode: Mode.Auto, topK: 5 });
await kb.createWikiProjectSearch({ query: '退款流程是什么?' });   // 项目内全部可见库
await kb.getWikiGraph({ knowledgeBaseId: base.$id });              // Wiki 页面链接图(红链 redLink=true)
await kb.getGraph({ knowledgeBaseId: base.$id, seed: '<entityId>', hops: 2, limit: 50 });   // GraphRAG 有界快照

// 维护:推荐上限 / 导出 Memory / clear(留 canonical)与 reset(删 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' });

逐方法签名与 Java / Python / Go / REST 写法见 knowledge-base/wiki.md。

LLM Gateway(执行与密钥)

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

// 执行面:OpenAI 兼容
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 });

// 管理面:签发 Gateway Key(明文只在响应出现一次)
const key = await llmGateway.createKey({
  keyId: ID.unique(),
  name: 'frontend',
  allowedModels: ['qwen-max'],
});

AI Gateway(2.6.0 新数据面控制面)

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: [] });
// 其余控制面方法(Policy/Snapshot/Target/Tool/Invocation 系列)同名见 SDK 类型定义
// 工具数据面走 HTTP:/ai-gateway/g/{gatewayId}/mcp | /a2a/{targetSlug};模型调用使用 LLM Gateway

Agent Runtime(项目级智能体工作台)

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

// 业务后端使用 Project API Key(含 agent-runtime.project Scope)接入当前项目的智能体工作台
const endpoint = process.env.APPWRITE_ENDPOINT; // 例如 https://appbuild-sit.oceanbase.com/v1
const projectId = process.env.APPWRITE_PROJECT_ID; // 例如 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. 幂等初始化项目智能体工作台并更新运行配置(项目共享接口不传 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. 用户级会话与异步 Run(POST 请求在 JSON Body 传 userId,GET/DELETE 在 URL Query 传 userId)
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. 订阅可恢复 SSE 事件流(断线重连携带 Last-Event-ID);取消须显式调用 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' } }
);

项目级智能体工作台完整接口(词库绑定 /project/lexicons、Gateway 绑定 /project/gateway、Skill 包上传 /project/skills、Client Tool 回传 /runs/{runId}/tool-messages)见 agent-runtime.md。

Observability(上报与 207 处理)

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

const res = await observability.createIngestion({
  batch: [{
    id: crypto.randomUUID(),            // 外层幂等 ID
    timestamp: new Date().toISOString(),
    type: 'trace-create',
    body: { id: traceId32Hex, name: 'agent-run' },
  }],
});
// 全部成功 HTTP 200;部分失败 HTTP 207 —— 响应体携带逐项 errors[],必须逐项检查,不能只看是否抛错
if (res.errors?.length) {
  for (const item of res.errors) console.error(item);
}

// Trace 日志(独立 scope traceLogs.read;时间窗 ≤24h)
const logs = await observability.listLogs({ query: `executionId:${execId}`, limit: 50 });

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 专有)

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(部署序列)

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',       // 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 });
// 轮询 sites.getDeployment 直至 status === 'ready';用本次 deploymentId 经 Proxy 规则解析 URL

Custom Token(服务端签发 → 客户端换 Session)

// 服务端
const token = await new Users(client).createToken('<userId>');   // { secret, expire }
// 浏览器
await account.createSession({ userId: '<userId>', secret: token.secret });

配额与用量

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;不要使用项目 API Key

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

// 项目配额由 Console SDK 提供;Server SDK 的 Projects 没有这两个方法
await projects.getQuotaLimits({ projectId: '<projectId>' });
await projects.updateQuotaLimits({ projectId: '<projectId>', tablesPerProject: 120 });

// 三级用量(Console SDK,最近 30 个 UTC 日;quantity=null 表示缺失,不要转 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();

错误处理统一捕获 AgentbaseException(e.code HTTP 状态、e.type 错误类型),常见码见 troubleshooting.md。