Java 示例
Java Server SDK 与 Console SDK 以 ZIP 交付包发布(不发布到 Maven Central/内部 registry),托管在 agentbase-sdks release v2.12.0:
下载地址:<https://code.alipay.com/obai/agentbase-sdks/releases/v2.12.0>
制品:Server SDK ZIP、Console SDK ZIP 与
SHA256SUMS校验文件运行时:Java 11 source/target(可跑 OpenJDK 11/17);transport 为 OkHttp(解包目录的
lib/携带运行时依赖,直接用 JAR 时必须连lib/一起分发)
获取与校验
# 1. 下载 ZIP 与校验文件(curl 或浏览器)
curl -LO <release 页面中的 Server SDK ZIP 地址>
curl -LO <release 页面中的 Console SDK ZIP 地址>
curl -LO <release 页面中的 SHA256SUMS 地址>
# 2. 校验完整性
sha256sum -c SHA256SUMS --ignore-missing
unzip agentbase-java-sdk-2.12.0.zip && unzip agentbase-console-java-sdk-2.12.0.zip
# 解包目录内如再有 SHA256SUMS,进入后再次 sha256sum -c SHA256SUMS
# 3. 安装到本地 Maven 仓库(或确认团队仓库已提供同 GAV)
mvn install:install-file -Dfile=agentbase-java-sdk-2.12.0.jar -DpomFile=agentbase-java-sdk-2.12.0.pom
mvn install:install-file -Dfile=agentbase-console-java-sdk-2.12.0.jar -DpomFile=agentbase-console-java-sdk-2.12.0.pomZIP 与 JAR 的确切文件名以 release v2.12.0 页面实际资产为准;不要凭记忆拼文件名。
依赖声明(maven.compiler.release 11+):
<dependency>
<groupId>io.agentbase</groupId>
<artifactId>agentbase-java-sdk</artifactId>
<version>2.12.0</version>
</dependency>
<dependency>
<groupId>io.agentbase.console</groupId>
<artifactId>agentbase-console-java-sdk</artifactId>
<version>2.12.0</version>
</dependency>Server SDK 初始化
import io.agentbase.Client;
import io.agentbase.services.TablesDB;
import io.agentbase.Query;
import io.agentbase.ID;
Client client = new Client()
.setEndpoint(System.getenv("APPBASE_ENDPOINT")) // https://appbuild.oceanbase.com/v1
.setProject(System.getenv("APPBASE_PROJECT_ID"))
.setKey(System.getenv("APPBASE_API_KEY")); // 最小 scope 的项目 API Key
client.setHttpClient(new okhttp3.OkHttpClient.Builder()
.followRedirects(false).followSslRedirects(false).build());
TablesDB tables = new TablesDB(client); // 服务逐个构造Console SDK 初始化
import io.agentbase.console.Client;
import io.agentbase.console.services.Projects;
Client consoleClient = new Client()
.setEndpoint(System.getenv("APPBASE_ENDPOINT")) // 包含 /v1
.setProject("console")
.setCookie(System.getenv("APPBASE_SESSION_COOKIE")); // 完整 Cookie header 值
// 短期 Console JWT 可替代 Cookie;不要同时装载多种凭据。
// consoleClient.setJWT(System.getenv("APPBASE_CONSOLE_JWT"));同 classpath 并用:两个 SDK 的 Client 同名、namespace 独立(io.agentbase.Client vs io.agentbase.console.Client)。同一个 Java 文件只 import 一个,另一个用全限定类名;两边的 model / enum / service 禁止混用。
管理面调用仍受组织成员角色约束;普通项目 API Key 不能替代 Console Session/JWT。认证和治理方法差异见 Console Java SDK。
TablesDB(建库表、行、查询)
import io.agentbase.models.DatabaseColumnDefinition;
import io.agentbase.models.DatabaseIndexDefinition;
import io.agentbase.enums.DatabaseSchemaType;
import io.agentbase.enums.DatabaseSchemaIndexType;
import java.util.List;
import java.util.Map;
tables.create("app-db", "App", true); // enabled
tables.createTable(
"app-db", "tasks", "Tasks",
null, // permissions
true, // rowSecurity
true, // enabled
List.of(new DatabaseColumnDefinition()
.setKey("title").setType(DatabaseSchemaType.VARCHAR)
.setSize(256L).setRequired(true),
new DatabaseColumnDefinition()
.setKey("done").setType(DatabaseSchemaType.BOOLEAN).setRequired(true)),
List.of(new DatabaseIndexDefinition()
.setKey("title_idx").setType(DatabaseSchemaIndexType.KEY)
.setAttributes(List.of("title"))),
null // comment
);
tables.createRow("app-db", "tasks", ID.unique(),
Map.of("title", "写周报", "done", false), null, null);
var rows = tables.listRows("app-db", "tasks",
List.of(Query.equal("done", false), Query.orderDesc("$createdAt"), Query.limit(25)),
null, true, null);Storage / Functions
import io.agentbase.ID;
import io.agentbase.enums.ExecutionMethod;
import io.agentbase.models.Execution;
import io.agentbase.models.InputFile;
import io.agentbase.services.Functions;
import io.agentbase.services.Storage;
Storage storage = new Storage(client);
storage.createBucket("attachments", "附件", null, true, true,
26214400L, null, null, true, false, true, false); // clientFileListing=false,客户端不能列举
storage.createFile("attachments", ID.unique(),
InputFile.fromPath(java.nio.file.Paths.get("./report.pdf")), null, null); // permissions, onProgress
Functions functions = new Functions(client);
Execution exec = functions.createExecution("send-mailer",
"{\"to\":\"a@b.c\"}", true, "/", ExecutionMethod.POST, null, null);
Execution current = functions.getExecution(exec.getFunctionId(), exec.getId());
// async=true:按间隔重复查询,直到状态为 COMPLETED 或 FAILED。Sites(位置参数全集,绝大多数可空)
import io.agentbase.enums.Adapter;
import io.agentbase.enums.BuildRuntime;
import io.agentbase.enums.Framework;
import io.agentbase.services.Sites;
Sites sites = new Sites(client);
sites.create("portal", "用户门户", Framework.REACT, BuildRuntime.NODE_22,
true, true, 30L,
"npm install", "npm run build", "", "dist",
Adapter.STATIC,
null, "index.html", // installationId, fallbackFile(SPA 必备)
null, null, false, null, // VCS 相关
null, null, null, null, null); // 规格/执行计划/保留期,见 listSpecifications()
// 部署:sites.createDeployment(siteId, code, activate, ...) 后轮询 getDeployment;
// 用本次 deploymentId 经 Proxy 规则解析预览 URLCustom Token(服务端签发 → 客户端换 Session)
Users users = new Users(client);
Token token = users.createToken("<userId>", null, null); // { secret, expire }
// 浏览器端用 Client SDK:account.createSession({ userId, secret: token.secret })Memory / Knowledge Bases
Memory memory = new Memory(client);
memory.create(userId, io.agentbase.enums.MemoryScope.USER, "preference",
io.agentbase.enums.RecordKind.FACT,
null, // pipelineId
"我喜欢简洁的回复", null, // content, messages
null, // media
null, null, null, // agentId, runId, sessionId
null, null, null, null, // sensitivity, handlingPolicy, metadata, sourceContext
false, null, false); // infer, reRemember, async
// 确定性直写;模型提取使用 infer=true,并检查异步结果。
KnowledgeBases kb = new KnowledgeBases(client);
KnowledgeBase base = kb.create(ID.unique(), "产品手册", "text-embedding-v3",
null, null, null, null, null, null, null, null, null); // description through tracingEnabled
kb.createIngestion(base.getId(), docId, null, null, null, null, null); // 异步:轮询 getIngestionLLM Gateway / AI Gateway / Observability / Moderation
LlmGateway llm = new LlmGateway(client);
Object chat = llm.createChatCompletion(
"qwen-max",
List.of(Map.of("role", "user", "content", "用一句话介绍 TablesDB")),
0.2, 300L, false, null, null);
AiGateway aiGateway = new AiGateway(client);
aiGateway.listKeys(); // Consumer/Policy/Target/Tool 控制面同名方法见源码
// 工具数据面走 HTTP:/ai-gateway/g/{gatewayId}/mcp | /a2a/{targetSlug};模型调用使用 LLM Gateway
// 项目级智能体工作台(/v1/agent-runtime/project/*)通过 Project API Key(agent-runtime.project)+ userId 接入,完整示例见 ../agent-runtime.md
Observability observability = new Observability(client);
observability.createIngestion(
List.of(Map.of(
"id", java.util.UUID.randomUUID().toString(), // 外层幂等 ID
"timestamp", java.time.Instant.now().toString(),
"type", "trace-create",
"body", Map.of("id", traceId32Hex, "name", "agent-run"))),
null);
// 全部成功 HTTP 200;部分失败 HTTP 207 —— 逐项检查 errors[],不能只看是否抛异常
Moderation moderation = new Moderation(client);
moderation.createConfig(ResourceType.COLLECTIONS, "tasks", Mode.PRE,
List.of("text"), "app-db", true, null); // requireManualReviewOnViolation 仅用于 post/hybridWebhooks / Console 用量
Webhooks webhooks = new Webhooks(client);
webhooks.create(ID.unique(), "https://example.com/hook", "notify",
List.of("databases.*.tables.*.rows.*.create"), true, true, null, null);
// 三级用量(最近 30 个 UTC 日):Java Console SDK 生成名是 getUsageAggregates
new io.agentbase.console.services.Projects(consoleClient)
.getUsageAggregates("<projectId>");
// 旧口径 /project/usage 需要业务项目上下文,见 Console Java SDK“用量查询”示例。错误处理与类型
try {
tables.getRow("app-db", "tasks", rowId, null, null);
} catch (io.agentbase.exceptions.AgentbaseException e) {
System.err.println("HTTP " + e.getCode() + " type=" + e.getType() + " msg=" + e.getMessage());
// 413 存储超限 / 429 限频 / 401·403 认证或 scope
}方法默认返回类型化 model 或 Map<String,Object>;自定义 POJO 用 new TypeToken<MyPojo>(){}.getType() 重载。Java Console SDK 没有 Sql 服务(SQL 走 HTTP 形态或 JS Console SDK)。项目配额和限频则提供 typed 的 Projects.getQuotaLimits / updateQuotaLimits / getLimits / updateLimits / deleteLimits;初始化与调用见 Console Java,字段语义见 限额与配额。