Docs
文档目录

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

这是什么 / 何时用

Agent Runtime(智能体工作台)是 Agentbase 提供的项目级托管智能体运行引擎(/v1/agent-runtime/project/*)。业务后端无需自行在应用层维护复杂的“Prompt 组装 → 模型推理 → 工具调用 → 上下文压缩 → 流式推送”ReAct 循环:只需在当前 Project 中配置对话模型(如 qwen-plus)、系统提示词及所需能力开关(企业知识库检索 Knowledge Search、长期记忆 Memory 或托管上下文 PowerContext、项目词库 Lexicons、AI Gateway 工具与 Skill 技能包),即可通过统一的 Project API Key 为不同业务终端用户(userId)创建连续会话(Thread)、异步提交任务(Run)、订阅支持断线重连的 AG-UI 流式事件(SSE),并在客户端工具(Client Tool)场景下暂停等待回传后继续同一 Run。

典型适用场景:

前置

配置项 / 依赖规范要求与 SIT 演示坐标
API Endpointhttps://appbuild-sit.oceanbase.com/v1(项目级智能体工作台路径前缀:/v1/agent-runtime/project)
所属组织与项目组织:Agentbase 企业智能中台(69c6d1aa00062e6bb60);项目:企业智能客服与知识中台(Project ID:enterprise-ai-hub-210,Shared V2 存储模式)
认证头与最小 ScopeX-Appwrite-Project: enterprise-ai-hub-210 + X-Appwrite-Key: <APPBASE_API_KEY>;API Key 必须包含 agent-runtime.project Scope(涵盖配置管理与会话运行全套 27 个端点)
SDK 版本基线Node.js:agentbase-node-sdk@2.10.0;Python:agentbase-python-sdk==2.10.0;Java:io.agentbase:agentbase-server-java:2.10.0;Go:agentbase-go-sdk(v2.10.0)
多用户隔离参数 userId1–128 位 ASCII 字母、数字或下划线(^[A-Za-z0-9_]{1,128}$),不区分大小写(服务端统一归一化为小写),system 为保留字。14 个项目共享配置接口不传 userId;13 个用户级 Thread/Run 接口必填 userId(POST 放 JSON Body,GET / DELETE 放 URL Query)
关联项目资源(按需)对话模型:qwen-plus / qwen-turbo(Provider:dashscope-prod);向量模型:text-embedding-v3(1024 维);知识库:kb_enterprise_support;词库:lex_enterprise_synonyms、lex_support_stopwords;AI Gateway:gw_7194685489feb1e169548619(需为 Shared V2 项目且 Gateway 状态为 ACTIVE)

使用骨架

  1. 初始化项目工作台并保存运行配置:查询 /v1/agent-runtime/project 状态 → 执行幂等初始化 POST /v1/agent-runtime/project → 查询可用模型 GET .../models → 通过 PATCH .../config 配置 qwen-plus、系统提示词、上下文预算及 Memory / Knowledge Search 开关。

  2. 绑定项目词库与 AI Gateway:通过 PUT .../lexicons 挂载企业同义词库与停用词库(配置 stopIntercept: true 与合规拦截话术 stopReply);通过 PUT .../gateway 绑定活跃的 AI Gateway。

  3. 上传与管理 Skill 技能包:通过 multipart/form-data 上传含 SKILL.md 的 .zip / .tar.gz / .tgz 技能包至 /v1/agent-runtime/project/skills,供智能体按需读取标准操作流程。

  4. 为业务用户创建会话并幂等提交 Run:携带业务用户 userId(如 user_zhangwei_001)调用 POST .../threads 创建会话 → 携带 Idempotency-Key 调用 POST .../runs 提交问题(返回 202 Accepted 及 run_id)。

  5. 订阅可恢复 SSE 事件流与读取最终消息:调用 GET .../runs/{runId}/events?userId=... 实时消费 TEXT_MESSAGE_CONTENT、TOOL_CALL_* 等 AG-UI 事件并记录最新帧 id;若网络断开则携带 Last-Event-ID 续连同一 Run;收到 RUN_FINISHED 后调用 GET .../runs/{runId}/messages 读取持久化回答与知识引用。

  6. 处理 Client Tool 回传、显式取消与用量审计:当 Run 进入 WAITING_CLIENT_TOOL 时,执行本地获准工具并通过 POST .../runs/{runId}/tool-messages 回传结果恢复同一 Run;需要终止任务时显式调用 POST .../runs/{runId}/cancel;通过 GET .../model-invocations 与 GET .../context-compactions 审计 Token 消耗与上下文精简记录。

关键参数与返回

接口 / 阶段关键输入参数与位置返回结构核心字段与处理要点
更新配置 PATCH /project/configBody(无 userId):system_prompt、model_id、model_parameters(temperature/top_p)、context_window_tokens、reserved_output_tokens、max_steps、max_duration_ms、memory_enabled、powercontext_enabled(与 Memory 互斥)、knowledge_search_enabled、knowledge_base_ids(最多 100 个 ID)、memory_embedding_model_id、memory_embedding_dimensions。返回完整 Config 对象与只读 config_hash。Run 受理时冻结当次配置快照,修改配置不影响在途 Run。
绑定词库 PUT /project/lexiconsBody(无 userId):bindings: [{ lexiconId, priority }](最多 100 项)、enabled: boolean、stopIntercept: boolean、stopReply: string(最长 4096 字符)。返回生效的 LexiconBindings。开启 stopIntercept 后,用户输入命中 stop 词条将短路终止 Run 并直接返回 stopReply。
上传 Skill POST /project/skillsmultipart/form-data(无 userId):二进制文件字段 file(.zip / .tar.gz / .tgz,<= 10 MiB,根目录含 SKILL.md)。201 Created,返回 skill_id、name、description、front_matter、content_hash。列表接口另返回 skill_count 与 skill_limit。
创建会话 POST /project/threadsBody:{ "userId": "user_zhangwei_001" }。201 Created,返回 thread_id、title(初始 null)、status: "ACTIVE"。后续所有对该 Thread 的操作必须使用相同 userId。
创建 Run POST /project/runsHeader:Idempotency-Key(1–128 bytes);Body:{ "userId", "thread_id", "user_message" }。首次受理返回 202 Accepted(run_id、status: "QUEUED"、created_at);同幂等键同请求体重放返回 200 OK 且 idempotent_replay: true。
SSE 事件流 GET /project/runs/{runId}/eventsQuery:userId;Header:Accept: text/event-stream、重连时带 Last-Event-ID。每帧含外层 id、event 与 data(JSON,含 type、messageId/toolCallId、delta 等)。外层 id 用于 Last-Event-ID 续连,不可与消息序号 message_seq 混用。
回传工具结果 POST /project/runs/{runId}/tool-messagesBody:{ "userId", "id", "role": "tool", "toolCallId", "content", "error" }(error 可选),其中 content 必须是 JSON 序列化后的字符串(如 "{\"status\":\"shipped\"}")。202 Accepted,返回 Run(状态回到 QUEUED 继续执行同一 Run,不会新建第二个 Run)。
消息分页 GET .../messagesQuery:userId、after(默认 0,传入上一页最后一条的 message_seq)、limit(默认 100,1–1000)。返回 Message[] 数组(message_id、message_seq、message_type、payload、tool_call_id、trace_id)。

错误与边界

SDK 类别差异

SDK 类别与语言面项目级智能体工作台(/v1/agent-runtime/project/*)接入方式
Node.js Server SDK(server-sdk/nodejs.md)初始化 agentbase-node-sdk@2.10.0 的 Client(设置 Endpoint、Project ID enterprise-ai-hub-210 与含 agent-runtime.project 的 API Key),复用项目认证头通过原生 fetch / Web Streams 调用 /v1/agent-runtime/project/* 全量 27 个端点与可恢复 SSE 流。
Java / Python / Go Server SDK(server-sdk/java.md、server-sdk/python.md、server-sdk/go.md)与 Node.js 相同,在受控服务端持有 Project API Key,通过标准 HTTP/SSE 客户端携带 X-Appwrite-Project、X-Appwrite-Key 与业务 userId 接入项目级智能体工作台。
Web Client SDK(client-sdk/web.md)浏览器前端不得持有 Project API Key,也不直接调用 /v1/agent-runtime/project/*;前端通过业务后端封装的接口发起提问并消费后端转发的 SSE 事件流。
Console SDK(console-sdk/nodejs.md)用于创建项目与签发包含 agent-runtime.project Scope 的 Project API Key。

各语言调用示例

每个卡片可切换语言页签(全页同步),卡片与「使用骨架」逐条对应。

1. 初始化项目工作台并保存运行配置

初始化项目智能体工作台(POST /v1/agent-runtime/project),查询可用模型(GET .../models),并通过 PATCH .../config 配置 qwen-plus、系统提示词、上下文窗口预算以及启用 Memory 与企业知识库检索(kb_enterprise_support)。项目配置接口无需传入 userId。

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

const ENDPOINT = process.env.APPBASE_ENDPOINT ?? 'https://appbuild-sit.oceanbase.com/v1';
const PROJECT_ID = process.env.APPBASE_PROJECT_ID ?? 'enterprise-ai-hub-210';
const API_KEY = process.env.APPBASE_API_KEY!; // 具备 agent-runtime.project Scope

// Server SDK Client 统一管理项目坐标,同时构造项目级 Runtime 请求头
const client = new Client()
    .setEndpoint(ENDPOINT)
    .setProject(PROJECT_ID)
    .setKey(API_KEY);

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

// 1. 幂等初始化项目 Agent Runtime(重复调用不会清空已有数据)
await fetch(`${ENDPOINT}/agent-runtime/project`, {
    method: 'POST',
    headers,
    body: JSON.stringify({}),
});

// 2. 列出当前项目可用模型(确认 qwen-plus 具备 chat 能力)
const modelsRes = await fetch(`${ENDPOINT}/agent-runtime/project/models`, { headers });
const { models } = await modelsRes.json();

// 3. 稀疏更新项目智能体工作台配置
const configRes = await fetch(`${ENDPOINT}/agent-runtime/project/config`, {
    method: 'PATCH',
    headers,
    body: JSON.stringify({
        system_prompt: '你是企业智能客服与知识中台助手,请优先检索企业知识库回答问题,保留引用来源。',
        model_id: 'qwen-plus',
        model_parameters: { temperature: 0.3, top_p: 0.9 },
        context_window_tokens: 32768,
        reserved_output_tokens: 2048,
        max_steps: 12,
        max_duration_ms: 120000,
        memory_enabled: true,
        powercontext_enabled: false,
        knowledge_search_enabled: true,
        knowledge_base_ids: ['kb_enterprise_support'],
        memory_embedding_model_id: 'text-embedding-v3',
        memory_embedding_dimensions: 1024,
    }),
});
const config = await configRes.json();
console.log('Saved config_hash:', config.config_hash, 'models count:', models.length);

2. 绑定项目词库与 AI Gateway

通过 PUT /v1/agent-runtime/project/lexicons 绑定同义词词库(lex_enterprise_synonyms)与停用词词库(lex_support_stopwords),开启停用词阻断(stopIntercept: true);通过 PUT /v1/agent-runtime/project/gateway 绑定活跃的 AI Gateway(gw_7194685489feb1e169548619)。

// 1. 绑定项目词库并启用停用词短路拦截
await fetch(`${ENDPOINT}/agent-runtime/project/lexicons`, {
    method: 'PUT',
    headers,
    body: JSON.stringify({
        enabled: true,
        stopIntercept: true,
        stopReply: '您好,您咨询的内容涉及企业受限或违规词条,当前请求已被拦截,请联系人工客服处理。',
        bindings: [
            { lexiconId: 'lex_enterprise_synonyms', priority: 1 },
            { lexiconId: 'lex_support_stopwords', priority: 2 },
        ],
    }),
});

// 2. 绑定同项目下状态为 ACTIVE 的 AI Gateway
await fetch(`${ENDPOINT}/agent-runtime/project/gateway`, {
    method: 'PUT',
    headers,
    body: JSON.stringify({
        gateway_id: 'gw_7194685489feb1e169548619',
    }),
});

3. 上传与管理 Skill 技能包

通过 multipart/form-data 上传包含 SKILL.md 的 .zip / .tar.gz / .tgz 技能包至 /v1/agent-runtime/project/skills,并支持列表查询、全量替换与删除。

import { readFile } from 'node:fs/promises';

const zipBytes = await readFile('./skills/enterprise-order-sop.zip');
const form = new FormData();
form.append('file', new Blob([zipBytes], { type: 'application/zip' }), 'enterprise-order-sop.zip');

// 1. 上传 Skill 包(注意:不要手动设置 Content-Type,由 FormData 自动生成 multipart boundary)
const uploadRes = await fetch(`${ENDPOINT}/agent-runtime/project/skills`, {
    method: 'POST',
    headers: {
        'X-Appwrite-Project': PROJECT_ID,
        'X-Appwrite-Key': API_KEY,
    },
    body: form,
});
const skill = await uploadRes.json();

// 2. 列出项目已上传的 Skill 包及配额(skill_count / skill_limit)
const listRes = await fetch(`${ENDPOINT}/agent-runtime/project/skills`, {
    headers: { 'X-Appwrite-Project': PROJECT_ID, 'X-Appwrite-Key': API_KEY },
});
const skillList = await listRes.json();
console.log('Uploaded skill:', skill.skill_id, 'Quota:', skillList.skill_count, '/', skillList.skill_limit);

4. 为业务用户创建会话并幂等提交 Run

为业务用户 user_zhangwei_001 创建会话(POST /v1/agent-runtime/project/threads,userId 放 JSON Body),并在该会话下携带 Idempotency-Key 异步提交 Run(POST /v1/agent-runtime/project/runs,返回 202 Accepted)。

const userId = 'user_zhangwei_001';

// 1. 为业务用户创建会话(POST 请求:userId 放在 JSON Body 中)
const threadRes = await fetch(`${ENDPOINT}/agent-runtime/project/threads`, {
    method: 'POST',
    headers,
    body: JSON.stringify({ userId }),
});
const thread = await threadRes.json(); // { thread_id, title, status: 'ACTIVE' }

// 2. 携带 Idempotency-Key 异步提交 Run(返回 202 Accepted 与 run_id)
const runRes = await fetch(`${ENDPOINT}/agent-runtime/project/runs`, {
    method: 'POST',
    headers: {
        ...headers,
        'Idempotency-Key': 'req_zhangwei_20261022_001',
    },
    body: JSON.stringify({
        userId,
        thread_id: thread.thread_id,
        user_message: '请帮我查询订单 ORD-20261022-889 的发货状态,并说明跨月退货如何处理增值税专用发票。',
    }),
});
const run = await runRes.json(); // { run_id, status: 'QUEUED', created_at }
console.log('Created thread:', thread.thread_id, 'Run queued:', run.run_id);

5. 订阅可恢复 SSE 事件流与读取最终消息

对 /v1/agent-runtime/project/runs/{runId}/events?userId=... 发起 GET(GET 请求 userId 放在 Query 中),实时解析 AG-UI 事件并保存最新外层帧 id;断线重连时携带 Last-Event-ID 续连同一 Run;收到终态事件后通过 GET .../messages 读取持久化消息。

async function consumeRunEvents(runId: string, userId: string, lastEventId?: string) {
    const eventHeaders: Record<string, string> = {
        'X-Appwrite-Project': PROJECT_ID,
        'X-Appwrite-Key': API_KEY,
        Accept: 'text/event-stream',
    };
    if (lastEventId) {
        eventHeaders['Last-Event-ID'] = lastEventId; // 断线重连时从断点续传
    }

    const res = await fetch(
        `${ENDPOINT}/agent-runtime/project/runs/${encodeURIComponent(runId)}/events?userId=${encodeURIComponent(userId)}`,
        { headers: eventHeaders }
    );
    if (res.status === 409) {
        // 游标过期(stream_cursor_expired):先读取持久化 Run 状态与消息,不要重复创建 Run
        console.warn('SSE cursor expired, falling back to persisted messages');
        return;
    }

    const reader = res.body!.pipeThrough(new TextDecoderStream()).getReader();
    let buffer = '';
    let currentId = lastEventId;

    while (true) {
        const { value, done } = await reader.read();
        if (done) break;
        buffer += value;
        const frames = buffer.split('\n\n');
        buffer = frames.pop() ?? '';
        for (const frame of frames) {
            for (const line of frame.split('\n')) {
                if (line.startsWith('id: ')) currentId = line.slice(4).trim();
                if (line.startsWith('data: ')) {
                    const event = JSON.parse(line.slice(6));
                    if (event.type === 'TEXT_MESSAGE_CONTENT') {
                        process.stdout.write(event.delta);
                    }
                }
            }
        }
    }

    // 终态后按 message_seq 游标读取持久化消息
    const msgRes = await fetch(
        `${ENDPOINT}/agent-runtime/project/runs/${encodeURIComponent(runId)}/messages?userId=${encodeURIComponent(userId)}&after=0&limit=100`,
        { headers: { 'X-Appwrite-Project': PROJECT_ID, 'X-Appwrite-Key': API_KEY } }
    );
    return { lastEventId: currentId, messages: await msgRes.json() };
}

6. 处理 Client Tool 回传、显式取消与用量审计

当 Run 进入 WAITING_CLIENT_TOOL 时,调用 POST /v1/agent-runtime/project/runs/{runId}/tool-messages 回传工具结果以恢复同一 Run;需要终止任务时调用 POST .../cancel;并通过 GET .../model-invocations 与 GET .../context-compactions 读取各步 Token 消耗与上下文精简事件。

// 1. 回传客户端工具执行结果(content 必须是 JSON 序列化字符串;失败时可传 error 字段)
await fetch(`${ENDPOINT}/agent-runtime/project/runs/${encodeURIComponent(run.run_id)}/tool-messages`, {
    method: 'POST',
    headers,
    body: JSON.stringify({
        userId,
        id: 'tmsg_01ja9x9c4d5e6f7g8h9j0k1l2m',
        role: 'tool',
        toolCallId: 'call_order_lookup_001',
        content: JSON.stringify({ order_id: 'ORD-20261022-889', status: 'shipped', carrier: 'SF-Express' }),
    }),
});

// 2. 显式取消正在执行的 Run(断开 SSE 不会取消 Run)
await fetch(`${ENDPOINT}/agent-runtime/project/runs/${encodeURIComponent(run.run_id)}/cancel`, {
    method: 'POST',
    headers,
    body: JSON.stringify({ userId }),
});

// 3. 查询单次 Run 的模型调用 Token 消耗与耗时记录(GET 请求:userId 放 Query)
const invocationsRes = await fetch(
    `${ENDPOINT}/agent-runtime/project/runs/${encodeURIComponent(run.run_id)}/model-invocations?userId=${encodeURIComponent(userId)}`,
    { headers: { 'X-Appwrite-Project': PROJECT_ID, 'X-Appwrite-Key': API_KEY } }
);
const invocations = await invocationsRes.json();

// 4. 查询会话的上下文自动精简记录
const compactionsRes = await fetch(
    `${ENDPOINT}/agent-runtime/project/threads/${encodeURIComponent(thread.thread_id)}/context-compactions?userId=${encodeURIComponent(userId)}`,
    { headers: { 'X-Appwrite-Project': PROJECT_ID, 'X-Appwrite-Key': API_KEY } }
);
const compactions = await compactionsRes.json();
console.log('Model steps:', invocations.items.length, 'Compactions:', compactions.items.length);

示例指引