JavaScript 示例
本文给出 2.6.0 三个 JavaScript SDK 的初始化与各功能点真实调用写法。版本一律精确钉:agentbase-web-sdk@2.9.0(浏览器)、agentbase-node-sdk@2.9.0(服务端)、agentbase-console-sdk@2.9.0(管理面)。禁止 latest、^、~ 或替代包。
npm install agentbase-web-sdk@2.9.0 agentbase-node-sdk@2.9.0 agentbase-console-sdk@2.9.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();
// 注销当前会话
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 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('https://appbuild.oceanbase.com/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 }],
indexes: [{ key: 'title_idx', type: 'key' }],
});
await tablesDB.createRow('app-db', 'tasks', ID.unique(), { title: '写周报' });
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' } },
],
});
await tablesDB.updateTransaction({ transactionId: tx.$id, commit: true });Storage(桶与文件)
import { Storage, InputFile } from 'agentbase-node-sdk';
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')
});
await storage.getFileDownload('attachments', '<fileId>'); // → 重定向/URLFunctions(部署与执行)
import { Functions, InputFile } from 'agentbase-node-sdk';
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);
await memory.create({
messages: [{ role: 'user', content: '我喜欢简洁的回复' }],
userId: '<userId>',
scope: MemoryScope.User,
memoryType: 'long_term',
recordKind: 'fact',
infer: true, // 显式传:true 走抽取/去重,false 直写
});
const hits = await memory.search({ query: '回复偏好', userId: '<userId>', limit: 5 });
const ctx = await memory.recallKnowledge({ query: '回复偏好', limit: 10, tokenBudget: 2000 });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 会话方法,RAG 流程放服务端。
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: '退款规则与边界' },
});
await kb.restoreWikiPage({ knowledgeBaseId: base.$id, slug: 'refund-policy', revisionId: '<revisionId>', contentRevision: '<currentRevision>' });
// 提案与冲突
await kb.acceptWikiProposal({ knowledgeBaseId: base.$id, proposalId: '<proposalId>', contentRevision: '<currentRevision>' });
await kb.resolveWikiConflict({
knowledgeBaseId: base.$id, slug: '<slug>', contentRevision: '<currentRevision>',
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>'] });
// 其余控制面方法(Policy/Snapshot/Target/Tool/StandardModel/Invocation 系列)同名见 SDK 类型定义
// 数据面推理/MCP/A2A 走 HTTP:/ai-gateway/g/{gatewayId}/v1 | /mcp | /a2a/{targetSlug}Agent Runtime(2.7.0 项目级 API)
import { Client, AgentRuntime } from 'agentbase-node-sdk';
// Skill 上传用 InputFile:import { InputFile } from 'agentbase-node-sdk/file';
// 开发者面(Draft):setProject 填 Agent Version 路由标识 + Version Project API Key
const runtime = new AgentRuntime(new Client()
.setEndpoint(process.env.APPWRITE_ENDPOINT)
.setProject(process.env.AGENT_VERSION_ID)
.setKey(process.env.AGENT_VERSION_API_KEY));
// Draft 配置与发布前就绪检查(readiness 顶层 ready=true 才可发布)
await runtime.updateAgentVersionConfig({
agentVersionId: process.env.AGENT_VERSION_ID,
systemPrompt: '仅基于企业知识回答问题。',
modelId: '<modelId>',
memoryEnabled: true,
knowledgeSearchEnabled: true,
maxSteps: 12,
});
await runtime.getAgentVersionReadiness({ agentVersionId: process.env.AGENT_VERSION_ID });
// Published 调用:Thread → Run(202 JSON,不保持长连接)→ SSE(断线用最后 SSE id 续连同一 Run)
const thread = await runtime.createThread({ agentId: process.env.AGENT_ID });
const run = await runtime.createRun({
agentId: process.env.AGENT_ID,
agentVersionId: thread.agent_version_id, // Thread 返回的服务端固定 Published Version
threadId: thread.thread_id,
userMessage: '我的订单什么时候发货?',
});
const stream = await runtime.streamRunEvents({ runId: run.run_id, agentVersionId: thread.agent_version_id });
// Client Tool 回传(同一 Run;失败也回传并带 error)
await runtime.submitToolMessage({
runId: run.run_id,
agentVersionId: thread.agent_version_id,
id: '<messageId>',
role: 'tool',
toolCallId: '<toolCallId>',
content: '{"status":"shipped"}',
});
// 取消必须显式调用——SSE 断开不会取消 Run
await runtime.cancelRun({ runId: run.run_id, agentVersionId: thread.agent_version_id });浏览器端(agentbase-web-sdk)只有 Published 面(Thread/Run/SSE/消息/Tool 回传/评测),Draft 配置与 Skill 管理在服务端;组织级 Agent/Version 创建与发布走 Console(见 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, InputFile } from 'agentbase-node-sdk';
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', variableId: ID.unique(), key: 'VITE_API_BASE', value: 'https://appbuild.oceanbase.com/v1' });
const dep = await sites.createDeployment({ siteId: 'portal', code: InputFile.fromPath('./site.tar.gz'), activate: true });
// 轮询 sites.getDeployment 直至 status === 'ready';用本次 deploymentId 经 Proxy 规则解析 URLCustom Token(服务端签发 → 客户端换 Session)
// 服务端
const token = await new Users(client).createToken('<userId>'); // { secret, expire }
// 浏览器
await account.createSession({ userId: '<userId>', secret: token.secret });配额与用量
import { Projects } from 'agentbase-node-sdk';
const projects = new Projects(client);
await projects.getQuotaLimits({ projectId: '<projectId>' });
await projects.updateQuotaLimits({ projectId: '<projectId>', tablesPerProject: 120 });
// 三级用量(Console SDK,最近 30 个 UTC 日;quantity=null 表示缺失,不要转 0)
await sdk.forConsole.account.listUsageAggregates();
await sdk.forConsole.organizations.listUsageAggregates({ organizationId: '<orgId>' });
await sdk.forConsole.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。